angular.js 1014 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294
  1. /**
  2. * @license AngularJS v1.4.1
  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.1/' +
  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 (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  382. baseExtend(dst[key], [src], true);
  383. } else {
  384. dst[key] = src;
  385. }
  386. }
  387. }
  388. setHashKey(dst, h);
  389. return dst;
  390. }
  391. /**
  392. * @ngdoc function
  393. * @name angular.extend
  394. * @module ng
  395. * @kind function
  396. *
  397. * @description
  398. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  399. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  400. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  401. *
  402. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  403. * {@link angular.merge} for this.
  404. *
  405. * @param {Object} dst Destination object.
  406. * @param {...Object} src Source object(s).
  407. * @returns {Object} Reference to `dst`.
  408. */
  409. function extend(dst) {
  410. return baseExtend(dst, slice.call(arguments, 1), false);
  411. }
  412. /**
  413. * @ngdoc function
  414. * @name angular.merge
  415. * @module ng
  416. * @kind function
  417. *
  418. * @description
  419. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  420. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  421. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  422. *
  423. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  424. * objects, performing a deep copy.
  425. *
  426. * @param {Object} dst Destination object.
  427. * @param {...Object} src Source object(s).
  428. * @returns {Object} Reference to `dst`.
  429. */
  430. function merge(dst) {
  431. return baseExtend(dst, slice.call(arguments, 1), true);
  432. }
  433. function toInt(str) {
  434. return parseInt(str, 10);
  435. }
  436. function inherit(parent, extra) {
  437. return extend(Object.create(parent), extra);
  438. }
  439. /**
  440. * @ngdoc function
  441. * @name angular.noop
  442. * @module ng
  443. * @kind function
  444. *
  445. * @description
  446. * A function that performs no operations. This function can be useful when writing code in the
  447. * functional style.
  448. ```js
  449. function foo(callback) {
  450. var result = calculateResult();
  451. (callback || angular.noop)(result);
  452. }
  453. ```
  454. */
  455. function noop() {}
  456. noop.$inject = [];
  457. /**
  458. * @ngdoc function
  459. * @name angular.identity
  460. * @module ng
  461. * @kind function
  462. *
  463. * @description
  464. * A function that returns its first argument. This function is useful when writing code in the
  465. * functional style.
  466. *
  467. ```js
  468. function transformer(transformationFn, value) {
  469. return (transformationFn || angular.identity)(value);
  470. };
  471. ```
  472. * @param {*} value to be returned.
  473. * @returns {*} the value passed in.
  474. */
  475. function identity($) {return $;}
  476. identity.$inject = [];
  477. function valueFn(value) {return function() {return value;};}
  478. /**
  479. * @ngdoc function
  480. * @name angular.isUndefined
  481. * @module ng
  482. * @kind function
  483. *
  484. * @description
  485. * Determines if a reference is undefined.
  486. *
  487. * @param {*} value Reference to check.
  488. * @returns {boolean} True if `value` is undefined.
  489. */
  490. function isUndefined(value) {return typeof value === 'undefined';}
  491. /**
  492. * @ngdoc function
  493. * @name angular.isDefined
  494. * @module ng
  495. * @kind function
  496. *
  497. * @description
  498. * Determines if a reference is defined.
  499. *
  500. * @param {*} value Reference to check.
  501. * @returns {boolean} True if `value` is defined.
  502. */
  503. function isDefined(value) {return typeof value !== 'undefined';}
  504. /**
  505. * @ngdoc function
  506. * @name angular.isObject
  507. * @module ng
  508. * @kind function
  509. *
  510. * @description
  511. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  512. * considered to be objects. Note that JavaScript arrays are objects.
  513. *
  514. * @param {*} value Reference to check.
  515. * @returns {boolean} True if `value` is an `Object` but not `null`.
  516. */
  517. function isObject(value) {
  518. // http://jsperf.com/isobject4
  519. return value !== null && typeof value === 'object';
  520. }
  521. /**
  522. * Determine if a value is an object with a null prototype
  523. *
  524. * @returns {boolean} True if `value` is an `Object` with a null prototype
  525. */
  526. function isBlankObject(value) {
  527. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  528. }
  529. /**
  530. * @ngdoc function
  531. * @name angular.isString
  532. * @module ng
  533. * @kind function
  534. *
  535. * @description
  536. * Determines if a reference is a `String`.
  537. *
  538. * @param {*} value Reference to check.
  539. * @returns {boolean} True if `value` is a `String`.
  540. */
  541. function isString(value) {return typeof value === 'string';}
  542. /**
  543. * @ngdoc function
  544. * @name angular.isNumber
  545. * @module ng
  546. * @kind function
  547. *
  548. * @description
  549. * Determines if a reference is a `Number`.
  550. *
  551. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  552. *
  553. * If you wish to exclude these then you can use the native
  554. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  555. * method.
  556. *
  557. * @param {*} value Reference to check.
  558. * @returns {boolean} True if `value` is a `Number`.
  559. */
  560. function isNumber(value) {return typeof value === 'number';}
  561. /**
  562. * @ngdoc function
  563. * @name angular.isDate
  564. * @module ng
  565. * @kind function
  566. *
  567. * @description
  568. * Determines if a value is a date.
  569. *
  570. * @param {*} value Reference to check.
  571. * @returns {boolean} True if `value` is a `Date`.
  572. */
  573. function isDate(value) {
  574. return toString.call(value) === '[object Date]';
  575. }
  576. /**
  577. * @ngdoc function
  578. * @name angular.isArray
  579. * @module ng
  580. * @kind function
  581. *
  582. * @description
  583. * Determines if a reference is an `Array`.
  584. *
  585. * @param {*} value Reference to check.
  586. * @returns {boolean} True if `value` is an `Array`.
  587. */
  588. var isArray = Array.isArray;
  589. /**
  590. * @ngdoc function
  591. * @name angular.isFunction
  592. * @module ng
  593. * @kind function
  594. *
  595. * @description
  596. * Determines if a reference is a `Function`.
  597. *
  598. * @param {*} value Reference to check.
  599. * @returns {boolean} True if `value` is a `Function`.
  600. */
  601. function isFunction(value) {return typeof value === 'function';}
  602. /**
  603. * Determines if a value is a regular expression object.
  604. *
  605. * @private
  606. * @param {*} value Reference to check.
  607. * @returns {boolean} True if `value` is a `RegExp`.
  608. */
  609. function isRegExp(value) {
  610. return toString.call(value) === '[object RegExp]';
  611. }
  612. /**
  613. * Checks if `obj` is a window object.
  614. *
  615. * @private
  616. * @param {*} obj Object to check
  617. * @returns {boolean} True if `obj` is a window obj.
  618. */
  619. function isWindow(obj) {
  620. return obj && obj.window === obj;
  621. }
  622. function isScope(obj) {
  623. return obj && obj.$evalAsync && obj.$watch;
  624. }
  625. function isFile(obj) {
  626. return toString.call(obj) === '[object File]';
  627. }
  628. function isFormData(obj) {
  629. return toString.call(obj) === '[object FormData]';
  630. }
  631. function isBlob(obj) {
  632. return toString.call(obj) === '[object Blob]';
  633. }
  634. function isBoolean(value) {
  635. return typeof value === 'boolean';
  636. }
  637. function isPromiseLike(obj) {
  638. return obj && isFunction(obj.then);
  639. }
  640. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  641. function isTypedArray(value) {
  642. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  643. }
  644. var trim = function(value) {
  645. return isString(value) ? value.trim() : value;
  646. };
  647. // Copied from:
  648. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  649. // Prereq: s is a string.
  650. var escapeForRegexp = function(s) {
  651. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  652. replace(/\x08/g, '\\x08');
  653. };
  654. /**
  655. * @ngdoc function
  656. * @name angular.isElement
  657. * @module ng
  658. * @kind function
  659. *
  660. * @description
  661. * Determines if a reference is a DOM element (or wrapped jQuery element).
  662. *
  663. * @param {*} value Reference to check.
  664. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  665. */
  666. function isElement(node) {
  667. return !!(node &&
  668. (node.nodeName // we are a direct element
  669. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  670. }
  671. /**
  672. * @param str 'key1,key2,...'
  673. * @returns {object} in the form of {key1:true, key2:true, ...}
  674. */
  675. function makeMap(str) {
  676. var obj = {}, items = str.split(","), i;
  677. for (i = 0; i < items.length; i++) {
  678. obj[items[i]] = true;
  679. }
  680. return obj;
  681. }
  682. function nodeName_(element) {
  683. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  684. }
  685. function includes(array, obj) {
  686. return Array.prototype.indexOf.call(array, obj) != -1;
  687. }
  688. function arrayRemove(array, value) {
  689. var index = array.indexOf(value);
  690. if (index >= 0) {
  691. array.splice(index, 1);
  692. }
  693. return index;
  694. }
  695. /**
  696. * @ngdoc function
  697. * @name angular.copy
  698. * @module ng
  699. * @kind function
  700. *
  701. * @description
  702. * Creates a deep copy of `source`, which should be an object or an array.
  703. *
  704. * * If no destination is supplied, a copy of the object or array is created.
  705. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  706. * are deleted and then all elements/properties from the source are copied to it.
  707. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  708. * * If `source` is identical to 'destination' an exception will be thrown.
  709. *
  710. * @param {*} source The source that will be used to make a copy.
  711. * Can be any type, including primitives, `null`, and `undefined`.
  712. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  713. * provided, must be of the same type as `source`.
  714. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  715. *
  716. * @example
  717. <example module="copyExample">
  718. <file name="index.html">
  719. <div ng-controller="ExampleController">
  720. <form novalidate class="simple-form">
  721. Name: <input type="text" ng-model="user.name" /><br />
  722. E-mail: <input type="email" ng-model="user.email" /><br />
  723. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  724. <input type="radio" ng-model="user.gender" value="female" />female<br />
  725. <button ng-click="reset()">RESET</button>
  726. <button ng-click="update(user)">SAVE</button>
  727. </form>
  728. <pre>form = {{user | json}}</pre>
  729. <pre>master = {{master | json}}</pre>
  730. </div>
  731. <script>
  732. angular.module('copyExample', [])
  733. .controller('ExampleController', ['$scope', function($scope) {
  734. $scope.master= {};
  735. $scope.update = function(user) {
  736. // Example with 1 argument
  737. $scope.master= angular.copy(user);
  738. };
  739. $scope.reset = function() {
  740. // Example with 2 arguments
  741. angular.copy($scope.master, $scope.user);
  742. };
  743. $scope.reset();
  744. }]);
  745. </script>
  746. </file>
  747. </example>
  748. */
  749. function copy(source, destination, stackSource, stackDest) {
  750. if (isWindow(source) || isScope(source)) {
  751. throw ngMinErr('cpws',
  752. "Can't copy! Making copies of Window or Scope instances is not supported.");
  753. }
  754. if (isTypedArray(destination)) {
  755. throw ngMinErr('cpta',
  756. "Can't copy! TypedArray destination cannot be mutated.");
  757. }
  758. if (!destination) {
  759. destination = source;
  760. if (isObject(source)) {
  761. var index;
  762. if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
  763. return stackDest[index];
  764. }
  765. // TypedArray, Date and RegExp have specific copy functionality and must be
  766. // pushed onto the stack before returning.
  767. // Array and other objects create the base object and recurse to copy child
  768. // objects. The array/object will be pushed onto the stack when recursed.
  769. if (isArray(source)) {
  770. return copy(source, [], stackSource, stackDest);
  771. } else if (isTypedArray(source)) {
  772. destination = new source.constructor(source);
  773. } else if (isDate(source)) {
  774. destination = new Date(source.getTime());
  775. } else if (isRegExp(source)) {
  776. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  777. destination.lastIndex = source.lastIndex;
  778. } else {
  779. var emptyObject = Object.create(getPrototypeOf(source));
  780. return copy(source, emptyObject, stackSource, stackDest);
  781. }
  782. if (stackDest) {
  783. stackSource.push(source);
  784. stackDest.push(destination);
  785. }
  786. }
  787. } else {
  788. if (source === destination) throw ngMinErr('cpi',
  789. "Can't copy! Source and destination are identical.");
  790. stackSource = stackSource || [];
  791. stackDest = stackDest || [];
  792. if (isObject(source)) {
  793. stackSource.push(source);
  794. stackDest.push(destination);
  795. }
  796. var result, key;
  797. if (isArray(source)) {
  798. destination.length = 0;
  799. for (var i = 0; i < source.length; i++) {
  800. destination.push(copy(source[i], null, stackSource, stackDest));
  801. }
  802. } else {
  803. var h = destination.$$hashKey;
  804. if (isArray(destination)) {
  805. destination.length = 0;
  806. } else {
  807. forEach(destination, function(value, key) {
  808. delete destination[key];
  809. });
  810. }
  811. if (isBlankObject(source)) {
  812. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  813. for (key in source) {
  814. destination[key] = copy(source[key], null, stackSource, stackDest);
  815. }
  816. } else if (source && typeof source.hasOwnProperty === 'function') {
  817. // Slow path, which must rely on hasOwnProperty
  818. for (key in source) {
  819. if (source.hasOwnProperty(key)) {
  820. destination[key] = copy(source[key], null, stackSource, stackDest);
  821. }
  822. }
  823. } else {
  824. // Slowest path --- hasOwnProperty can't be called as a method
  825. for (key in source) {
  826. if (hasOwnProperty.call(source, key)) {
  827. destination[key] = copy(source[key], null, stackSource, stackDest);
  828. }
  829. }
  830. }
  831. setHashKey(destination,h);
  832. }
  833. }
  834. return destination;
  835. }
  836. /**
  837. * Creates a shallow copy of an object, an array or a primitive.
  838. *
  839. * Assumes that there are no proto properties for objects.
  840. */
  841. function shallowCopy(src, dst) {
  842. if (isArray(src)) {
  843. dst = dst || [];
  844. for (var i = 0, ii = src.length; i < ii; i++) {
  845. dst[i] = src[i];
  846. }
  847. } else if (isObject(src)) {
  848. dst = dst || {};
  849. for (var key in src) {
  850. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  851. dst[key] = src[key];
  852. }
  853. }
  854. }
  855. return dst || src;
  856. }
  857. /**
  858. * @ngdoc function
  859. * @name angular.equals
  860. * @module ng
  861. * @kind function
  862. *
  863. * @description
  864. * Determines if two objects or two values are equivalent. Supports value types, regular
  865. * expressions, arrays and objects.
  866. *
  867. * Two objects or values are considered equivalent if at least one of the following is true:
  868. *
  869. * * Both objects or values pass `===` comparison.
  870. * * Both objects or values are of the same type and all of their properties are equal by
  871. * comparing them with `angular.equals`.
  872. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  873. * * Both values represent the same regular expression (In JavaScript,
  874. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  875. * representation matches).
  876. *
  877. * During a property comparison, properties of `function` type and properties with names
  878. * that begin with `$` are ignored.
  879. *
  880. * Scope and DOMWindow objects are being compared only by identify (`===`).
  881. *
  882. * @param {*} o1 Object or value to compare.
  883. * @param {*} o2 Object or value to compare.
  884. * @returns {boolean} True if arguments are equal.
  885. */
  886. function equals(o1, o2) {
  887. if (o1 === o2) return true;
  888. if (o1 === null || o2 === null) return false;
  889. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  890. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  891. if (t1 == t2) {
  892. if (t1 == 'object') {
  893. if (isArray(o1)) {
  894. if (!isArray(o2)) return false;
  895. if ((length = o1.length) == o2.length) {
  896. for (key = 0; key < length; key++) {
  897. if (!equals(o1[key], o2[key])) return false;
  898. }
  899. return true;
  900. }
  901. } else if (isDate(o1)) {
  902. if (!isDate(o2)) return false;
  903. return equals(o1.getTime(), o2.getTime());
  904. } else if (isRegExp(o1)) {
  905. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  906. } else {
  907. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  908. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  909. keySet = createMap();
  910. for (key in o1) {
  911. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  912. if (!equals(o1[key], o2[key])) return false;
  913. keySet[key] = true;
  914. }
  915. for (key in o2) {
  916. if (!(key in keySet) &&
  917. key.charAt(0) !== '$' &&
  918. o2[key] !== undefined &&
  919. !isFunction(o2[key])) return false;
  920. }
  921. return true;
  922. }
  923. }
  924. }
  925. return false;
  926. }
  927. var csp = function() {
  928. if (isDefined(csp.isActive_)) return csp.isActive_;
  929. var active = !!(document.querySelector('[ng-csp]') ||
  930. document.querySelector('[data-ng-csp]'));
  931. if (!active) {
  932. try {
  933. /* jshint -W031, -W054 */
  934. new Function('');
  935. /* jshint +W031, +W054 */
  936. } catch (e) {
  937. active = true;
  938. }
  939. }
  940. return (csp.isActive_ = active);
  941. };
  942. /**
  943. * @ngdoc directive
  944. * @module ng
  945. * @name ngJq
  946. *
  947. * @element ANY
  948. * @param {string=} ngJq the name of the library available under `window`
  949. * to be used for angular.element
  950. * @description
  951. * Use this directive to force the angular.element library. This should be
  952. * used to force either jqLite by leaving ng-jq blank or setting the name of
  953. * the jquery variable under window (eg. jQuery).
  954. *
  955. * Since angular looks for this directive when it is loaded (doesn't wait for the
  956. * DOMContentLoaded event), it must be placed on an element that comes before the script
  957. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  958. * others ignored.
  959. *
  960. * @example
  961. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  962. ```html
  963. <!doctype html>
  964. <html ng-app ng-jq>
  965. ...
  966. ...
  967. </html>
  968. ```
  969. * @example
  970. * This example shows how to use a jQuery based library of a different name.
  971. * The library name must be available at the top most 'window'.
  972. ```html
  973. <!doctype html>
  974. <html ng-app ng-jq="jQueryLib">
  975. ...
  976. ...
  977. </html>
  978. ```
  979. */
  980. var jq = function() {
  981. if (isDefined(jq.name_)) return jq.name_;
  982. var el;
  983. var i, ii = ngAttrPrefixes.length, prefix, name;
  984. for (i = 0; i < ii; ++i) {
  985. prefix = ngAttrPrefixes[i];
  986. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  987. name = el.getAttribute(prefix + 'jq');
  988. break;
  989. }
  990. }
  991. return (jq.name_ = name);
  992. };
  993. function concat(array1, array2, index) {
  994. return array1.concat(slice.call(array2, index));
  995. }
  996. function sliceArgs(args, startIndex) {
  997. return slice.call(args, startIndex || 0);
  998. }
  999. /* jshint -W101 */
  1000. /**
  1001. * @ngdoc function
  1002. * @name angular.bind
  1003. * @module ng
  1004. * @kind function
  1005. *
  1006. * @description
  1007. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1008. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1009. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1010. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1011. *
  1012. * @param {Object} self Context which `fn` should be evaluated in.
  1013. * @param {function()} fn Function to be bound.
  1014. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1015. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1016. */
  1017. /* jshint +W101 */
  1018. function bind(self, fn) {
  1019. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1020. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1021. return curryArgs.length
  1022. ? function() {
  1023. return arguments.length
  1024. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1025. : fn.apply(self, curryArgs);
  1026. }
  1027. : function() {
  1028. return arguments.length
  1029. ? fn.apply(self, arguments)
  1030. : fn.call(self);
  1031. };
  1032. } else {
  1033. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1034. return fn;
  1035. }
  1036. }
  1037. function toJsonReplacer(key, value) {
  1038. var val = value;
  1039. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1040. val = undefined;
  1041. } else if (isWindow(value)) {
  1042. val = '$WINDOW';
  1043. } else if (value && document === value) {
  1044. val = '$DOCUMENT';
  1045. } else if (isScope(value)) {
  1046. val = '$SCOPE';
  1047. }
  1048. return val;
  1049. }
  1050. /**
  1051. * @ngdoc function
  1052. * @name angular.toJson
  1053. * @module ng
  1054. * @kind function
  1055. *
  1056. * @description
  1057. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1058. * stripped since angular uses this notation internally.
  1059. *
  1060. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1061. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1062. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1063. * @returns {string|undefined} JSON-ified string representing `obj`.
  1064. */
  1065. function toJson(obj, pretty) {
  1066. if (typeof obj === 'undefined') return undefined;
  1067. if (!isNumber(pretty)) {
  1068. pretty = pretty ? 2 : null;
  1069. }
  1070. return JSON.stringify(obj, toJsonReplacer, pretty);
  1071. }
  1072. /**
  1073. * @ngdoc function
  1074. * @name angular.fromJson
  1075. * @module ng
  1076. * @kind function
  1077. *
  1078. * @description
  1079. * Deserializes a JSON string.
  1080. *
  1081. * @param {string} json JSON string to deserialize.
  1082. * @returns {Object|Array|string|number} Deserialized JSON string.
  1083. */
  1084. function fromJson(json) {
  1085. return isString(json)
  1086. ? JSON.parse(json)
  1087. : json;
  1088. }
  1089. function timezoneToOffset(timezone, fallback) {
  1090. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1091. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1092. }
  1093. function addDateMinutes(date, minutes) {
  1094. date = new Date(date.getTime());
  1095. date.setMinutes(date.getMinutes() + minutes);
  1096. return date;
  1097. }
  1098. function convertTimezoneToLocal(date, timezone, reverse) {
  1099. reverse = reverse ? -1 : 1;
  1100. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1101. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1102. }
  1103. /**
  1104. * @returns {string} Returns the string representation of the element.
  1105. */
  1106. function startingTag(element) {
  1107. element = jqLite(element).clone();
  1108. try {
  1109. // turns out IE does not let you set .html() on elements which
  1110. // are not allowed to have children. So we just ignore it.
  1111. element.empty();
  1112. } catch (e) {}
  1113. var elemHtml = jqLite('<div>').append(element).html();
  1114. try {
  1115. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1116. elemHtml.
  1117. match(/^(<[^>]+>)/)[1].
  1118. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1119. } catch (e) {
  1120. return lowercase(elemHtml);
  1121. }
  1122. }
  1123. /////////////////////////////////////////////////
  1124. /**
  1125. * Tries to decode the URI component without throwing an exception.
  1126. *
  1127. * @private
  1128. * @param str value potential URI component to check.
  1129. * @returns {boolean} True if `value` can be decoded
  1130. * with the decodeURIComponent function.
  1131. */
  1132. function tryDecodeURIComponent(value) {
  1133. try {
  1134. return decodeURIComponent(value);
  1135. } catch (e) {
  1136. // Ignore any invalid uri component
  1137. }
  1138. }
  1139. /**
  1140. * Parses an escaped url query string into key-value pairs.
  1141. * @returns {Object.<string,boolean|Array>}
  1142. */
  1143. function parseKeyValue(/**string*/keyValue) {
  1144. var obj = {}, key_value, key;
  1145. forEach((keyValue || "").split('&'), function(keyValue) {
  1146. if (keyValue) {
  1147. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1148. key = tryDecodeURIComponent(key_value[0]);
  1149. if (isDefined(key)) {
  1150. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1151. if (!hasOwnProperty.call(obj, key)) {
  1152. obj[key] = val;
  1153. } else if (isArray(obj[key])) {
  1154. obj[key].push(val);
  1155. } else {
  1156. obj[key] = [obj[key],val];
  1157. }
  1158. }
  1159. }
  1160. });
  1161. return obj;
  1162. }
  1163. function toKeyValue(obj) {
  1164. var parts = [];
  1165. forEach(obj, function(value, key) {
  1166. if (isArray(value)) {
  1167. forEach(value, function(arrayValue) {
  1168. parts.push(encodeUriQuery(key, true) +
  1169. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1170. });
  1171. } else {
  1172. parts.push(encodeUriQuery(key, true) +
  1173. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1174. }
  1175. });
  1176. return parts.length ? parts.join('&') : '';
  1177. }
  1178. /**
  1179. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1180. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1181. * segments:
  1182. * segment = *pchar
  1183. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1184. * pct-encoded = "%" HEXDIG HEXDIG
  1185. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1186. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1187. * / "*" / "+" / "," / ";" / "="
  1188. */
  1189. function encodeUriSegment(val) {
  1190. return encodeUriQuery(val, true).
  1191. replace(/%26/gi, '&').
  1192. replace(/%3D/gi, '=').
  1193. replace(/%2B/gi, '+');
  1194. }
  1195. /**
  1196. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1197. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1198. * encoded per http://tools.ietf.org/html/rfc3986:
  1199. * query = *( pchar / "/" / "?" )
  1200. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1201. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1202. * pct-encoded = "%" HEXDIG HEXDIG
  1203. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1204. * / "*" / "+" / "," / ";" / "="
  1205. */
  1206. function encodeUriQuery(val, pctEncodeSpaces) {
  1207. return encodeURIComponent(val).
  1208. replace(/%40/gi, '@').
  1209. replace(/%3A/gi, ':').
  1210. replace(/%24/g, '$').
  1211. replace(/%2C/gi, ',').
  1212. replace(/%3B/gi, ';').
  1213. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1214. }
  1215. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1216. function getNgAttribute(element, ngAttr) {
  1217. var attr, i, ii = ngAttrPrefixes.length;
  1218. for (i = 0; i < ii; ++i) {
  1219. attr = ngAttrPrefixes[i] + ngAttr;
  1220. if (isString(attr = element.getAttribute(attr))) {
  1221. return attr;
  1222. }
  1223. }
  1224. return null;
  1225. }
  1226. /**
  1227. * @ngdoc directive
  1228. * @name ngApp
  1229. * @module ng
  1230. *
  1231. * @element ANY
  1232. * @param {angular.Module} ngApp an optional application
  1233. * {@link angular.module module} name to load.
  1234. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1235. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1236. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1237. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1238. * tracking down the root of these bugs.
  1239. *
  1240. * @description
  1241. *
  1242. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1243. * designates the **root element** of the application and is typically placed near the root element
  1244. * of the page - e.g. on the `<body>` or `<html>` tags.
  1245. *
  1246. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1247. * found in the document will be used to define the root element to auto-bootstrap as an
  1248. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1249. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1250. *
  1251. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1252. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1253. * should contain the application code needed or have dependencies on other modules that will
  1254. * contain the code. See {@link angular.module} for more information.
  1255. *
  1256. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1257. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1258. * would not be resolved to `3`.
  1259. *
  1260. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1261. *
  1262. <example module="ngAppDemo">
  1263. <file name="index.html">
  1264. <div ng-controller="ngAppDemoController">
  1265. I can add: {{a}} + {{b}} = {{ a+b }}
  1266. </div>
  1267. </file>
  1268. <file name="script.js">
  1269. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1270. $scope.a = 1;
  1271. $scope.b = 2;
  1272. });
  1273. </file>
  1274. </example>
  1275. *
  1276. * Using `ngStrictDi`, you would see something like this:
  1277. *
  1278. <example ng-app-included="true">
  1279. <file name="index.html">
  1280. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1281. <div ng-controller="GoodController1">
  1282. I can add: {{a}} + {{b}} = {{ a+b }}
  1283. <p>This renders because the controller does not fail to
  1284. instantiate, by using explicit annotation style (see
  1285. script.js for details)
  1286. </p>
  1287. </div>
  1288. <div ng-controller="GoodController2">
  1289. Name: <input ng-model="name"><br />
  1290. Hello, {{name}}!
  1291. <p>This renders because the controller does not fail to
  1292. instantiate, by using explicit annotation style
  1293. (see script.js for details)
  1294. </p>
  1295. </div>
  1296. <div ng-controller="BadController">
  1297. I can add: {{a}} + {{b}} = {{ a+b }}
  1298. <p>The controller could not be instantiated, due to relying
  1299. on automatic function annotations (which are disabled in
  1300. strict mode). As such, the content of this section is not
  1301. interpolated, and there should be an error in your web console.
  1302. </p>
  1303. </div>
  1304. </div>
  1305. </file>
  1306. <file name="script.js">
  1307. angular.module('ngAppStrictDemo', [])
  1308. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1309. // rather than an explicit annotation
  1310. .controller('BadController', function($scope) {
  1311. $scope.a = 1;
  1312. $scope.b = 2;
  1313. })
  1314. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1315. // due to using explicit annotations using the array style and $inject property, respectively.
  1316. .controller('GoodController1', ['$scope', function($scope) {
  1317. $scope.a = 1;
  1318. $scope.b = 2;
  1319. }])
  1320. .controller('GoodController2', GoodController2);
  1321. function GoodController2($scope) {
  1322. $scope.name = "World";
  1323. }
  1324. GoodController2.$inject = ['$scope'];
  1325. </file>
  1326. <file name="style.css">
  1327. div[ng-controller] {
  1328. margin-bottom: 1em;
  1329. -webkit-border-radius: 4px;
  1330. border-radius: 4px;
  1331. border: 1px solid;
  1332. padding: .5em;
  1333. }
  1334. div[ng-controller^=Good] {
  1335. border-color: #d6e9c6;
  1336. background-color: #dff0d8;
  1337. color: #3c763d;
  1338. }
  1339. div[ng-controller^=Bad] {
  1340. border-color: #ebccd1;
  1341. background-color: #f2dede;
  1342. color: #a94442;
  1343. margin-bottom: 0;
  1344. }
  1345. </file>
  1346. </example>
  1347. */
  1348. function angularInit(element, bootstrap) {
  1349. var appElement,
  1350. module,
  1351. config = {};
  1352. // The element `element` has priority over any other element
  1353. forEach(ngAttrPrefixes, function(prefix) {
  1354. var name = prefix + 'app';
  1355. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1356. appElement = element;
  1357. module = element.getAttribute(name);
  1358. }
  1359. });
  1360. forEach(ngAttrPrefixes, function(prefix) {
  1361. var name = prefix + 'app';
  1362. var candidate;
  1363. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1364. appElement = candidate;
  1365. module = candidate.getAttribute(name);
  1366. }
  1367. });
  1368. if (appElement) {
  1369. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1370. bootstrap(appElement, module ? [module] : [], config);
  1371. }
  1372. }
  1373. /**
  1374. * @ngdoc function
  1375. * @name angular.bootstrap
  1376. * @module ng
  1377. * @description
  1378. * Use this function to manually start up angular application.
  1379. *
  1380. * See: {@link guide/bootstrap Bootstrap}
  1381. *
  1382. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1383. * They must use {@link ng.directive:ngApp ngApp}.
  1384. *
  1385. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1386. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1387. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1388. * multiple instances of Angular try to work on the DOM.
  1389. *
  1390. * ```html
  1391. * <!doctype html>
  1392. * <html>
  1393. * <body>
  1394. * <div ng-controller="WelcomeController">
  1395. * {{greeting}}
  1396. * </div>
  1397. *
  1398. * <script src="angular.js"></script>
  1399. * <script>
  1400. * var app = angular.module('demo', [])
  1401. * .controller('WelcomeController', function($scope) {
  1402. * $scope.greeting = 'Welcome!';
  1403. * });
  1404. * angular.bootstrap(document, ['demo']);
  1405. * </script>
  1406. * </body>
  1407. * </html>
  1408. * ```
  1409. *
  1410. * @param {DOMElement} element DOM element which is the root of angular application.
  1411. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1412. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1413. * function that will be invoked by the injector as a `config` block.
  1414. * See: {@link angular.module modules}
  1415. * @param {Object=} config an object for defining configuration options for the application. The
  1416. * following keys are supported:
  1417. *
  1418. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1419. * assist in finding bugs which break minified code. Defaults to `false`.
  1420. *
  1421. * @returns {auto.$injector} Returns the newly created injector for this app.
  1422. */
  1423. function bootstrap(element, modules, config) {
  1424. if (!isObject(config)) config = {};
  1425. var defaultConfig = {
  1426. strictDi: false
  1427. };
  1428. config = extend(defaultConfig, config);
  1429. var doBootstrap = function() {
  1430. element = jqLite(element);
  1431. if (element.injector()) {
  1432. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1433. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1434. throw ngMinErr(
  1435. 'btstrpd',
  1436. "App Already Bootstrapped with this Element '{0}'",
  1437. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1438. }
  1439. modules = modules || [];
  1440. modules.unshift(['$provide', function($provide) {
  1441. $provide.value('$rootElement', element);
  1442. }]);
  1443. if (config.debugInfoEnabled) {
  1444. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1445. modules.push(['$compileProvider', function($compileProvider) {
  1446. $compileProvider.debugInfoEnabled(true);
  1447. }]);
  1448. }
  1449. modules.unshift('ng');
  1450. var injector = createInjector(modules, config.strictDi);
  1451. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1452. function bootstrapApply(scope, element, compile, injector) {
  1453. scope.$apply(function() {
  1454. element.data('$injector', injector);
  1455. compile(element)(scope);
  1456. });
  1457. }]
  1458. );
  1459. return injector;
  1460. };
  1461. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1462. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1463. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1464. config.debugInfoEnabled = true;
  1465. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1466. }
  1467. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1468. return doBootstrap();
  1469. }
  1470. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1471. angular.resumeBootstrap = function(extraModules) {
  1472. forEach(extraModules, function(module) {
  1473. modules.push(module);
  1474. });
  1475. return doBootstrap();
  1476. };
  1477. if (isFunction(angular.resumeDeferredBootstrap)) {
  1478. angular.resumeDeferredBootstrap();
  1479. }
  1480. }
  1481. /**
  1482. * @ngdoc function
  1483. * @name angular.reloadWithDebugInfo
  1484. * @module ng
  1485. * @description
  1486. * Use this function to reload the current application with debug information turned on.
  1487. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1488. *
  1489. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1490. */
  1491. function reloadWithDebugInfo() {
  1492. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1493. window.location.reload();
  1494. }
  1495. /**
  1496. * @name angular.getTestability
  1497. * @module ng
  1498. * @description
  1499. * Get the testability service for the instance of Angular on the given
  1500. * element.
  1501. * @param {DOMElement} element DOM element which is the root of angular application.
  1502. */
  1503. function getTestability(rootElement) {
  1504. var injector = angular.element(rootElement).injector();
  1505. if (!injector) {
  1506. throw ngMinErr('test',
  1507. 'no injector found for element argument to getTestability');
  1508. }
  1509. return injector.get('$$testability');
  1510. }
  1511. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1512. function snake_case(name, separator) {
  1513. separator = separator || '_';
  1514. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1515. return (pos ? separator : '') + letter.toLowerCase();
  1516. });
  1517. }
  1518. var bindJQueryFired = false;
  1519. var skipDestroyOnNextJQueryCleanData;
  1520. function bindJQuery() {
  1521. var originalCleanData;
  1522. if (bindJQueryFired) {
  1523. return;
  1524. }
  1525. // bind to jQuery if present;
  1526. var jqName = jq();
  1527. jQuery = window.jQuery; // use default jQuery.
  1528. if (isDefined(jqName)) { // `ngJq` present
  1529. jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  1530. }
  1531. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1532. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1533. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1534. // versions. It will not work for sure with jQuery <1.7, though.
  1535. if (jQuery && jQuery.fn.on) {
  1536. jqLite = jQuery;
  1537. extend(jQuery.fn, {
  1538. scope: JQLitePrototype.scope,
  1539. isolateScope: JQLitePrototype.isolateScope,
  1540. controller: JQLitePrototype.controller,
  1541. injector: JQLitePrototype.injector,
  1542. inheritedData: JQLitePrototype.inheritedData
  1543. });
  1544. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1545. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1546. // the $destroy event on all removed nodes.
  1547. originalCleanData = jQuery.cleanData;
  1548. jQuery.cleanData = function(elems) {
  1549. var events;
  1550. if (!skipDestroyOnNextJQueryCleanData) {
  1551. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1552. events = jQuery._data(elem, "events");
  1553. if (events && events.$destroy) {
  1554. jQuery(elem).triggerHandler('$destroy');
  1555. }
  1556. }
  1557. } else {
  1558. skipDestroyOnNextJQueryCleanData = false;
  1559. }
  1560. originalCleanData(elems);
  1561. };
  1562. } else {
  1563. jqLite = JQLite;
  1564. }
  1565. angular.element = jqLite;
  1566. // Prevent double-proxying.
  1567. bindJQueryFired = true;
  1568. }
  1569. /**
  1570. * throw error if the argument is falsy.
  1571. */
  1572. function assertArg(arg, name, reason) {
  1573. if (!arg) {
  1574. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1575. }
  1576. return arg;
  1577. }
  1578. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1579. if (acceptArrayAnnotation && isArray(arg)) {
  1580. arg = arg[arg.length - 1];
  1581. }
  1582. assertArg(isFunction(arg), name, 'not a function, got ' +
  1583. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1584. return arg;
  1585. }
  1586. /**
  1587. * throw error if the name given is hasOwnProperty
  1588. * @param {String} name the name to test
  1589. * @param {String} context the context in which the name is used, such as module or directive
  1590. */
  1591. function assertNotHasOwnProperty(name, context) {
  1592. if (name === 'hasOwnProperty') {
  1593. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1594. }
  1595. }
  1596. /**
  1597. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1598. * @param {Object} obj starting object
  1599. * @param {String} path path to traverse
  1600. * @param {boolean} [bindFnToScope=true]
  1601. * @returns {Object} value as accessible by path
  1602. */
  1603. //TODO(misko): this function needs to be removed
  1604. function getter(obj, path, bindFnToScope) {
  1605. if (!path) return obj;
  1606. var keys = path.split('.');
  1607. var key;
  1608. var lastInstance = obj;
  1609. var len = keys.length;
  1610. for (var i = 0; i < len; i++) {
  1611. key = keys[i];
  1612. if (obj) {
  1613. obj = (lastInstance = obj)[key];
  1614. }
  1615. }
  1616. if (!bindFnToScope && isFunction(obj)) {
  1617. return bind(lastInstance, obj);
  1618. }
  1619. return obj;
  1620. }
  1621. /**
  1622. * Return the DOM siblings between the first and last node in the given array.
  1623. * @param {Array} array like object
  1624. * @returns {jqLite} jqLite collection containing the nodes
  1625. */
  1626. function getBlockNodes(nodes) {
  1627. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1628. // collection, otherwise update the original collection.
  1629. var node = nodes[0];
  1630. var endNode = nodes[nodes.length - 1];
  1631. var blockNodes = [node];
  1632. do {
  1633. node = node.nextSibling;
  1634. if (!node) break;
  1635. blockNodes.push(node);
  1636. } while (node !== endNode);
  1637. return jqLite(blockNodes);
  1638. }
  1639. /**
  1640. * Creates a new object without a prototype. This object is useful for lookup without having to
  1641. * guard against prototypically inherited properties via hasOwnProperty.
  1642. *
  1643. * Related micro-benchmarks:
  1644. * - http://jsperf.com/object-create2
  1645. * - http://jsperf.com/proto-map-lookup/2
  1646. * - http://jsperf.com/for-in-vs-object-keys2
  1647. *
  1648. * @returns {Object}
  1649. */
  1650. function createMap() {
  1651. return Object.create(null);
  1652. }
  1653. var NODE_TYPE_ELEMENT = 1;
  1654. var NODE_TYPE_ATTRIBUTE = 2;
  1655. var NODE_TYPE_TEXT = 3;
  1656. var NODE_TYPE_COMMENT = 8;
  1657. var NODE_TYPE_DOCUMENT = 9;
  1658. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1659. /**
  1660. * @ngdoc type
  1661. * @name angular.Module
  1662. * @module ng
  1663. * @description
  1664. *
  1665. * Interface for configuring angular {@link angular.module modules}.
  1666. */
  1667. function setupModuleLoader(window) {
  1668. var $injectorMinErr = minErr('$injector');
  1669. var ngMinErr = minErr('ng');
  1670. function ensure(obj, name, factory) {
  1671. return obj[name] || (obj[name] = factory());
  1672. }
  1673. var angular = ensure(window, 'angular', Object);
  1674. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1675. angular.$$minErr = angular.$$minErr || minErr;
  1676. return ensure(angular, 'module', function() {
  1677. /** @type {Object.<string, angular.Module>} */
  1678. var modules = {};
  1679. /**
  1680. * @ngdoc function
  1681. * @name angular.module
  1682. * @module ng
  1683. * @description
  1684. *
  1685. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1686. * modules.
  1687. * All modules (angular core or 3rd party) that should be available to an application must be
  1688. * registered using this mechanism.
  1689. *
  1690. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1691. * existing module (the name passed as the first argument to `module`) is retrieved.
  1692. *
  1693. *
  1694. * # Module
  1695. *
  1696. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1697. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1698. *
  1699. * ```js
  1700. * // Create a new module
  1701. * var myModule = angular.module('myModule', []);
  1702. *
  1703. * // register a new service
  1704. * myModule.value('appName', 'MyCoolApp');
  1705. *
  1706. * // configure existing services inside initialization blocks.
  1707. * myModule.config(['$locationProvider', function($locationProvider) {
  1708. * // Configure existing providers
  1709. * $locationProvider.hashPrefix('!');
  1710. * }]);
  1711. * ```
  1712. *
  1713. * Then you can create an injector and load your modules like this:
  1714. *
  1715. * ```js
  1716. * var injector = angular.injector(['ng', 'myModule'])
  1717. * ```
  1718. *
  1719. * However it's more likely that you'll just use
  1720. * {@link ng.directive:ngApp ngApp} or
  1721. * {@link angular.bootstrap} to simplify this process for you.
  1722. *
  1723. * @param {!string} name The name of the module to create or retrieve.
  1724. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1725. * unspecified then the module is being retrieved for further configuration.
  1726. * @param {Function=} configFn Optional configuration function for the module. Same as
  1727. * {@link angular.Module#config Module#config()}.
  1728. * @returns {module} new module with the {@link angular.Module} api.
  1729. */
  1730. return function module(name, requires, configFn) {
  1731. var assertNotHasOwnProperty = function(name, context) {
  1732. if (name === 'hasOwnProperty') {
  1733. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1734. }
  1735. };
  1736. assertNotHasOwnProperty(name, 'module');
  1737. if (requires && modules.hasOwnProperty(name)) {
  1738. modules[name] = null;
  1739. }
  1740. return ensure(modules, name, function() {
  1741. if (!requires) {
  1742. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1743. "the module name or forgot to load it. If registering a module ensure that you " +
  1744. "specify the dependencies as the second argument.", name);
  1745. }
  1746. /** @type {!Array.<Array.<*>>} */
  1747. var invokeQueue = [];
  1748. /** @type {!Array.<Function>} */
  1749. var configBlocks = [];
  1750. /** @type {!Array.<Function>} */
  1751. var runBlocks = [];
  1752. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1753. /** @type {angular.Module} */
  1754. var moduleInstance = {
  1755. // Private state
  1756. _invokeQueue: invokeQueue,
  1757. _configBlocks: configBlocks,
  1758. _runBlocks: runBlocks,
  1759. /**
  1760. * @ngdoc property
  1761. * @name angular.Module#requires
  1762. * @module ng
  1763. *
  1764. * @description
  1765. * Holds the list of modules which the injector will load before the current module is
  1766. * loaded.
  1767. */
  1768. requires: requires,
  1769. /**
  1770. * @ngdoc property
  1771. * @name angular.Module#name
  1772. * @module ng
  1773. *
  1774. * @description
  1775. * Name of the module.
  1776. */
  1777. name: name,
  1778. /**
  1779. * @ngdoc method
  1780. * @name angular.Module#provider
  1781. * @module ng
  1782. * @param {string} name service name
  1783. * @param {Function} providerType Construction function for creating new instance of the
  1784. * service.
  1785. * @description
  1786. * See {@link auto.$provide#provider $provide.provider()}.
  1787. */
  1788. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1789. /**
  1790. * @ngdoc method
  1791. * @name angular.Module#factory
  1792. * @module ng
  1793. * @param {string} name service name
  1794. * @param {Function} providerFunction Function for creating new instance of the service.
  1795. * @description
  1796. * See {@link auto.$provide#factory $provide.factory()}.
  1797. */
  1798. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1799. /**
  1800. * @ngdoc method
  1801. * @name angular.Module#service
  1802. * @module ng
  1803. * @param {string} name service name
  1804. * @param {Function} constructor A constructor function that will be instantiated.
  1805. * @description
  1806. * See {@link auto.$provide#service $provide.service()}.
  1807. */
  1808. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1809. /**
  1810. * @ngdoc method
  1811. * @name angular.Module#value
  1812. * @module ng
  1813. * @param {string} name service name
  1814. * @param {*} object Service instance object.
  1815. * @description
  1816. * See {@link auto.$provide#value $provide.value()}.
  1817. */
  1818. value: invokeLater('$provide', 'value'),
  1819. /**
  1820. * @ngdoc method
  1821. * @name angular.Module#constant
  1822. * @module ng
  1823. * @param {string} name constant name
  1824. * @param {*} object Constant value.
  1825. * @description
  1826. * Because the constant are fixed, they get applied before other provide methods.
  1827. * See {@link auto.$provide#constant $provide.constant()}.
  1828. */
  1829. constant: invokeLater('$provide', 'constant', 'unshift'),
  1830. /**
  1831. * @ngdoc method
  1832. * @name angular.Module#decorator
  1833. * @module ng
  1834. * @param {string} The name of the service to decorate.
  1835. * @param {Function} This function will be invoked when the service needs to be
  1836. * instantiated and should return the decorated service instance.
  1837. * @description
  1838. * See {@link auto.$provide#decorator $provide.decorator()}.
  1839. */
  1840. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1841. /**
  1842. * @ngdoc method
  1843. * @name angular.Module#animation
  1844. * @module ng
  1845. * @param {string} name animation name
  1846. * @param {Function} animationFactory Factory function for creating new instance of an
  1847. * animation.
  1848. * @description
  1849. *
  1850. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1851. *
  1852. *
  1853. * Defines an animation hook that can be later used with
  1854. * {@link $animate $animate} service and directives that use this service.
  1855. *
  1856. * ```js
  1857. * module.animation('.animation-name', function($inject1, $inject2) {
  1858. * return {
  1859. * eventName : function(element, done) {
  1860. * //code to run the animation
  1861. * //once complete, then run done()
  1862. * return function cancellationFunction(element) {
  1863. * //code to cancel the animation
  1864. * }
  1865. * }
  1866. * }
  1867. * })
  1868. * ```
  1869. *
  1870. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1871. * {@link ngAnimate ngAnimate module} for more information.
  1872. */
  1873. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1874. /**
  1875. * @ngdoc method
  1876. * @name angular.Module#filter
  1877. * @module ng
  1878. * @param {string} name Filter name - this must be a valid angular expression identifier
  1879. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1880. * @description
  1881. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1882. *
  1883. * <div class="alert alert-warning">
  1884. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1885. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1886. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1887. * (`myapp_subsection_filterx`).
  1888. * </div>
  1889. */
  1890. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1891. /**
  1892. * @ngdoc method
  1893. * @name angular.Module#controller
  1894. * @module ng
  1895. * @param {string|Object} name Controller name, or an object map of controllers where the
  1896. * keys are the names and the values are the constructors.
  1897. * @param {Function} constructor Controller constructor function.
  1898. * @description
  1899. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1900. */
  1901. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1902. /**
  1903. * @ngdoc method
  1904. * @name angular.Module#directive
  1905. * @module ng
  1906. * @param {string|Object} name Directive name, or an object map of directives where the
  1907. * keys are the names and the values are the factories.
  1908. * @param {Function} directiveFactory Factory function for creating new instance of
  1909. * directives.
  1910. * @description
  1911. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1912. */
  1913. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1914. /**
  1915. * @ngdoc method
  1916. * @name angular.Module#config
  1917. * @module ng
  1918. * @param {Function} configFn Execute this function on module load. Useful for service
  1919. * configuration.
  1920. * @description
  1921. * Use this method to register work which needs to be performed on module loading.
  1922. * For more about how to configure services, see
  1923. * {@link providers#provider-recipe Provider Recipe}.
  1924. */
  1925. config: config,
  1926. /**
  1927. * @ngdoc method
  1928. * @name angular.Module#run
  1929. * @module ng
  1930. * @param {Function} initializationFn Execute this function after injector creation.
  1931. * Useful for application initialization.
  1932. * @description
  1933. * Use this method to register work which should be performed when the injector is done
  1934. * loading all modules.
  1935. */
  1936. run: function(block) {
  1937. runBlocks.push(block);
  1938. return this;
  1939. }
  1940. };
  1941. if (configFn) {
  1942. config(configFn);
  1943. }
  1944. return moduleInstance;
  1945. /**
  1946. * @param {string} provider
  1947. * @param {string} method
  1948. * @param {String=} insertMethod
  1949. * @returns {angular.Module}
  1950. */
  1951. function invokeLater(provider, method, insertMethod, queue) {
  1952. if (!queue) queue = invokeQueue;
  1953. return function() {
  1954. queue[insertMethod || 'push']([provider, method, arguments]);
  1955. return moduleInstance;
  1956. };
  1957. }
  1958. /**
  1959. * @param {string} provider
  1960. * @param {string} method
  1961. * @returns {angular.Module}
  1962. */
  1963. function invokeLaterAndSetModuleName(provider, method) {
  1964. return function(recipeName, factoryFunction) {
  1965. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  1966. invokeQueue.push([provider, method, arguments]);
  1967. return moduleInstance;
  1968. };
  1969. }
  1970. });
  1971. };
  1972. });
  1973. }
  1974. /* global: toDebugString: true */
  1975. function serializeObject(obj) {
  1976. var seen = [];
  1977. return JSON.stringify(obj, function(key, val) {
  1978. val = toJsonReplacer(key, val);
  1979. if (isObject(val)) {
  1980. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1981. seen.push(val);
  1982. }
  1983. return val;
  1984. });
  1985. }
  1986. function toDebugString(obj) {
  1987. if (typeof obj === 'function') {
  1988. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1989. } else if (typeof obj === 'undefined') {
  1990. return 'undefined';
  1991. } else if (typeof obj !== 'string') {
  1992. return serializeObject(obj);
  1993. }
  1994. return obj;
  1995. }
  1996. /* global angularModule: true,
  1997. version: true,
  1998. $LocaleProvider,
  1999. $CompileProvider,
  2000. htmlAnchorDirective,
  2001. inputDirective,
  2002. inputDirective,
  2003. formDirective,
  2004. scriptDirective,
  2005. selectDirective,
  2006. styleDirective,
  2007. optionDirective,
  2008. ngBindDirective,
  2009. ngBindHtmlDirective,
  2010. ngBindTemplateDirective,
  2011. ngClassDirective,
  2012. ngClassEvenDirective,
  2013. ngClassOddDirective,
  2014. ngCspDirective,
  2015. ngCloakDirective,
  2016. ngControllerDirective,
  2017. ngFormDirective,
  2018. ngHideDirective,
  2019. ngIfDirective,
  2020. ngIncludeDirective,
  2021. ngIncludeFillContentDirective,
  2022. ngInitDirective,
  2023. ngNonBindableDirective,
  2024. ngPluralizeDirective,
  2025. ngRepeatDirective,
  2026. ngShowDirective,
  2027. ngStyleDirective,
  2028. ngSwitchDirective,
  2029. ngSwitchWhenDirective,
  2030. ngSwitchDefaultDirective,
  2031. ngOptionsDirective,
  2032. ngTranscludeDirective,
  2033. ngModelDirective,
  2034. ngListDirective,
  2035. ngChangeDirective,
  2036. patternDirective,
  2037. patternDirective,
  2038. requiredDirective,
  2039. requiredDirective,
  2040. minlengthDirective,
  2041. minlengthDirective,
  2042. maxlengthDirective,
  2043. maxlengthDirective,
  2044. ngValueDirective,
  2045. ngModelOptionsDirective,
  2046. ngAttributeAliasDirectives,
  2047. ngEventDirectives,
  2048. $AnchorScrollProvider,
  2049. $AnimateProvider,
  2050. $$CoreAnimateQueueProvider,
  2051. $$CoreAnimateRunnerProvider,
  2052. $BrowserProvider,
  2053. $CacheFactoryProvider,
  2054. $ControllerProvider,
  2055. $DocumentProvider,
  2056. $ExceptionHandlerProvider,
  2057. $FilterProvider,
  2058. $InterpolateProvider,
  2059. $IntervalProvider,
  2060. $$HashMapProvider,
  2061. $HttpProvider,
  2062. $HttpParamSerializerProvider,
  2063. $HttpParamSerializerJQLikeProvider,
  2064. $HttpBackendProvider,
  2065. $LocationProvider,
  2066. $LogProvider,
  2067. $ParseProvider,
  2068. $RootScopeProvider,
  2069. $QProvider,
  2070. $$QProvider,
  2071. $$SanitizeUriProvider,
  2072. $SceProvider,
  2073. $SceDelegateProvider,
  2074. $SnifferProvider,
  2075. $TemplateCacheProvider,
  2076. $TemplateRequestProvider,
  2077. $$TestabilityProvider,
  2078. $TimeoutProvider,
  2079. $$RAFProvider,
  2080. $$AsyncCallbackProvider,
  2081. $WindowProvider,
  2082. $$jqLiteProvider,
  2083. $$CookieReaderProvider
  2084. */
  2085. /**
  2086. * @ngdoc object
  2087. * @name angular.version
  2088. * @module ng
  2089. * @description
  2090. * An object that contains information about the current AngularJS version. This object has the
  2091. * following properties:
  2092. *
  2093. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2094. * - `major` – `{number}` – Major version number, such as "0".
  2095. * - `minor` – `{number}` – Minor version number, such as "9".
  2096. * - `dot` – `{number}` – Dot version number, such as "18".
  2097. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2098. */
  2099. var version = {
  2100. full: '1.4.1', // all of these placeholder strings will be replaced by grunt's
  2101. major: 1, // package task
  2102. minor: 4,
  2103. dot: 1,
  2104. codeName: 'hyperionic-illumination'
  2105. };
  2106. function publishExternalAPI(angular) {
  2107. extend(angular, {
  2108. 'bootstrap': bootstrap,
  2109. 'copy': copy,
  2110. 'extend': extend,
  2111. 'merge': merge,
  2112. 'equals': equals,
  2113. 'element': jqLite,
  2114. 'forEach': forEach,
  2115. 'injector': createInjector,
  2116. 'noop': noop,
  2117. 'bind': bind,
  2118. 'toJson': toJson,
  2119. 'fromJson': fromJson,
  2120. 'identity': identity,
  2121. 'isUndefined': isUndefined,
  2122. 'isDefined': isDefined,
  2123. 'isString': isString,
  2124. 'isFunction': isFunction,
  2125. 'isObject': isObject,
  2126. 'isNumber': isNumber,
  2127. 'isElement': isElement,
  2128. 'isArray': isArray,
  2129. 'version': version,
  2130. 'isDate': isDate,
  2131. 'lowercase': lowercase,
  2132. 'uppercase': uppercase,
  2133. 'callbacks': {counter: 0},
  2134. 'getTestability': getTestability,
  2135. '$$minErr': minErr,
  2136. '$$csp': csp,
  2137. 'reloadWithDebugInfo': reloadWithDebugInfo
  2138. });
  2139. angularModule = setupModuleLoader(window);
  2140. try {
  2141. angularModule('ngLocale');
  2142. } catch (e) {
  2143. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  2144. }
  2145. angularModule('ng', ['ngLocale'], ['$provide',
  2146. function ngModule($provide) {
  2147. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2148. $provide.provider({
  2149. $$sanitizeUri: $$SanitizeUriProvider
  2150. });
  2151. $provide.provider('$compile', $CompileProvider).
  2152. directive({
  2153. a: htmlAnchorDirective,
  2154. input: inputDirective,
  2155. textarea: inputDirective,
  2156. form: formDirective,
  2157. script: scriptDirective,
  2158. select: selectDirective,
  2159. style: styleDirective,
  2160. option: optionDirective,
  2161. ngBind: ngBindDirective,
  2162. ngBindHtml: ngBindHtmlDirective,
  2163. ngBindTemplate: ngBindTemplateDirective,
  2164. ngClass: ngClassDirective,
  2165. ngClassEven: ngClassEvenDirective,
  2166. ngClassOdd: ngClassOddDirective,
  2167. ngCloak: ngCloakDirective,
  2168. ngController: ngControllerDirective,
  2169. ngForm: ngFormDirective,
  2170. ngHide: ngHideDirective,
  2171. ngIf: ngIfDirective,
  2172. ngInclude: ngIncludeDirective,
  2173. ngInit: ngInitDirective,
  2174. ngNonBindable: ngNonBindableDirective,
  2175. ngPluralize: ngPluralizeDirective,
  2176. ngRepeat: ngRepeatDirective,
  2177. ngShow: ngShowDirective,
  2178. ngStyle: ngStyleDirective,
  2179. ngSwitch: ngSwitchDirective,
  2180. ngSwitchWhen: ngSwitchWhenDirective,
  2181. ngSwitchDefault: ngSwitchDefaultDirective,
  2182. ngOptions: ngOptionsDirective,
  2183. ngTransclude: ngTranscludeDirective,
  2184. ngModel: ngModelDirective,
  2185. ngList: ngListDirective,
  2186. ngChange: ngChangeDirective,
  2187. pattern: patternDirective,
  2188. ngPattern: patternDirective,
  2189. required: requiredDirective,
  2190. ngRequired: requiredDirective,
  2191. minlength: minlengthDirective,
  2192. ngMinlength: minlengthDirective,
  2193. maxlength: maxlengthDirective,
  2194. ngMaxlength: maxlengthDirective,
  2195. ngValue: ngValueDirective,
  2196. ngModelOptions: ngModelOptionsDirective
  2197. }).
  2198. directive({
  2199. ngInclude: ngIncludeFillContentDirective
  2200. }).
  2201. directive(ngAttributeAliasDirectives).
  2202. directive(ngEventDirectives);
  2203. $provide.provider({
  2204. $anchorScroll: $AnchorScrollProvider,
  2205. $animate: $AnimateProvider,
  2206. $$animateQueue: $$CoreAnimateQueueProvider,
  2207. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2208. $browser: $BrowserProvider,
  2209. $cacheFactory: $CacheFactoryProvider,
  2210. $controller: $ControllerProvider,
  2211. $document: $DocumentProvider,
  2212. $exceptionHandler: $ExceptionHandlerProvider,
  2213. $filter: $FilterProvider,
  2214. $interpolate: $InterpolateProvider,
  2215. $interval: $IntervalProvider,
  2216. $http: $HttpProvider,
  2217. $httpParamSerializer: $HttpParamSerializerProvider,
  2218. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2219. $httpBackend: $HttpBackendProvider,
  2220. $location: $LocationProvider,
  2221. $log: $LogProvider,
  2222. $parse: $ParseProvider,
  2223. $rootScope: $RootScopeProvider,
  2224. $q: $QProvider,
  2225. $$q: $$QProvider,
  2226. $sce: $SceProvider,
  2227. $sceDelegate: $SceDelegateProvider,
  2228. $sniffer: $SnifferProvider,
  2229. $templateCache: $TemplateCacheProvider,
  2230. $templateRequest: $TemplateRequestProvider,
  2231. $$testability: $$TestabilityProvider,
  2232. $timeout: $TimeoutProvider,
  2233. $window: $WindowProvider,
  2234. $$rAF: $$RAFProvider,
  2235. $$asyncCallback: $$AsyncCallbackProvider,
  2236. $$jqLite: $$jqLiteProvider,
  2237. $$HashMap: $$HashMapProvider,
  2238. $$cookieReader: $$CookieReaderProvider
  2239. });
  2240. }
  2241. ]);
  2242. }
  2243. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2244. * Any commits to this file should be reviewed with security in mind. *
  2245. * Changes to this file can potentially create security vulnerabilities. *
  2246. * An approval from 2 Core members with history of modifying *
  2247. * this file is required. *
  2248. * *
  2249. * Does the change somehow allow for arbitrary javascript to be executed? *
  2250. * Or allows for someone to change the prototype of built-in objects? *
  2251. * Or gives undesired access to variables likes document or window? *
  2252. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2253. /* global JQLitePrototype: true,
  2254. addEventListenerFn: true,
  2255. removeEventListenerFn: true,
  2256. BOOLEAN_ATTR: true,
  2257. ALIASED_ATTR: true,
  2258. */
  2259. //////////////////////////////////
  2260. //JQLite
  2261. //////////////////////////////////
  2262. /**
  2263. * @ngdoc function
  2264. * @name angular.element
  2265. * @module ng
  2266. * @kind function
  2267. *
  2268. * @description
  2269. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2270. *
  2271. * If jQuery is available, `angular.element` is an alias for the
  2272. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2273. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2274. *
  2275. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2276. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2277. * commonly needed functionality with the goal of having a very small footprint.</div>
  2278. *
  2279. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2280. *
  2281. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2282. * jqLite; they are never raw DOM references.</div>
  2283. *
  2284. * ## Angular's jqLite
  2285. * jqLite provides only the following jQuery methods:
  2286. *
  2287. * - [`addClass()`](http://api.jquery.com/addClass/)
  2288. * - [`after()`](http://api.jquery.com/after/)
  2289. * - [`append()`](http://api.jquery.com/append/)
  2290. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2291. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2292. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2293. * - [`clone()`](http://api.jquery.com/clone/)
  2294. * - [`contents()`](http://api.jquery.com/contents/)
  2295. * - [`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'.
  2296. * - [`data()`](http://api.jquery.com/data/)
  2297. * - [`detach()`](http://api.jquery.com/detach/)
  2298. * - [`empty()`](http://api.jquery.com/empty/)
  2299. * - [`eq()`](http://api.jquery.com/eq/)
  2300. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2301. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2302. * - [`html()`](http://api.jquery.com/html/)
  2303. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2304. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2305. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2306. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2307. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2308. * - [`prepend()`](http://api.jquery.com/prepend/)
  2309. * - [`prop()`](http://api.jquery.com/prop/)
  2310. * - [`ready()`](http://api.jquery.com/ready/)
  2311. * - [`remove()`](http://api.jquery.com/remove/)
  2312. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2313. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2314. * - [`removeData()`](http://api.jquery.com/removeData/)
  2315. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2316. * - [`text()`](http://api.jquery.com/text/)
  2317. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2318. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2319. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2320. * - [`val()`](http://api.jquery.com/val/)
  2321. * - [`wrap()`](http://api.jquery.com/wrap/)
  2322. *
  2323. * ## jQuery/jqLite Extras
  2324. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2325. *
  2326. * ### Events
  2327. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2328. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2329. * element before it is removed.
  2330. *
  2331. * ### Methods
  2332. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2333. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2334. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2335. * `'ngModel'`).
  2336. * - `injector()` - retrieves the injector of the current element or its parent.
  2337. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2338. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2339. * be enabled.
  2340. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2341. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2342. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2343. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2344. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2345. * parent element is reached.
  2346. *
  2347. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2348. * @returns {Object} jQuery object.
  2349. */
  2350. JQLite.expando = 'ng339';
  2351. var jqCache = JQLite.cache = {},
  2352. jqId = 1,
  2353. addEventListenerFn = function(element, type, fn) {
  2354. element.addEventListener(type, fn, false);
  2355. },
  2356. removeEventListenerFn = function(element, type, fn) {
  2357. element.removeEventListener(type, fn, false);
  2358. };
  2359. /*
  2360. * !!! This is an undocumented "private" function !!!
  2361. */
  2362. JQLite._data = function(node) {
  2363. //jQuery always returns an object on cache miss
  2364. return this.cache[node[this.expando]] || {};
  2365. };
  2366. function jqNextId() { return ++jqId; }
  2367. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2368. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2369. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2370. var jqLiteMinErr = minErr('jqLite');
  2371. /**
  2372. * Converts snake_case to camelCase.
  2373. * Also there is special case for Moz prefix starting with upper case letter.
  2374. * @param name Name to normalize
  2375. */
  2376. function camelCase(name) {
  2377. return name.
  2378. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2379. return offset ? letter.toUpperCase() : letter;
  2380. }).
  2381. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2382. }
  2383. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2384. var HTML_REGEXP = /<|&#?\w+;/;
  2385. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2386. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2387. var wrapMap = {
  2388. 'option': [1, '<select multiple="multiple">', '</select>'],
  2389. 'thead': [1, '<table>', '</table>'],
  2390. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2391. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2392. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2393. '_default': [0, "", ""]
  2394. };
  2395. wrapMap.optgroup = wrapMap.option;
  2396. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2397. wrapMap.th = wrapMap.td;
  2398. function jqLiteIsTextNode(html) {
  2399. return !HTML_REGEXP.test(html);
  2400. }
  2401. function jqLiteAcceptsData(node) {
  2402. // The window object can accept data but has no nodeType
  2403. // Otherwise we are only interested in elements (1) and documents (9)
  2404. var nodeType = node.nodeType;
  2405. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2406. }
  2407. function jqLiteHasData(node) {
  2408. for (var key in jqCache[node.ng339]) {
  2409. return true;
  2410. }
  2411. return false;
  2412. }
  2413. function jqLiteBuildFragment(html, context) {
  2414. var tmp, tag, wrap,
  2415. fragment = context.createDocumentFragment(),
  2416. nodes = [], i;
  2417. if (jqLiteIsTextNode(html)) {
  2418. // Convert non-html into a text node
  2419. nodes.push(context.createTextNode(html));
  2420. } else {
  2421. // Convert html into DOM nodes
  2422. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2423. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2424. wrap = wrapMap[tag] || wrapMap._default;
  2425. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2426. // Descend through wrappers to the right content
  2427. i = wrap[0];
  2428. while (i--) {
  2429. tmp = tmp.lastChild;
  2430. }
  2431. nodes = concat(nodes, tmp.childNodes);
  2432. tmp = fragment.firstChild;
  2433. tmp.textContent = "";
  2434. }
  2435. // Remove wrapper from fragment
  2436. fragment.textContent = "";
  2437. fragment.innerHTML = ""; // Clear inner HTML
  2438. forEach(nodes, function(node) {
  2439. fragment.appendChild(node);
  2440. });
  2441. return fragment;
  2442. }
  2443. function jqLiteParseHTML(html, context) {
  2444. context = context || document;
  2445. var parsed;
  2446. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2447. return [context.createElement(parsed[1])];
  2448. }
  2449. if ((parsed = jqLiteBuildFragment(html, context))) {
  2450. return parsed.childNodes;
  2451. }
  2452. return [];
  2453. }
  2454. /////////////////////////////////////////////
  2455. function JQLite(element) {
  2456. if (element instanceof JQLite) {
  2457. return element;
  2458. }
  2459. var argIsString;
  2460. if (isString(element)) {
  2461. element = trim(element);
  2462. argIsString = true;
  2463. }
  2464. if (!(this instanceof JQLite)) {
  2465. if (argIsString && element.charAt(0) != '<') {
  2466. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2467. }
  2468. return new JQLite(element);
  2469. }
  2470. if (argIsString) {
  2471. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2472. } else {
  2473. jqLiteAddNodes(this, element);
  2474. }
  2475. }
  2476. function jqLiteClone(element) {
  2477. return element.cloneNode(true);
  2478. }
  2479. function jqLiteDealoc(element, onlyDescendants) {
  2480. if (!onlyDescendants) jqLiteRemoveData(element);
  2481. if (element.querySelectorAll) {
  2482. var descendants = element.querySelectorAll('*');
  2483. for (var i = 0, l = descendants.length; i < l; i++) {
  2484. jqLiteRemoveData(descendants[i]);
  2485. }
  2486. }
  2487. }
  2488. function jqLiteOff(element, type, fn, unsupported) {
  2489. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2490. var expandoStore = jqLiteExpandoStore(element);
  2491. var events = expandoStore && expandoStore.events;
  2492. var handle = expandoStore && expandoStore.handle;
  2493. if (!handle) return; //no listeners registered
  2494. if (!type) {
  2495. for (type in events) {
  2496. if (type !== '$destroy') {
  2497. removeEventListenerFn(element, type, handle);
  2498. }
  2499. delete events[type];
  2500. }
  2501. } else {
  2502. forEach(type.split(' '), function(type) {
  2503. if (isDefined(fn)) {
  2504. var listenerFns = events[type];
  2505. arrayRemove(listenerFns || [], fn);
  2506. if (listenerFns && listenerFns.length > 0) {
  2507. return;
  2508. }
  2509. }
  2510. removeEventListenerFn(element, type, handle);
  2511. delete events[type];
  2512. });
  2513. }
  2514. }
  2515. function jqLiteRemoveData(element, name) {
  2516. var expandoId = element.ng339;
  2517. var expandoStore = expandoId && jqCache[expandoId];
  2518. if (expandoStore) {
  2519. if (name) {
  2520. delete expandoStore.data[name];
  2521. return;
  2522. }
  2523. if (expandoStore.handle) {
  2524. if (expandoStore.events.$destroy) {
  2525. expandoStore.handle({}, '$destroy');
  2526. }
  2527. jqLiteOff(element);
  2528. }
  2529. delete jqCache[expandoId];
  2530. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2531. }
  2532. }
  2533. function jqLiteExpandoStore(element, createIfNecessary) {
  2534. var expandoId = element.ng339,
  2535. expandoStore = expandoId && jqCache[expandoId];
  2536. if (createIfNecessary && !expandoStore) {
  2537. element.ng339 = expandoId = jqNextId();
  2538. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2539. }
  2540. return expandoStore;
  2541. }
  2542. function jqLiteData(element, key, value) {
  2543. if (jqLiteAcceptsData(element)) {
  2544. var isSimpleSetter = isDefined(value);
  2545. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2546. var massGetter = !key;
  2547. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2548. var data = expandoStore && expandoStore.data;
  2549. if (isSimpleSetter) { // data('key', value)
  2550. data[key] = value;
  2551. } else {
  2552. if (massGetter) { // data()
  2553. return data;
  2554. } else {
  2555. if (isSimpleGetter) { // data('key')
  2556. // don't force creation of expandoStore if it doesn't exist yet
  2557. return data && data[key];
  2558. } else { // mass-setter: data({key1: val1, key2: val2})
  2559. extend(data, key);
  2560. }
  2561. }
  2562. }
  2563. }
  2564. }
  2565. function jqLiteHasClass(element, selector) {
  2566. if (!element.getAttribute) return false;
  2567. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2568. indexOf(" " + selector + " ") > -1);
  2569. }
  2570. function jqLiteRemoveClass(element, cssClasses) {
  2571. if (cssClasses && element.setAttribute) {
  2572. forEach(cssClasses.split(' '), function(cssClass) {
  2573. element.setAttribute('class', trim(
  2574. (" " + (element.getAttribute('class') || '') + " ")
  2575. .replace(/[\n\t]/g, " ")
  2576. .replace(" " + trim(cssClass) + " ", " "))
  2577. );
  2578. });
  2579. }
  2580. }
  2581. function jqLiteAddClass(element, cssClasses) {
  2582. if (cssClasses && element.setAttribute) {
  2583. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2584. .replace(/[\n\t]/g, " ");
  2585. forEach(cssClasses.split(' '), function(cssClass) {
  2586. cssClass = trim(cssClass);
  2587. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2588. existingClasses += cssClass + ' ';
  2589. }
  2590. });
  2591. element.setAttribute('class', trim(existingClasses));
  2592. }
  2593. }
  2594. function jqLiteAddNodes(root, elements) {
  2595. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2596. if (elements) {
  2597. // if a Node (the most common case)
  2598. if (elements.nodeType) {
  2599. root[root.length++] = elements;
  2600. } else {
  2601. var length = elements.length;
  2602. // if an Array or NodeList and not a Window
  2603. if (typeof length === 'number' && elements.window !== elements) {
  2604. if (length) {
  2605. for (var i = 0; i < length; i++) {
  2606. root[root.length++] = elements[i];
  2607. }
  2608. }
  2609. } else {
  2610. root[root.length++] = elements;
  2611. }
  2612. }
  2613. }
  2614. }
  2615. function jqLiteController(element, name) {
  2616. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2617. }
  2618. function jqLiteInheritedData(element, name, value) {
  2619. // if element is the document object work with the html element instead
  2620. // this makes $(document).scope() possible
  2621. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2622. element = element.documentElement;
  2623. }
  2624. var names = isArray(name) ? name : [name];
  2625. while (element) {
  2626. for (var i = 0, ii = names.length; i < ii; i++) {
  2627. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2628. }
  2629. // If dealing with a document fragment node with a host element, and no parent, use the host
  2630. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2631. // to lookup parent controllers.
  2632. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2633. }
  2634. }
  2635. function jqLiteEmpty(element) {
  2636. jqLiteDealoc(element, true);
  2637. while (element.firstChild) {
  2638. element.removeChild(element.firstChild);
  2639. }
  2640. }
  2641. function jqLiteRemove(element, keepData) {
  2642. if (!keepData) jqLiteDealoc(element);
  2643. var parent = element.parentNode;
  2644. if (parent) parent.removeChild(element);
  2645. }
  2646. function jqLiteDocumentLoaded(action, win) {
  2647. win = win || window;
  2648. if (win.document.readyState === 'complete') {
  2649. // Force the action to be run async for consistent behaviour
  2650. // from the action's point of view
  2651. // i.e. it will definitely not be in a $apply
  2652. win.setTimeout(action);
  2653. } else {
  2654. // No need to unbind this handler as load is only ever called once
  2655. jqLite(win).on('load', action);
  2656. }
  2657. }
  2658. //////////////////////////////////////////
  2659. // Functions which are declared directly.
  2660. //////////////////////////////////////////
  2661. var JQLitePrototype = JQLite.prototype = {
  2662. ready: function(fn) {
  2663. var fired = false;
  2664. function trigger() {
  2665. if (fired) return;
  2666. fired = true;
  2667. fn();
  2668. }
  2669. // check if document is already loaded
  2670. if (document.readyState === 'complete') {
  2671. setTimeout(trigger);
  2672. } else {
  2673. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2674. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2675. // jshint -W064
  2676. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2677. // jshint +W064
  2678. }
  2679. },
  2680. toString: function() {
  2681. var value = [];
  2682. forEach(this, function(e) { value.push('' + e);});
  2683. return '[' + value.join(', ') + ']';
  2684. },
  2685. eq: function(index) {
  2686. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2687. },
  2688. length: 0,
  2689. push: push,
  2690. sort: [].sort,
  2691. splice: [].splice
  2692. };
  2693. //////////////////////////////////////////
  2694. // Functions iterating getter/setters.
  2695. // these functions return self on setter and
  2696. // value on get.
  2697. //////////////////////////////////////////
  2698. var BOOLEAN_ATTR = {};
  2699. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2700. BOOLEAN_ATTR[lowercase(value)] = value;
  2701. });
  2702. var BOOLEAN_ELEMENTS = {};
  2703. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2704. BOOLEAN_ELEMENTS[value] = true;
  2705. });
  2706. var ALIASED_ATTR = {
  2707. 'ngMinlength': 'minlength',
  2708. 'ngMaxlength': 'maxlength',
  2709. 'ngMin': 'min',
  2710. 'ngMax': 'max',
  2711. 'ngPattern': 'pattern'
  2712. };
  2713. function getBooleanAttrName(element, name) {
  2714. // check dom last since we will most likely fail on name
  2715. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2716. // booleanAttr is here twice to minimize DOM access
  2717. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2718. }
  2719. function getAliasedAttrName(element, name) {
  2720. var nodeName = element.nodeName;
  2721. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2722. }
  2723. forEach({
  2724. data: jqLiteData,
  2725. removeData: jqLiteRemoveData,
  2726. hasData: jqLiteHasData
  2727. }, function(fn, name) {
  2728. JQLite[name] = fn;
  2729. });
  2730. forEach({
  2731. data: jqLiteData,
  2732. inheritedData: jqLiteInheritedData,
  2733. scope: function(element) {
  2734. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2735. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2736. },
  2737. isolateScope: function(element) {
  2738. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2739. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2740. },
  2741. controller: jqLiteController,
  2742. injector: function(element) {
  2743. return jqLiteInheritedData(element, '$injector');
  2744. },
  2745. removeAttr: function(element, name) {
  2746. element.removeAttribute(name);
  2747. },
  2748. hasClass: jqLiteHasClass,
  2749. css: function(element, name, value) {
  2750. name = camelCase(name);
  2751. if (isDefined(value)) {
  2752. element.style[name] = value;
  2753. } else {
  2754. return element.style[name];
  2755. }
  2756. },
  2757. attr: function(element, name, value) {
  2758. var nodeType = element.nodeType;
  2759. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2760. return;
  2761. }
  2762. var lowercasedName = lowercase(name);
  2763. if (BOOLEAN_ATTR[lowercasedName]) {
  2764. if (isDefined(value)) {
  2765. if (!!value) {
  2766. element[name] = true;
  2767. element.setAttribute(name, lowercasedName);
  2768. } else {
  2769. element[name] = false;
  2770. element.removeAttribute(lowercasedName);
  2771. }
  2772. } else {
  2773. return (element[name] ||
  2774. (element.attributes.getNamedItem(name) || noop).specified)
  2775. ? lowercasedName
  2776. : undefined;
  2777. }
  2778. } else if (isDefined(value)) {
  2779. element.setAttribute(name, value);
  2780. } else if (element.getAttribute) {
  2781. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2782. // some elements (e.g. Document) don't have get attribute, so return undefined
  2783. var ret = element.getAttribute(name, 2);
  2784. // normalize non-existing attributes to undefined (as jQuery)
  2785. return ret === null ? undefined : ret;
  2786. }
  2787. },
  2788. prop: function(element, name, value) {
  2789. if (isDefined(value)) {
  2790. element[name] = value;
  2791. } else {
  2792. return element[name];
  2793. }
  2794. },
  2795. text: (function() {
  2796. getText.$dv = '';
  2797. return getText;
  2798. function getText(element, value) {
  2799. if (isUndefined(value)) {
  2800. var nodeType = element.nodeType;
  2801. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2802. }
  2803. element.textContent = value;
  2804. }
  2805. })(),
  2806. val: function(element, value) {
  2807. if (isUndefined(value)) {
  2808. if (element.multiple && nodeName_(element) === 'select') {
  2809. var result = [];
  2810. forEach(element.options, function(option) {
  2811. if (option.selected) {
  2812. result.push(option.value || option.text);
  2813. }
  2814. });
  2815. return result.length === 0 ? null : result;
  2816. }
  2817. return element.value;
  2818. }
  2819. element.value = value;
  2820. },
  2821. html: function(element, value) {
  2822. if (isUndefined(value)) {
  2823. return element.innerHTML;
  2824. }
  2825. jqLiteDealoc(element, true);
  2826. element.innerHTML = value;
  2827. },
  2828. empty: jqLiteEmpty
  2829. }, function(fn, name) {
  2830. /**
  2831. * Properties: writes return selection, reads return first value
  2832. */
  2833. JQLite.prototype[name] = function(arg1, arg2) {
  2834. var i, key;
  2835. var nodeCount = this.length;
  2836. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2837. // in a way that survives minification.
  2838. // jqLiteEmpty takes no arguments but is a setter.
  2839. if (fn !== jqLiteEmpty &&
  2840. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2841. if (isObject(arg1)) {
  2842. // we are a write, but the object properties are the key/values
  2843. for (i = 0; i < nodeCount; i++) {
  2844. if (fn === jqLiteData) {
  2845. // data() takes the whole object in jQuery
  2846. fn(this[i], arg1);
  2847. } else {
  2848. for (key in arg1) {
  2849. fn(this[i], key, arg1[key]);
  2850. }
  2851. }
  2852. }
  2853. // return self for chaining
  2854. return this;
  2855. } else {
  2856. // we are a read, so read the first child.
  2857. // TODO: do we still need this?
  2858. var value = fn.$dv;
  2859. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2860. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2861. for (var j = 0; j < jj; j++) {
  2862. var nodeValue = fn(this[j], arg1, arg2);
  2863. value = value ? value + nodeValue : nodeValue;
  2864. }
  2865. return value;
  2866. }
  2867. } else {
  2868. // we are a write, so apply to all children
  2869. for (i = 0; i < nodeCount; i++) {
  2870. fn(this[i], arg1, arg2);
  2871. }
  2872. // return self for chaining
  2873. return this;
  2874. }
  2875. };
  2876. });
  2877. function createEventHandler(element, events) {
  2878. var eventHandler = function(event, type) {
  2879. // jQuery specific api
  2880. event.isDefaultPrevented = function() {
  2881. return event.defaultPrevented;
  2882. };
  2883. var eventFns = events[type || event.type];
  2884. var eventFnsLength = eventFns ? eventFns.length : 0;
  2885. if (!eventFnsLength) return;
  2886. if (isUndefined(event.immediatePropagationStopped)) {
  2887. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2888. event.stopImmediatePropagation = function() {
  2889. event.immediatePropagationStopped = true;
  2890. if (event.stopPropagation) {
  2891. event.stopPropagation();
  2892. }
  2893. if (originalStopImmediatePropagation) {
  2894. originalStopImmediatePropagation.call(event);
  2895. }
  2896. };
  2897. }
  2898. event.isImmediatePropagationStopped = function() {
  2899. return event.immediatePropagationStopped === true;
  2900. };
  2901. // Copy event handlers in case event handlers array is modified during execution.
  2902. if ((eventFnsLength > 1)) {
  2903. eventFns = shallowCopy(eventFns);
  2904. }
  2905. for (var i = 0; i < eventFnsLength; i++) {
  2906. if (!event.isImmediatePropagationStopped()) {
  2907. eventFns[i].call(element, event);
  2908. }
  2909. }
  2910. };
  2911. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2912. // events on `element`
  2913. eventHandler.elem = element;
  2914. return eventHandler;
  2915. }
  2916. //////////////////////////////////////////
  2917. // Functions iterating traversal.
  2918. // These functions chain results into a single
  2919. // selector.
  2920. //////////////////////////////////////////
  2921. forEach({
  2922. removeData: jqLiteRemoveData,
  2923. on: function jqLiteOn(element, type, fn, unsupported) {
  2924. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2925. // Do not add event handlers to non-elements because they will not be cleaned up.
  2926. if (!jqLiteAcceptsData(element)) {
  2927. return;
  2928. }
  2929. var expandoStore = jqLiteExpandoStore(element, true);
  2930. var events = expandoStore.events;
  2931. var handle = expandoStore.handle;
  2932. if (!handle) {
  2933. handle = expandoStore.handle = createEventHandler(element, events);
  2934. }
  2935. // http://jsperf.com/string-indexof-vs-split
  2936. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2937. var i = types.length;
  2938. while (i--) {
  2939. type = types[i];
  2940. var eventFns = events[type];
  2941. if (!eventFns) {
  2942. events[type] = [];
  2943. if (type === 'mouseenter' || type === 'mouseleave') {
  2944. // Refer to jQuery's implementation of mouseenter & mouseleave
  2945. // Read about mouseenter and mouseleave:
  2946. // http://www.quirksmode.org/js/events_mouse.html#link8
  2947. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2948. var target = this, related = event.relatedTarget;
  2949. // For mousenter/leave call the handler if related is outside the target.
  2950. // NB: No relatedTarget if the mouse left/entered the browser window
  2951. if (!related || (related !== target && !target.contains(related))) {
  2952. handle(event, type);
  2953. }
  2954. });
  2955. } else {
  2956. if (type !== '$destroy') {
  2957. addEventListenerFn(element, type, handle);
  2958. }
  2959. }
  2960. eventFns = events[type];
  2961. }
  2962. eventFns.push(fn);
  2963. }
  2964. },
  2965. off: jqLiteOff,
  2966. one: function(element, type, fn) {
  2967. element = jqLite(element);
  2968. //add the listener twice so that when it is called
  2969. //you can remove the original function and still be
  2970. //able to call element.off(ev, fn) normally
  2971. element.on(type, function onFn() {
  2972. element.off(type, fn);
  2973. element.off(type, onFn);
  2974. });
  2975. element.on(type, fn);
  2976. },
  2977. replaceWith: function(element, replaceNode) {
  2978. var index, parent = element.parentNode;
  2979. jqLiteDealoc(element);
  2980. forEach(new JQLite(replaceNode), function(node) {
  2981. if (index) {
  2982. parent.insertBefore(node, index.nextSibling);
  2983. } else {
  2984. parent.replaceChild(node, element);
  2985. }
  2986. index = node;
  2987. });
  2988. },
  2989. children: function(element) {
  2990. var children = [];
  2991. forEach(element.childNodes, function(element) {
  2992. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2993. children.push(element);
  2994. }
  2995. });
  2996. return children;
  2997. },
  2998. contents: function(element) {
  2999. return element.contentDocument || element.childNodes || [];
  3000. },
  3001. append: function(element, node) {
  3002. var nodeType = element.nodeType;
  3003. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3004. node = new JQLite(node);
  3005. for (var i = 0, ii = node.length; i < ii; i++) {
  3006. var child = node[i];
  3007. element.appendChild(child);
  3008. }
  3009. },
  3010. prepend: function(element, node) {
  3011. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3012. var index = element.firstChild;
  3013. forEach(new JQLite(node), function(child) {
  3014. element.insertBefore(child, index);
  3015. });
  3016. }
  3017. },
  3018. wrap: function(element, wrapNode) {
  3019. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3020. var parent = element.parentNode;
  3021. if (parent) {
  3022. parent.replaceChild(wrapNode, element);
  3023. }
  3024. wrapNode.appendChild(element);
  3025. },
  3026. remove: jqLiteRemove,
  3027. detach: function(element) {
  3028. jqLiteRemove(element, true);
  3029. },
  3030. after: function(element, newElement) {
  3031. var index = element, parent = element.parentNode;
  3032. newElement = new JQLite(newElement);
  3033. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3034. var node = newElement[i];
  3035. parent.insertBefore(node, index.nextSibling);
  3036. index = node;
  3037. }
  3038. },
  3039. addClass: jqLiteAddClass,
  3040. removeClass: jqLiteRemoveClass,
  3041. toggleClass: function(element, selector, condition) {
  3042. if (selector) {
  3043. forEach(selector.split(' '), function(className) {
  3044. var classCondition = condition;
  3045. if (isUndefined(classCondition)) {
  3046. classCondition = !jqLiteHasClass(element, className);
  3047. }
  3048. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3049. });
  3050. }
  3051. },
  3052. parent: function(element) {
  3053. var parent = element.parentNode;
  3054. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3055. },
  3056. next: function(element) {
  3057. return element.nextElementSibling;
  3058. },
  3059. find: function(element, selector) {
  3060. if (element.getElementsByTagName) {
  3061. return element.getElementsByTagName(selector);
  3062. } else {
  3063. return [];
  3064. }
  3065. },
  3066. clone: jqLiteClone,
  3067. triggerHandler: function(element, event, extraParameters) {
  3068. var dummyEvent, eventFnsCopy, handlerArgs;
  3069. var eventName = event.type || event;
  3070. var expandoStore = jqLiteExpandoStore(element);
  3071. var events = expandoStore && expandoStore.events;
  3072. var eventFns = events && events[eventName];
  3073. if (eventFns) {
  3074. // Create a dummy event to pass to the handlers
  3075. dummyEvent = {
  3076. preventDefault: function() { this.defaultPrevented = true; },
  3077. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3078. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3079. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3080. stopPropagation: noop,
  3081. type: eventName,
  3082. target: element
  3083. };
  3084. // If a custom event was provided then extend our dummy event with it
  3085. if (event.type) {
  3086. dummyEvent = extend(dummyEvent, event);
  3087. }
  3088. // Copy event handlers in case event handlers array is modified during execution.
  3089. eventFnsCopy = shallowCopy(eventFns);
  3090. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3091. forEach(eventFnsCopy, function(fn) {
  3092. if (!dummyEvent.isImmediatePropagationStopped()) {
  3093. fn.apply(element, handlerArgs);
  3094. }
  3095. });
  3096. }
  3097. }
  3098. }, function(fn, name) {
  3099. /**
  3100. * chaining functions
  3101. */
  3102. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3103. var value;
  3104. for (var i = 0, ii = this.length; i < ii; i++) {
  3105. if (isUndefined(value)) {
  3106. value = fn(this[i], arg1, arg2, arg3);
  3107. if (isDefined(value)) {
  3108. // any function which returns a value needs to be wrapped
  3109. value = jqLite(value);
  3110. }
  3111. } else {
  3112. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3113. }
  3114. }
  3115. return isDefined(value) ? value : this;
  3116. };
  3117. // bind legacy bind/unbind to on/off
  3118. JQLite.prototype.bind = JQLite.prototype.on;
  3119. JQLite.prototype.unbind = JQLite.prototype.off;
  3120. });
  3121. // Provider for private $$jqLite service
  3122. function $$jqLiteProvider() {
  3123. this.$get = function $$jqLite() {
  3124. return extend(JQLite, {
  3125. hasClass: function(node, classes) {
  3126. if (node.attr) node = node[0];
  3127. return jqLiteHasClass(node, classes);
  3128. },
  3129. addClass: function(node, classes) {
  3130. if (node.attr) node = node[0];
  3131. return jqLiteAddClass(node, classes);
  3132. },
  3133. removeClass: function(node, classes) {
  3134. if (node.attr) node = node[0];
  3135. return jqLiteRemoveClass(node, classes);
  3136. }
  3137. });
  3138. };
  3139. }
  3140. /**
  3141. * Computes a hash of an 'obj'.
  3142. * Hash of a:
  3143. * string is string
  3144. * number is number as string
  3145. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3146. * that is also assigned to the $$hashKey property of the object.
  3147. *
  3148. * @param obj
  3149. * @returns {string} hash string such that the same input will have the same hash string.
  3150. * The resulting string key is in 'type:hashKey' format.
  3151. */
  3152. function hashKey(obj, nextUidFn) {
  3153. var key = obj && obj.$$hashKey;
  3154. if (key) {
  3155. if (typeof key === 'function') {
  3156. key = obj.$$hashKey();
  3157. }
  3158. return key;
  3159. }
  3160. var objType = typeof obj;
  3161. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3162. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3163. } else {
  3164. key = objType + ':' + obj;
  3165. }
  3166. return key;
  3167. }
  3168. /**
  3169. * HashMap which can use objects as keys
  3170. */
  3171. function HashMap(array, isolatedUid) {
  3172. if (isolatedUid) {
  3173. var uid = 0;
  3174. this.nextUid = function() {
  3175. return ++uid;
  3176. };
  3177. }
  3178. forEach(array, this.put, this);
  3179. }
  3180. HashMap.prototype = {
  3181. /**
  3182. * Store key value pair
  3183. * @param key key to store can be any type
  3184. * @param value value to store can be any type
  3185. */
  3186. put: function(key, value) {
  3187. this[hashKey(key, this.nextUid)] = value;
  3188. },
  3189. /**
  3190. * @param key
  3191. * @returns {Object} the value for the key
  3192. */
  3193. get: function(key) {
  3194. return this[hashKey(key, this.nextUid)];
  3195. },
  3196. /**
  3197. * Remove the key/value pair
  3198. * @param key
  3199. */
  3200. remove: function(key) {
  3201. var value = this[key = hashKey(key, this.nextUid)];
  3202. delete this[key];
  3203. return value;
  3204. }
  3205. };
  3206. var $$HashMapProvider = [function() {
  3207. this.$get = [function() {
  3208. return HashMap;
  3209. }];
  3210. }];
  3211. /**
  3212. * @ngdoc function
  3213. * @module ng
  3214. * @name angular.injector
  3215. * @kind function
  3216. *
  3217. * @description
  3218. * Creates an injector object that can be used for retrieving services as well as for
  3219. * dependency injection (see {@link guide/di dependency injection}).
  3220. *
  3221. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3222. * {@link angular.module}. The `ng` module must be explicitly added.
  3223. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3224. * disallows argument name annotation inference.
  3225. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3226. *
  3227. * @example
  3228. * Typical usage
  3229. * ```js
  3230. * // create an injector
  3231. * var $injector = angular.injector(['ng']);
  3232. *
  3233. * // use the injector to kick off your application
  3234. * // use the type inference to auto inject arguments, or use implicit injection
  3235. * $injector.invoke(function($rootScope, $compile, $document) {
  3236. * $compile($document)($rootScope);
  3237. * $rootScope.$digest();
  3238. * });
  3239. * ```
  3240. *
  3241. * Sometimes you want to get access to the injector of a currently running Angular app
  3242. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3243. * application has been bootstrapped. You can do this using the extra `injector()` added
  3244. * to JQuery/jqLite elements. See {@link angular.element}.
  3245. *
  3246. * *This is fairly rare but could be the case if a third party library is injecting the
  3247. * markup.*
  3248. *
  3249. * In the following example a new block of HTML containing a `ng-controller`
  3250. * directive is added to the end of the document body by JQuery. We then compile and link
  3251. * it into the current AngularJS scope.
  3252. *
  3253. * ```js
  3254. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3255. * $(document.body).append($div);
  3256. *
  3257. * angular.element(document).injector().invoke(function($compile) {
  3258. * var scope = angular.element($div).scope();
  3259. * $compile($div)(scope);
  3260. * });
  3261. * ```
  3262. */
  3263. /**
  3264. * @ngdoc module
  3265. * @name auto
  3266. * @description
  3267. *
  3268. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3269. */
  3270. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3271. var FN_ARG_SPLIT = /,/;
  3272. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3273. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3274. var $injectorMinErr = minErr('$injector');
  3275. function anonFn(fn) {
  3276. // For anonymous functions, showing at the very least the function signature can help in
  3277. // debugging.
  3278. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3279. args = fnText.match(FN_ARGS);
  3280. if (args) {
  3281. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3282. }
  3283. return 'fn';
  3284. }
  3285. function annotate(fn, strictDi, name) {
  3286. var $inject,
  3287. fnText,
  3288. argDecl,
  3289. last;
  3290. if (typeof fn === 'function') {
  3291. if (!($inject = fn.$inject)) {
  3292. $inject = [];
  3293. if (fn.length) {
  3294. if (strictDi) {
  3295. if (!isString(name) || !name) {
  3296. name = fn.name || anonFn(fn);
  3297. }
  3298. throw $injectorMinErr('strictdi',
  3299. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3300. }
  3301. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3302. argDecl = fnText.match(FN_ARGS);
  3303. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3304. arg.replace(FN_ARG, function(all, underscore, name) {
  3305. $inject.push(name);
  3306. });
  3307. });
  3308. }
  3309. fn.$inject = $inject;
  3310. }
  3311. } else if (isArray(fn)) {
  3312. last = fn.length - 1;
  3313. assertArgFn(fn[last], 'fn');
  3314. $inject = fn.slice(0, last);
  3315. } else {
  3316. assertArgFn(fn, 'fn', true);
  3317. }
  3318. return $inject;
  3319. }
  3320. ///////////////////////////////////////
  3321. /**
  3322. * @ngdoc service
  3323. * @name $injector
  3324. *
  3325. * @description
  3326. *
  3327. * `$injector` is used to retrieve object instances as defined by
  3328. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3329. * and load modules.
  3330. *
  3331. * The following always holds true:
  3332. *
  3333. * ```js
  3334. * var $injector = angular.injector();
  3335. * expect($injector.get('$injector')).toBe($injector);
  3336. * expect($injector.invoke(function($injector) {
  3337. * return $injector;
  3338. * })).toBe($injector);
  3339. * ```
  3340. *
  3341. * # Injection Function Annotation
  3342. *
  3343. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3344. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3345. *
  3346. * ```js
  3347. * // inferred (only works if code not minified/obfuscated)
  3348. * $injector.invoke(function(serviceA){});
  3349. *
  3350. * // annotated
  3351. * function explicit(serviceA) {};
  3352. * explicit.$inject = ['serviceA'];
  3353. * $injector.invoke(explicit);
  3354. *
  3355. * // inline
  3356. * $injector.invoke(['serviceA', function(serviceA){}]);
  3357. * ```
  3358. *
  3359. * ## Inference
  3360. *
  3361. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3362. * can then be parsed and the function arguments can be extracted. This method of discovering
  3363. * annotations is disallowed when the injector is in strict mode.
  3364. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3365. * argument names.
  3366. *
  3367. * ## `$inject` Annotation
  3368. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3369. *
  3370. * ## Inline
  3371. * As an array of injection names, where the last item in the array is the function to call.
  3372. */
  3373. /**
  3374. * @ngdoc method
  3375. * @name $injector#get
  3376. *
  3377. * @description
  3378. * Return an instance of the service.
  3379. *
  3380. * @param {string} name The name of the instance to retrieve.
  3381. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3382. * @return {*} The instance.
  3383. */
  3384. /**
  3385. * @ngdoc method
  3386. * @name $injector#invoke
  3387. *
  3388. * @description
  3389. * Invoke the method and supply the method arguments from the `$injector`.
  3390. *
  3391. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3392. * injected according to the {@link guide/di $inject Annotation} rules.
  3393. * @param {Object=} self The `this` for the invoked method.
  3394. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3395. * object first, before the `$injector` is consulted.
  3396. * @returns {*} the value returned by the invoked `fn` function.
  3397. */
  3398. /**
  3399. * @ngdoc method
  3400. * @name $injector#has
  3401. *
  3402. * @description
  3403. * Allows the user to query if the particular service exists.
  3404. *
  3405. * @param {string} name Name of the service to query.
  3406. * @returns {boolean} `true` if injector has given service.
  3407. */
  3408. /**
  3409. * @ngdoc method
  3410. * @name $injector#instantiate
  3411. * @description
  3412. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3413. * operator, and supplies all of the arguments to the constructor function as specified by the
  3414. * constructor annotation.
  3415. *
  3416. * @param {Function} Type Annotated constructor function.
  3417. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3418. * object first, before the `$injector` is consulted.
  3419. * @returns {Object} new instance of `Type`.
  3420. */
  3421. /**
  3422. * @ngdoc method
  3423. * @name $injector#annotate
  3424. *
  3425. * @description
  3426. * Returns an array of service names which the function is requesting for injection. This API is
  3427. * used by the injector to determine which services need to be injected into the function when the
  3428. * function is invoked. There are three ways in which the function can be annotated with the needed
  3429. * dependencies.
  3430. *
  3431. * # Argument names
  3432. *
  3433. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3434. * by converting the function into a string using `toString()` method and extracting the argument
  3435. * names.
  3436. * ```js
  3437. * // Given
  3438. * function MyController($scope, $route) {
  3439. * // ...
  3440. * }
  3441. *
  3442. * // Then
  3443. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3444. * ```
  3445. *
  3446. * You can disallow this method by using strict injection mode.
  3447. *
  3448. * This method does not work with code minification / obfuscation. For this reason the following
  3449. * annotation strategies are supported.
  3450. *
  3451. * # The `$inject` property
  3452. *
  3453. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3454. * represent names of services to be injected into the function.
  3455. * ```js
  3456. * // Given
  3457. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3458. * // ...
  3459. * }
  3460. * // Define function dependencies
  3461. * MyController['$inject'] = ['$scope', '$route'];
  3462. *
  3463. * // Then
  3464. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3465. * ```
  3466. *
  3467. * # The array notation
  3468. *
  3469. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3470. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3471. * a way that survives minification is a better choice:
  3472. *
  3473. * ```js
  3474. * // We wish to write this (not minification / obfuscation safe)
  3475. * injector.invoke(function($compile, $rootScope) {
  3476. * // ...
  3477. * });
  3478. *
  3479. * // We are forced to write break inlining
  3480. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3481. * // ...
  3482. * };
  3483. * tmpFn.$inject = ['$compile', '$rootScope'];
  3484. * injector.invoke(tmpFn);
  3485. *
  3486. * // To better support inline function the inline annotation is supported
  3487. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3488. * // ...
  3489. * }]);
  3490. *
  3491. * // Therefore
  3492. * expect(injector.annotate(
  3493. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3494. * ).toEqual(['$compile', '$rootScope']);
  3495. * ```
  3496. *
  3497. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3498. * be retrieved as described above.
  3499. *
  3500. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3501. *
  3502. * @returns {Array.<string>} The names of the services which the function requires.
  3503. */
  3504. /**
  3505. * @ngdoc service
  3506. * @name $provide
  3507. *
  3508. * @description
  3509. *
  3510. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3511. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3512. * {@link angular.Module}.
  3513. *
  3514. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3515. * factories** are functions which, in turn, are created by a **service provider**.
  3516. * The **service providers** are constructor functions. When instantiated they must contain a
  3517. * property called `$get`, which holds the **service factory** function.
  3518. *
  3519. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3520. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3521. * function to get the instance of the **service**.
  3522. *
  3523. * Often services have no configuration options and there is no need to add methods to the service
  3524. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3525. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3526. * services without specifying a provider.
  3527. *
  3528. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3529. * {@link auto.$injector $injector}
  3530. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3531. * providers and services.
  3532. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3533. * services, not providers.
  3534. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3535. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3536. * given factory function.
  3537. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3538. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3539. * a new object using the given constructor function.
  3540. *
  3541. * See the individual methods for more information and examples.
  3542. */
  3543. /**
  3544. * @ngdoc method
  3545. * @name $provide#provider
  3546. * @description
  3547. *
  3548. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3549. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3550. * service.
  3551. *
  3552. * Service provider names start with the name of the service they provide followed by `Provider`.
  3553. * For example, the {@link ng.$log $log} service has a provider called
  3554. * {@link ng.$logProvider $logProvider}.
  3555. *
  3556. * Service provider objects can have additional methods which allow configuration of the provider
  3557. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3558. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3559. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3560. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3561. * console or not.
  3562. *
  3563. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3564. 'Provider'` key.
  3565. * @param {(Object|function())} provider If the provider is:
  3566. *
  3567. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3568. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3569. * - `Constructor`: a new instance of the provider will be created using
  3570. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3571. *
  3572. * @returns {Object} registered provider instance
  3573. * @example
  3574. *
  3575. * The following example shows how to create a simple event tracking service and register it using
  3576. * {@link auto.$provide#provider $provide.provider()}.
  3577. *
  3578. * ```js
  3579. * // Define the eventTracker provider
  3580. * function EventTrackerProvider() {
  3581. * var trackingUrl = '/track';
  3582. *
  3583. * // A provider method for configuring where the tracked events should been saved
  3584. * this.setTrackingUrl = function(url) {
  3585. * trackingUrl = url;
  3586. * };
  3587. *
  3588. * // The service factory function
  3589. * this.$get = ['$http', function($http) {
  3590. * var trackedEvents = {};
  3591. * return {
  3592. * // Call this to track an event
  3593. * event: function(event) {
  3594. * var count = trackedEvents[event] || 0;
  3595. * count += 1;
  3596. * trackedEvents[event] = count;
  3597. * return count;
  3598. * },
  3599. * // Call this to save the tracked events to the trackingUrl
  3600. * save: function() {
  3601. * $http.post(trackingUrl, trackedEvents);
  3602. * }
  3603. * };
  3604. * }];
  3605. * }
  3606. *
  3607. * describe('eventTracker', function() {
  3608. * var postSpy;
  3609. *
  3610. * beforeEach(module(function($provide) {
  3611. * // Register the eventTracker provider
  3612. * $provide.provider('eventTracker', EventTrackerProvider);
  3613. * }));
  3614. *
  3615. * beforeEach(module(function(eventTrackerProvider) {
  3616. * // Configure eventTracker provider
  3617. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3618. * }));
  3619. *
  3620. * it('tracks events', inject(function(eventTracker) {
  3621. * expect(eventTracker.event('login')).toEqual(1);
  3622. * expect(eventTracker.event('login')).toEqual(2);
  3623. * }));
  3624. *
  3625. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3626. * postSpy = spyOn($http, 'post');
  3627. * eventTracker.event('login');
  3628. * eventTracker.save();
  3629. * expect(postSpy).toHaveBeenCalled();
  3630. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3631. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3632. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3633. * }));
  3634. * });
  3635. * ```
  3636. */
  3637. /**
  3638. * @ngdoc method
  3639. * @name $provide#factory
  3640. * @description
  3641. *
  3642. * Register a **service factory**, which will be called to return the service instance.
  3643. * This is short for registering a service where its provider consists of only a `$get` property,
  3644. * which is the given service factory function.
  3645. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3646. * configure your service in a provider.
  3647. *
  3648. * @param {string} name The name of the instance.
  3649. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3650. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3651. * @returns {Object} registered provider instance
  3652. *
  3653. * @example
  3654. * Here is an example of registering a service
  3655. * ```js
  3656. * $provide.factory('ping', ['$http', function($http) {
  3657. * return function ping() {
  3658. * return $http.send('/ping');
  3659. * };
  3660. * }]);
  3661. * ```
  3662. * You would then inject and use this service like this:
  3663. * ```js
  3664. * someModule.controller('Ctrl', ['ping', function(ping) {
  3665. * ping();
  3666. * }]);
  3667. * ```
  3668. */
  3669. /**
  3670. * @ngdoc method
  3671. * @name $provide#service
  3672. * @description
  3673. *
  3674. * Register a **service constructor**, which will be invoked with `new` to create the service
  3675. * instance.
  3676. * This is short for registering a service where its provider's `$get` property is the service
  3677. * constructor function that will be used to instantiate the service instance.
  3678. *
  3679. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3680. * as a type/class.
  3681. *
  3682. * @param {string} name The name of the instance.
  3683. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3684. * that will be instantiated.
  3685. * @returns {Object} registered provider instance
  3686. *
  3687. * @example
  3688. * Here is an example of registering a service using
  3689. * {@link auto.$provide#service $provide.service(class)}.
  3690. * ```js
  3691. * var Ping = function($http) {
  3692. * this.$http = $http;
  3693. * };
  3694. *
  3695. * Ping.$inject = ['$http'];
  3696. *
  3697. * Ping.prototype.send = function() {
  3698. * return this.$http.get('/ping');
  3699. * };
  3700. * $provide.service('ping', Ping);
  3701. * ```
  3702. * You would then inject and use this service like this:
  3703. * ```js
  3704. * someModule.controller('Ctrl', ['ping', function(ping) {
  3705. * ping.send();
  3706. * }]);
  3707. * ```
  3708. */
  3709. /**
  3710. * @ngdoc method
  3711. * @name $provide#value
  3712. * @description
  3713. *
  3714. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3715. * number, an array, an object or a function. This is short for registering a service where its
  3716. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3717. * service**.
  3718. *
  3719. * Value services are similar to constant services, except that they cannot be injected into a
  3720. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3721. * an Angular
  3722. * {@link auto.$provide#decorator decorator}.
  3723. *
  3724. * @param {string} name The name of the instance.
  3725. * @param {*} value The value.
  3726. * @returns {Object} registered provider instance
  3727. *
  3728. * @example
  3729. * Here are some examples of creating value services.
  3730. * ```js
  3731. * $provide.value('ADMIN_USER', 'admin');
  3732. *
  3733. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3734. *
  3735. * $provide.value('halfOf', function(value) {
  3736. * return value / 2;
  3737. * });
  3738. * ```
  3739. */
  3740. /**
  3741. * @ngdoc method
  3742. * @name $provide#constant
  3743. * @description
  3744. *
  3745. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3746. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3747. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3748. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3749. *
  3750. * @param {string} name The name of the constant.
  3751. * @param {*} value The constant value.
  3752. * @returns {Object} registered instance
  3753. *
  3754. * @example
  3755. * Here a some examples of creating constants:
  3756. * ```js
  3757. * $provide.constant('SHARD_HEIGHT', 306);
  3758. *
  3759. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3760. *
  3761. * $provide.constant('double', function(value) {
  3762. * return value * 2;
  3763. * });
  3764. * ```
  3765. */
  3766. /**
  3767. * @ngdoc method
  3768. * @name $provide#decorator
  3769. * @description
  3770. *
  3771. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3772. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3773. * service. The object returned by the decorator may be the original service, or a new service
  3774. * object which replaces or wraps and delegates to the original service.
  3775. *
  3776. * @param {string} name The name of the service to decorate.
  3777. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3778. * instantiated and should return the decorated service instance. The function is called using
  3779. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3780. * Local injection arguments:
  3781. *
  3782. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3783. * decorated or delegated to.
  3784. *
  3785. * @example
  3786. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3787. * calls to {@link ng.$log#error $log.warn()}.
  3788. * ```js
  3789. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3790. * $delegate.warn = $delegate.error;
  3791. * return $delegate;
  3792. * }]);
  3793. * ```
  3794. */
  3795. function createInjector(modulesToLoad, strictDi) {
  3796. strictDi = (strictDi === true);
  3797. var INSTANTIATING = {},
  3798. providerSuffix = 'Provider',
  3799. path = [],
  3800. loadedModules = new HashMap([], true),
  3801. providerCache = {
  3802. $provide: {
  3803. provider: supportObject(provider),
  3804. factory: supportObject(factory),
  3805. service: supportObject(service),
  3806. value: supportObject(value),
  3807. constant: supportObject(constant),
  3808. decorator: decorator
  3809. }
  3810. },
  3811. providerInjector = (providerCache.$injector =
  3812. createInternalInjector(providerCache, function(serviceName, caller) {
  3813. if (angular.isString(caller)) {
  3814. path.push(caller);
  3815. }
  3816. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3817. })),
  3818. instanceCache = {},
  3819. instanceInjector = (instanceCache.$injector =
  3820. createInternalInjector(instanceCache, function(serviceName, caller) {
  3821. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3822. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3823. }));
  3824. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3825. return instanceInjector;
  3826. ////////////////////////////////////
  3827. // $provider
  3828. ////////////////////////////////////
  3829. function supportObject(delegate) {
  3830. return function(key, value) {
  3831. if (isObject(key)) {
  3832. forEach(key, reverseParams(delegate));
  3833. } else {
  3834. return delegate(key, value);
  3835. }
  3836. };
  3837. }
  3838. function provider(name, provider_) {
  3839. assertNotHasOwnProperty(name, 'service');
  3840. if (isFunction(provider_) || isArray(provider_)) {
  3841. provider_ = providerInjector.instantiate(provider_);
  3842. }
  3843. if (!provider_.$get) {
  3844. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3845. }
  3846. return providerCache[name + providerSuffix] = provider_;
  3847. }
  3848. function enforceReturnValue(name, factory) {
  3849. return function enforcedReturnValue() {
  3850. var result = instanceInjector.invoke(factory, this);
  3851. if (isUndefined(result)) {
  3852. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3853. }
  3854. return result;
  3855. };
  3856. }
  3857. function factory(name, factoryFn, enforce) {
  3858. return provider(name, {
  3859. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3860. });
  3861. }
  3862. function service(name, constructor) {
  3863. return factory(name, ['$injector', function($injector) {
  3864. return $injector.instantiate(constructor);
  3865. }]);
  3866. }
  3867. function value(name, val) { return factory(name, valueFn(val), false); }
  3868. function constant(name, value) {
  3869. assertNotHasOwnProperty(name, 'constant');
  3870. providerCache[name] = value;
  3871. instanceCache[name] = value;
  3872. }
  3873. function decorator(serviceName, decorFn) {
  3874. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3875. orig$get = origProvider.$get;
  3876. origProvider.$get = function() {
  3877. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3878. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3879. };
  3880. }
  3881. ////////////////////////////////////
  3882. // Module Loading
  3883. ////////////////////////////////////
  3884. function loadModules(modulesToLoad) {
  3885. var runBlocks = [], moduleFn;
  3886. forEach(modulesToLoad, function(module) {
  3887. if (loadedModules.get(module)) return;
  3888. loadedModules.put(module, true);
  3889. function runInvokeQueue(queue) {
  3890. var i, ii;
  3891. for (i = 0, ii = queue.length; i < ii; i++) {
  3892. var invokeArgs = queue[i],
  3893. provider = providerInjector.get(invokeArgs[0]);
  3894. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3895. }
  3896. }
  3897. try {
  3898. if (isString(module)) {
  3899. moduleFn = angularModule(module);
  3900. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3901. runInvokeQueue(moduleFn._invokeQueue);
  3902. runInvokeQueue(moduleFn._configBlocks);
  3903. } else if (isFunction(module)) {
  3904. runBlocks.push(providerInjector.invoke(module));
  3905. } else if (isArray(module)) {
  3906. runBlocks.push(providerInjector.invoke(module));
  3907. } else {
  3908. assertArgFn(module, 'module');
  3909. }
  3910. } catch (e) {
  3911. if (isArray(module)) {
  3912. module = module[module.length - 1];
  3913. }
  3914. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3915. // Safari & FF's stack traces don't contain error.message content
  3916. // unlike those of Chrome and IE
  3917. // So if stack doesn't contain message, we create a new string that contains both.
  3918. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3919. /* jshint -W022 */
  3920. e = e.message + '\n' + e.stack;
  3921. }
  3922. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3923. module, e.stack || e.message || e);
  3924. }
  3925. });
  3926. return runBlocks;
  3927. }
  3928. ////////////////////////////////////
  3929. // internal Injector
  3930. ////////////////////////////////////
  3931. function createInternalInjector(cache, factory) {
  3932. function getService(serviceName, caller) {
  3933. if (cache.hasOwnProperty(serviceName)) {
  3934. if (cache[serviceName] === INSTANTIATING) {
  3935. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3936. serviceName + ' <- ' + path.join(' <- '));
  3937. }
  3938. return cache[serviceName];
  3939. } else {
  3940. try {
  3941. path.unshift(serviceName);
  3942. cache[serviceName] = INSTANTIATING;
  3943. return cache[serviceName] = factory(serviceName, caller);
  3944. } catch (err) {
  3945. if (cache[serviceName] === INSTANTIATING) {
  3946. delete cache[serviceName];
  3947. }
  3948. throw err;
  3949. } finally {
  3950. path.shift();
  3951. }
  3952. }
  3953. }
  3954. function invoke(fn, self, locals, serviceName) {
  3955. if (typeof locals === 'string') {
  3956. serviceName = locals;
  3957. locals = null;
  3958. }
  3959. var args = [],
  3960. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3961. length, i,
  3962. key;
  3963. for (i = 0, length = $inject.length; i < length; i++) {
  3964. key = $inject[i];
  3965. if (typeof key !== 'string') {
  3966. throw $injectorMinErr('itkn',
  3967. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3968. }
  3969. args.push(
  3970. locals && locals.hasOwnProperty(key)
  3971. ? locals[key]
  3972. : getService(key, serviceName)
  3973. );
  3974. }
  3975. if (isArray(fn)) {
  3976. fn = fn[length];
  3977. }
  3978. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3979. // #5388
  3980. return fn.apply(self, args);
  3981. }
  3982. function instantiate(Type, locals, serviceName) {
  3983. // Check if Type is annotated and use just the given function at n-1 as parameter
  3984. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3985. // Object creation: http://jsperf.com/create-constructor/2
  3986. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3987. var returnedValue = invoke(Type, instance, locals, serviceName);
  3988. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3989. }
  3990. return {
  3991. invoke: invoke,
  3992. instantiate: instantiate,
  3993. get: getService,
  3994. annotate: createInjector.$$annotate,
  3995. has: function(name) {
  3996. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3997. }
  3998. };
  3999. }
  4000. }
  4001. createInjector.$$annotate = annotate;
  4002. /**
  4003. * @ngdoc provider
  4004. * @name $anchorScrollProvider
  4005. *
  4006. * @description
  4007. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4008. * {@link ng.$location#hash $location.hash()} changes.
  4009. */
  4010. function $AnchorScrollProvider() {
  4011. var autoScrollingEnabled = true;
  4012. /**
  4013. * @ngdoc method
  4014. * @name $anchorScrollProvider#disableAutoScrolling
  4015. *
  4016. * @description
  4017. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4018. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4019. * Use this method to disable automatic scrolling.
  4020. *
  4021. * If automatic scrolling is disabled, one must explicitly call
  4022. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4023. * current hash.
  4024. */
  4025. this.disableAutoScrolling = function() {
  4026. autoScrollingEnabled = false;
  4027. };
  4028. /**
  4029. * @ngdoc service
  4030. * @name $anchorScroll
  4031. * @kind function
  4032. * @requires $window
  4033. * @requires $location
  4034. * @requires $rootScope
  4035. *
  4036. * @description
  4037. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4038. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4039. * in the
  4040. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4041. *
  4042. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4043. * match any anchor whenever it changes. This can be disabled by calling
  4044. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4045. *
  4046. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4047. * vertical scroll-offset (either fixed or dynamic).
  4048. *
  4049. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4050. * {@link ng.$location#hash $location.hash()} will be used.
  4051. *
  4052. * @property {(number|function|jqLite)} yOffset
  4053. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4054. * positioned elements at the top of the page, such as navbars, headers etc.
  4055. *
  4056. * `yOffset` can be specified in various ways:
  4057. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4058. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4059. * a number representing the offset (in pixels).<br /><br />
  4060. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4061. * the top of the page to the element's bottom will be used as offset.<br />
  4062. * **Note**: The element will be taken into account only as long as its `position` is set to
  4063. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4064. * their height and/or positioning according to the viewport's size.
  4065. *
  4066. * <br />
  4067. * <div class="alert alert-warning">
  4068. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4069. * not some child element.
  4070. * </div>
  4071. *
  4072. * @example
  4073. <example module="anchorScrollExample">
  4074. <file name="index.html">
  4075. <div id="scrollArea" ng-controller="ScrollController">
  4076. <a ng-click="gotoBottom()">Go to bottom</a>
  4077. <a id="bottom"></a> You're at the bottom!
  4078. </div>
  4079. </file>
  4080. <file name="script.js">
  4081. angular.module('anchorScrollExample', [])
  4082. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4083. function ($scope, $location, $anchorScroll) {
  4084. $scope.gotoBottom = function() {
  4085. // set the location.hash to the id of
  4086. // the element you wish to scroll to.
  4087. $location.hash('bottom');
  4088. // call $anchorScroll()
  4089. $anchorScroll();
  4090. };
  4091. }]);
  4092. </file>
  4093. <file name="style.css">
  4094. #scrollArea {
  4095. height: 280px;
  4096. overflow: auto;
  4097. }
  4098. #bottom {
  4099. display: block;
  4100. margin-top: 2000px;
  4101. }
  4102. </file>
  4103. </example>
  4104. *
  4105. * <hr />
  4106. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4107. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4108. *
  4109. * @example
  4110. <example module="anchorScrollOffsetExample">
  4111. <file name="index.html">
  4112. <div class="fixed-header" ng-controller="headerCtrl">
  4113. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4114. Go to anchor {{x}}
  4115. </a>
  4116. </div>
  4117. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4118. Anchor {{x}} of 5
  4119. </div>
  4120. </file>
  4121. <file name="script.js">
  4122. angular.module('anchorScrollOffsetExample', [])
  4123. .run(['$anchorScroll', function($anchorScroll) {
  4124. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4125. }])
  4126. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4127. function ($anchorScroll, $location, $scope) {
  4128. $scope.gotoAnchor = function(x) {
  4129. var newHash = 'anchor' + x;
  4130. if ($location.hash() !== newHash) {
  4131. // set the $location.hash to `newHash` and
  4132. // $anchorScroll will automatically scroll to it
  4133. $location.hash('anchor' + x);
  4134. } else {
  4135. // call $anchorScroll() explicitly,
  4136. // since $location.hash hasn't changed
  4137. $anchorScroll();
  4138. }
  4139. };
  4140. }
  4141. ]);
  4142. </file>
  4143. <file name="style.css">
  4144. body {
  4145. padding-top: 50px;
  4146. }
  4147. .anchor {
  4148. border: 2px dashed DarkOrchid;
  4149. padding: 10px 10px 200px 10px;
  4150. }
  4151. .fixed-header {
  4152. background-color: rgba(0, 0, 0, 0.2);
  4153. height: 50px;
  4154. position: fixed;
  4155. top: 0; left: 0; right: 0;
  4156. }
  4157. .fixed-header > a {
  4158. display: inline-block;
  4159. margin: 5px 15px;
  4160. }
  4161. </file>
  4162. </example>
  4163. */
  4164. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4165. var document = $window.document;
  4166. // Helper function to get first anchor from a NodeList
  4167. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4168. // and working in all supported browsers.)
  4169. function getFirstAnchor(list) {
  4170. var result = null;
  4171. Array.prototype.some.call(list, function(element) {
  4172. if (nodeName_(element) === 'a') {
  4173. result = element;
  4174. return true;
  4175. }
  4176. });
  4177. return result;
  4178. }
  4179. function getYOffset() {
  4180. var offset = scroll.yOffset;
  4181. if (isFunction(offset)) {
  4182. offset = offset();
  4183. } else if (isElement(offset)) {
  4184. var elem = offset[0];
  4185. var style = $window.getComputedStyle(elem);
  4186. if (style.position !== 'fixed') {
  4187. offset = 0;
  4188. } else {
  4189. offset = elem.getBoundingClientRect().bottom;
  4190. }
  4191. } else if (!isNumber(offset)) {
  4192. offset = 0;
  4193. }
  4194. return offset;
  4195. }
  4196. function scrollTo(elem) {
  4197. if (elem) {
  4198. elem.scrollIntoView();
  4199. var offset = getYOffset();
  4200. if (offset) {
  4201. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4202. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4203. // top of the viewport.
  4204. //
  4205. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4206. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4207. // way down the page.
  4208. //
  4209. // This is often the case for elements near the bottom of the page.
  4210. //
  4211. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4212. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4213. // desired position.
  4214. var elemTop = elem.getBoundingClientRect().top;
  4215. $window.scrollBy(0, elemTop - offset);
  4216. }
  4217. } else {
  4218. $window.scrollTo(0, 0);
  4219. }
  4220. }
  4221. function scroll(hash) {
  4222. hash = isString(hash) ? hash : $location.hash();
  4223. var elm;
  4224. // empty hash, scroll to the top of the page
  4225. if (!hash) scrollTo(null);
  4226. // element with given id
  4227. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4228. // first anchor with given name :-D
  4229. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4230. // no element and hash == 'top', scroll to the top of the page
  4231. else if (hash === 'top') scrollTo(null);
  4232. }
  4233. // does not scroll when user clicks on anchor link that is currently on
  4234. // (no url change, no $location.hash() change), browser native does scroll
  4235. if (autoScrollingEnabled) {
  4236. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4237. function autoScrollWatchAction(newVal, oldVal) {
  4238. // skip the initial scroll if $location.hash is empty
  4239. if (newVal === oldVal && newVal === '') return;
  4240. jqLiteDocumentLoaded(function() {
  4241. $rootScope.$evalAsync(scroll);
  4242. });
  4243. });
  4244. }
  4245. return scroll;
  4246. }];
  4247. }
  4248. var $animateMinErr = minErr('$animate');
  4249. var ELEMENT_NODE = 1;
  4250. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4251. function mergeClasses(a,b) {
  4252. if (!a && !b) return '';
  4253. if (!a) return b;
  4254. if (!b) return a;
  4255. if (isArray(a)) a = a.join(' ');
  4256. if (isArray(b)) b = b.join(' ');
  4257. return a + ' ' + b;
  4258. }
  4259. function extractElementNode(element) {
  4260. for (var i = 0; i < element.length; i++) {
  4261. var elm = element[i];
  4262. if (elm.nodeType === ELEMENT_NODE) {
  4263. return elm;
  4264. }
  4265. }
  4266. }
  4267. function splitClasses(classes) {
  4268. if (isString(classes)) {
  4269. classes = classes.split(' ');
  4270. }
  4271. // Use createMap() to prevent class assumptions involving property names in
  4272. // Object.prototype
  4273. var obj = createMap();
  4274. forEach(classes, function(klass) {
  4275. // sometimes the split leaves empty string values
  4276. // incase extra spaces were applied to the options
  4277. if (klass.length) {
  4278. obj[klass] = true;
  4279. }
  4280. });
  4281. return obj;
  4282. }
  4283. // if any other type of options value besides an Object value is
  4284. // passed into the $animate.method() animation then this helper code
  4285. // will be run which will ignore it. While this patch is not the
  4286. // greatest solution to this, a lot of existing plugins depend on
  4287. // $animate to either call the callback (< 1.2) or return a promise
  4288. // that can be changed. This helper function ensures that the options
  4289. // are wiped clean incase a callback function is provided.
  4290. function prepareAnimateOptions(options) {
  4291. return isObject(options)
  4292. ? options
  4293. : {};
  4294. }
  4295. var $$CoreAnimateRunnerProvider = function() {
  4296. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4297. function AnimateRunner() {}
  4298. AnimateRunner.all = noop;
  4299. AnimateRunner.chain = noop;
  4300. AnimateRunner.prototype = {
  4301. end: noop,
  4302. cancel: noop,
  4303. resume: noop,
  4304. pause: noop,
  4305. complete: noop,
  4306. then: function(pass, fail) {
  4307. return $q(function(resolve) {
  4308. $$rAF(function() {
  4309. resolve();
  4310. });
  4311. }).then(pass, fail);
  4312. }
  4313. };
  4314. return AnimateRunner;
  4315. }];
  4316. };
  4317. // this is prefixed with Core since it conflicts with
  4318. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4319. var $$CoreAnimateQueueProvider = function() {
  4320. var postDigestQueue = new HashMap();
  4321. var postDigestElements = [];
  4322. this.$get = ['$$AnimateRunner', '$rootScope',
  4323. function($$AnimateRunner, $rootScope) {
  4324. return {
  4325. enabled: noop,
  4326. on: noop,
  4327. off: noop,
  4328. pin: noop,
  4329. push: function(element, event, options, domOperation) {
  4330. domOperation && domOperation();
  4331. options = options || {};
  4332. options.from && element.css(options.from);
  4333. options.to && element.css(options.to);
  4334. if (options.addClass || options.removeClass) {
  4335. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4336. }
  4337. return new $$AnimateRunner(); // jshint ignore:line
  4338. }
  4339. };
  4340. function addRemoveClassesPostDigest(element, add, remove) {
  4341. var data = postDigestQueue.get(element);
  4342. var classVal;
  4343. if (!data) {
  4344. postDigestQueue.put(element, data = {});
  4345. postDigestElements.push(element);
  4346. }
  4347. if (add) {
  4348. forEach(add.split(' '), function(className) {
  4349. if (className) {
  4350. data[className] = true;
  4351. }
  4352. });
  4353. }
  4354. if (remove) {
  4355. forEach(remove.split(' '), function(className) {
  4356. if (className) {
  4357. data[className] = false;
  4358. }
  4359. });
  4360. }
  4361. if (postDigestElements.length > 1) return;
  4362. $rootScope.$$postDigest(function() {
  4363. forEach(postDigestElements, function(element) {
  4364. var data = postDigestQueue.get(element);
  4365. if (data) {
  4366. var existing = splitClasses(element.attr('class'));
  4367. var toAdd = '';
  4368. var toRemove = '';
  4369. forEach(data, function(status, className) {
  4370. var hasClass = !!existing[className];
  4371. if (status !== hasClass) {
  4372. if (status) {
  4373. toAdd += (toAdd.length ? ' ' : '') + className;
  4374. } else {
  4375. toRemove += (toRemove.length ? ' ' : '') + className;
  4376. }
  4377. }
  4378. });
  4379. forEach(element, function(elm) {
  4380. toAdd && jqLiteAddClass(elm, toAdd);
  4381. toRemove && jqLiteRemoveClass(elm, toRemove);
  4382. });
  4383. postDigestQueue.remove(element);
  4384. }
  4385. });
  4386. postDigestElements.length = 0;
  4387. });
  4388. }
  4389. }];
  4390. };
  4391. /**
  4392. * @ngdoc provider
  4393. * @name $animateProvider
  4394. *
  4395. * @description
  4396. * Default implementation of $animate that doesn't perform any animations, instead just
  4397. * synchronously performs DOM updates and resolves the returned runner promise.
  4398. *
  4399. * In order to enable animations the `ngAnimate` module has to be loaded.
  4400. *
  4401. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4402. */
  4403. var $AnimateProvider = ['$provide', function($provide) {
  4404. var provider = this;
  4405. this.$$registeredAnimations = Object.create(null);
  4406. /**
  4407. * @ngdoc method
  4408. * @name $animateProvider#register
  4409. *
  4410. * @description
  4411. * Registers a new injectable animation factory function. The factory function produces the
  4412. * animation object which contains callback functions for each event that is expected to be
  4413. * animated.
  4414. *
  4415. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4416. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4417. * on the type of animation additional arguments will be injected into the animation function. The
  4418. * list below explains the function signatures for the different animation methods:
  4419. *
  4420. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4421. * - addClass: function(element, addedClasses, doneFunction, options)
  4422. * - removeClass: function(element, removedClasses, doneFunction, options)
  4423. * - enter, leave, move: function(element, doneFunction, options)
  4424. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4425. *
  4426. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4427. *
  4428. * ```js
  4429. * return {
  4430. * //enter, leave, move signature
  4431. * eventFn : function(element, done, options) {
  4432. * //code to run the animation
  4433. * //once complete, then run done()
  4434. * return function endFunction(wasCancelled) {
  4435. * //code to cancel the animation
  4436. * }
  4437. * }
  4438. * }
  4439. * ```
  4440. *
  4441. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4442. * @param {Function} factory The factory function that will be executed to return the animation
  4443. * object.
  4444. */
  4445. this.register = function(name, factory) {
  4446. if (name && name.charAt(0) !== '.') {
  4447. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4448. }
  4449. var key = name + '-animation';
  4450. provider.$$registeredAnimations[name.substr(1)] = key;
  4451. $provide.factory(key, factory);
  4452. };
  4453. /**
  4454. * @ngdoc method
  4455. * @name $animateProvider#classNameFilter
  4456. *
  4457. * @description
  4458. * Sets and/or returns the CSS class regular expression that is checked when performing
  4459. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4460. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4461. * When setting the `classNameFilter` value, animations will only be performed on elements
  4462. * that successfully match the filter expression. This in turn can boost performance
  4463. * for low-powered devices as well as applications containing a lot of structural operations.
  4464. * @param {RegExp=} expression The className expression which will be checked against all animations
  4465. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4466. */
  4467. this.classNameFilter = function(expression) {
  4468. if (arguments.length === 1) {
  4469. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4470. if (this.$$classNameFilter) {
  4471. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4472. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4473. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4474. }
  4475. }
  4476. }
  4477. return this.$$classNameFilter;
  4478. };
  4479. this.$get = ['$$animateQueue', function($$animateQueue) {
  4480. function domInsert(element, parentElement, afterElement) {
  4481. // if for some reason the previous element was removed
  4482. // from the dom sometime before this code runs then let's
  4483. // just stick to using the parent element as the anchor
  4484. if (afterElement) {
  4485. var afterNode = extractElementNode(afterElement);
  4486. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4487. afterElement = null;
  4488. }
  4489. }
  4490. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4491. }
  4492. /**
  4493. * @ngdoc service
  4494. * @name $animate
  4495. * @description The $animate service exposes a series of DOM utility methods that provide support
  4496. * for animation hooks. The default behavior is the application of DOM operations, however,
  4497. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4498. * to ensure that animation runs with the triggered DOM operation.
  4499. *
  4500. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4501. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4502. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4503. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4504. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4505. *
  4506. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4507. *
  4508. * To learn more about enabling animation support, click here to visit the
  4509. * {@link ngAnimate ngAnimate module page}.
  4510. */
  4511. return {
  4512. // we don't call it directly since non-existant arguments may
  4513. // be interpreted as null within the sub enabled function
  4514. /**
  4515. *
  4516. * @ngdoc method
  4517. * @name $animate#on
  4518. * @kind function
  4519. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4520. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4521. * is fired with the following params:
  4522. *
  4523. * ```js
  4524. * $animate.on('enter', container,
  4525. * function callback(element, phase) {
  4526. * // cool we detected an enter animation within the container
  4527. * }
  4528. * );
  4529. * ```
  4530. *
  4531. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4532. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4533. * as well as among its children
  4534. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4535. *
  4536. * The arguments present in the callback function are:
  4537. * * `element` - The captured DOM element that the animation was fired on.
  4538. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4539. */
  4540. on: $$animateQueue.on,
  4541. /**
  4542. *
  4543. * @ngdoc method
  4544. * @name $animate#off
  4545. * @kind function
  4546. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4547. * can be used in three different ways depending on the arguments:
  4548. *
  4549. * ```js
  4550. * // remove all the animation event listeners listening for `enter`
  4551. * $animate.off('enter');
  4552. *
  4553. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4554. * $animate.off('enter', container);
  4555. *
  4556. * // remove the event listener function provided by `listenerFn` that is set
  4557. * // to listen for `enter` on the given `element` as well as its children
  4558. * $animate.off('enter', container, callback);
  4559. * ```
  4560. *
  4561. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4562. * @param {DOMElement=} container the container element the event listener was placed on
  4563. * @param {Function=} callback the callback function that was registered as the listener
  4564. */
  4565. off: $$animateQueue.off,
  4566. /**
  4567. * @ngdoc method
  4568. * @name $animate#pin
  4569. * @kind function
  4570. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4571. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4572. * element despite being outside the realm of the application or within another application. Say for example if the application
  4573. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4574. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4575. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4576. *
  4577. * Note that this feature is only active when the `ngAnimate` module is used.
  4578. *
  4579. * @param {DOMElement} element the external element that will be pinned
  4580. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4581. */
  4582. pin: $$animateQueue.pin,
  4583. /**
  4584. *
  4585. * @ngdoc method
  4586. * @name $animate#enabled
  4587. * @kind function
  4588. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4589. * function can be called in four ways:
  4590. *
  4591. * ```js
  4592. * // returns true or false
  4593. * $animate.enabled();
  4594. *
  4595. * // changes the enabled state for all animations
  4596. * $animate.enabled(false);
  4597. * $animate.enabled(true);
  4598. *
  4599. * // returns true or false if animations are enabled for an element
  4600. * $animate.enabled(element);
  4601. *
  4602. * // changes the enabled state for an element and its children
  4603. * $animate.enabled(element, true);
  4604. * $animate.enabled(element, false);
  4605. * ```
  4606. *
  4607. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4608. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4609. *
  4610. * @return {boolean} whether or not animations are enabled
  4611. */
  4612. enabled: $$animateQueue.enabled,
  4613. /**
  4614. * @ngdoc method
  4615. * @name $animate#cancel
  4616. * @kind function
  4617. * @description Cancels the provided animation.
  4618. *
  4619. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4620. */
  4621. cancel: function(runner) {
  4622. runner.end && runner.end();
  4623. },
  4624. /**
  4625. *
  4626. * @ngdoc method
  4627. * @name $animate#enter
  4628. * @kind function
  4629. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4630. * as the first child within the `parent` element and then triggers an animation.
  4631. * A promise is returned that will be resolved during the next digest once the animation
  4632. * has completed.
  4633. *
  4634. * @param {DOMElement} element the element which will be inserted into the DOM
  4635. * @param {DOMElement} parent the parent element which will append the element as
  4636. * a child (so long as the after element is not present)
  4637. * @param {DOMElement=} after the sibling element after which the element will be appended
  4638. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4639. *
  4640. * @return {Promise} the animation callback promise
  4641. */
  4642. enter: function(element, parent, after, options) {
  4643. parent = parent && jqLite(parent);
  4644. after = after && jqLite(after);
  4645. parent = parent || after.parent();
  4646. domInsert(element, parent, after);
  4647. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4648. },
  4649. /**
  4650. *
  4651. * @ngdoc method
  4652. * @name $animate#move
  4653. * @kind function
  4654. * @description Inserts (moves) the element into its new position in the DOM either after
  4655. * the `after` element (if provided) or as the first child within the `parent` element
  4656. * and then triggers an animation. A promise is returned that will be resolved
  4657. * during the next digest once the animation has completed.
  4658. *
  4659. * @param {DOMElement} element the element which will be moved into the new DOM position
  4660. * @param {DOMElement} parent the parent element which will append the element as
  4661. * a child (so long as the after element is not present)
  4662. * @param {DOMElement=} after the sibling element after which the element will be appended
  4663. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4664. *
  4665. * @return {Promise} the animation callback promise
  4666. */
  4667. move: function(element, parent, after, options) {
  4668. parent = parent && jqLite(parent);
  4669. after = after && jqLite(after);
  4670. parent = parent || after.parent();
  4671. domInsert(element, parent, after);
  4672. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4673. },
  4674. /**
  4675. * @ngdoc method
  4676. * @name $animate#leave
  4677. * @kind function
  4678. * @description Triggers an animation and then removes the element from the DOM.
  4679. * When the function is called a promise is returned that will be resolved during the next
  4680. * digest once the animation has completed.
  4681. *
  4682. * @param {DOMElement} element the element which will be removed from the DOM
  4683. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4684. *
  4685. * @return {Promise} the animation callback promise
  4686. */
  4687. leave: function(element, options) {
  4688. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4689. element.remove();
  4690. });
  4691. },
  4692. /**
  4693. * @ngdoc method
  4694. * @name $animate#addClass
  4695. * @kind function
  4696. *
  4697. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4698. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4699. * animation if element already contains the CSS class or if the class is removed at a later step.
  4700. * Note that class-based animations are treated differently compared to structural animations
  4701. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4702. * depending if CSS or JavaScript animations are used.
  4703. *
  4704. * @param {DOMElement} element the element which the CSS classes will be applied to
  4705. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4706. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4707. *
  4708. * @return {Promise} the animation callback promise
  4709. */
  4710. addClass: function(element, className, options) {
  4711. options = prepareAnimateOptions(options);
  4712. options.addClass = mergeClasses(options.addclass, className);
  4713. return $$animateQueue.push(element, 'addClass', options);
  4714. },
  4715. /**
  4716. * @ngdoc method
  4717. * @name $animate#removeClass
  4718. * @kind function
  4719. *
  4720. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4721. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4722. * animation if element does not contain the CSS class or if the class is added at a later step.
  4723. * Note that class-based animations are treated differently compared to structural animations
  4724. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4725. * depending if CSS or JavaScript animations are used.
  4726. *
  4727. * @param {DOMElement} element the element which the CSS classes will be applied to
  4728. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4729. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4730. *
  4731. * @return {Promise} the animation callback promise
  4732. */
  4733. removeClass: function(element, className, options) {
  4734. options = prepareAnimateOptions(options);
  4735. options.removeClass = mergeClasses(options.removeClass, className);
  4736. return $$animateQueue.push(element, 'removeClass', options);
  4737. },
  4738. /**
  4739. * @ngdoc method
  4740. * @name $animate#setClass
  4741. * @kind function
  4742. *
  4743. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4744. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4745. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4746. * passed. Note that class-based animations are treated differently compared to structural animations
  4747. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4748. * depending if CSS or JavaScript animations are used.
  4749. *
  4750. * @param {DOMElement} element the element which the CSS classes will be applied to
  4751. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4752. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4753. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4754. *
  4755. * @return {Promise} the animation callback promise
  4756. */
  4757. setClass: function(element, add, remove, options) {
  4758. options = prepareAnimateOptions(options);
  4759. options.addClass = mergeClasses(options.addClass, add);
  4760. options.removeClass = mergeClasses(options.removeClass, remove);
  4761. return $$animateQueue.push(element, 'setClass', options);
  4762. },
  4763. /**
  4764. * @ngdoc method
  4765. * @name $animate#animate
  4766. * @kind function
  4767. *
  4768. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4769. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4770. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4771. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4772. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4773. *
  4774. * @param {DOMElement} element the element which the CSS styles will be applied to
  4775. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4776. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4777. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4778. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4779. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4780. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4781. *
  4782. * @return {Promise} the animation callback promise
  4783. */
  4784. animate: function(element, from, to, className, options) {
  4785. options = prepareAnimateOptions(options);
  4786. options.from = options.from ? extend(options.from, from) : from;
  4787. options.to = options.to ? extend(options.to, to) : to;
  4788. className = className || 'ng-inline-animate';
  4789. options.tempClasses = mergeClasses(options.tempClasses, className);
  4790. return $$animateQueue.push(element, 'animate', options);
  4791. }
  4792. };
  4793. }];
  4794. }];
  4795. function $$AsyncCallbackProvider() {
  4796. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4797. return $$rAF.supported
  4798. ? function(fn) { return $$rAF(fn); }
  4799. : function(fn) {
  4800. return $timeout(fn, 0, false);
  4801. };
  4802. }];
  4803. }
  4804. /* global stripHash: true */
  4805. /**
  4806. * ! This is a private undocumented service !
  4807. *
  4808. * @name $browser
  4809. * @requires $log
  4810. * @description
  4811. * This object has two goals:
  4812. *
  4813. * - hide all the global state in the browser caused by the window object
  4814. * - abstract away all the browser specific features and inconsistencies
  4815. *
  4816. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4817. * service, which can be used for convenient testing of the application without the interaction with
  4818. * the real browser apis.
  4819. */
  4820. /**
  4821. * @param {object} window The global window object.
  4822. * @param {object} document jQuery wrapped document.
  4823. * @param {object} $log window.console or an object with the same interface.
  4824. * @param {object} $sniffer $sniffer service
  4825. */
  4826. function Browser(window, document, $log, $sniffer) {
  4827. var self = this,
  4828. rawDocument = document[0],
  4829. location = window.location,
  4830. history = window.history,
  4831. setTimeout = window.setTimeout,
  4832. clearTimeout = window.clearTimeout,
  4833. pendingDeferIds = {};
  4834. self.isMock = false;
  4835. var outstandingRequestCount = 0;
  4836. var outstandingRequestCallbacks = [];
  4837. // TODO(vojta): remove this temporary api
  4838. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4839. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4840. /**
  4841. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4842. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4843. */
  4844. function completeOutstandingRequest(fn) {
  4845. try {
  4846. fn.apply(null, sliceArgs(arguments, 1));
  4847. } finally {
  4848. outstandingRequestCount--;
  4849. if (outstandingRequestCount === 0) {
  4850. while (outstandingRequestCallbacks.length) {
  4851. try {
  4852. outstandingRequestCallbacks.pop()();
  4853. } catch (e) {
  4854. $log.error(e);
  4855. }
  4856. }
  4857. }
  4858. }
  4859. }
  4860. function getHash(url) {
  4861. var index = url.indexOf('#');
  4862. return index === -1 ? '' : url.substr(index + 1);
  4863. }
  4864. /**
  4865. * @private
  4866. * Note: this method is used only by scenario runner
  4867. * TODO(vojta): prefix this method with $$ ?
  4868. * @param {function()} callback Function that will be called when no outstanding request
  4869. */
  4870. self.notifyWhenNoOutstandingRequests = function(callback) {
  4871. if (outstandingRequestCount === 0) {
  4872. callback();
  4873. } else {
  4874. outstandingRequestCallbacks.push(callback);
  4875. }
  4876. };
  4877. //////////////////////////////////////////////////////////////
  4878. // URL API
  4879. //////////////////////////////////////////////////////////////
  4880. var cachedState, lastHistoryState,
  4881. lastBrowserUrl = location.href,
  4882. baseElement = document.find('base'),
  4883. reloadLocation = null;
  4884. cacheState();
  4885. lastHistoryState = cachedState;
  4886. /**
  4887. * @name $browser#url
  4888. *
  4889. * @description
  4890. * GETTER:
  4891. * Without any argument, this method just returns current value of location.href.
  4892. *
  4893. * SETTER:
  4894. * With at least one argument, this method sets url to new value.
  4895. * If html5 history api supported, pushState/replaceState is used, otherwise
  4896. * location.href/location.replace is used.
  4897. * Returns its own instance to allow chaining
  4898. *
  4899. * NOTE: this api is intended for use only by the $location service. Please use the
  4900. * {@link ng.$location $location service} to change url.
  4901. *
  4902. * @param {string} url New url (when used as setter)
  4903. * @param {boolean=} replace Should new url replace current history record?
  4904. * @param {object=} state object to use with pushState/replaceState
  4905. */
  4906. self.url = function(url, replace, state) {
  4907. // In modern browsers `history.state` is `null` by default; treating it separately
  4908. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4909. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4910. if (isUndefined(state)) {
  4911. state = null;
  4912. }
  4913. // Android Browser BFCache causes location, history reference to become stale.
  4914. if (location !== window.location) location = window.location;
  4915. if (history !== window.history) history = window.history;
  4916. // setter
  4917. if (url) {
  4918. var sameState = lastHistoryState === state;
  4919. // Don't change anything if previous and current URLs and states match. This also prevents
  4920. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4921. // See https://github.com/angular/angular.js/commit/ffb2701
  4922. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4923. return self;
  4924. }
  4925. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4926. lastBrowserUrl = url;
  4927. lastHistoryState = state;
  4928. // Don't use history API if only the hash changed
  4929. // due to a bug in IE10/IE11 which leads
  4930. // to not firing a `hashchange` nor `popstate` event
  4931. // in some cases (see #9143).
  4932. if ($sniffer.history && (!sameBase || !sameState)) {
  4933. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4934. cacheState();
  4935. // Do the assignment again so that those two variables are referentially identical.
  4936. lastHistoryState = cachedState;
  4937. } else {
  4938. if (!sameBase || reloadLocation) {
  4939. reloadLocation = url;
  4940. }
  4941. if (replace) {
  4942. location.replace(url);
  4943. } else if (!sameBase) {
  4944. location.href = url;
  4945. } else {
  4946. location.hash = getHash(url);
  4947. }
  4948. }
  4949. return self;
  4950. // getter
  4951. } else {
  4952. // - reloadLocation is needed as browsers don't allow to read out
  4953. // the new location.href if a reload happened.
  4954. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4955. return reloadLocation || location.href.replace(/%27/g,"'");
  4956. }
  4957. };
  4958. /**
  4959. * @name $browser#state
  4960. *
  4961. * @description
  4962. * This method is a getter.
  4963. *
  4964. * Return history.state or null if history.state is undefined.
  4965. *
  4966. * @returns {object} state
  4967. */
  4968. self.state = function() {
  4969. return cachedState;
  4970. };
  4971. var urlChangeListeners = [],
  4972. urlChangeInit = false;
  4973. function cacheStateAndFireUrlChange() {
  4974. cacheState();
  4975. fireUrlChange();
  4976. }
  4977. function getCurrentState() {
  4978. try {
  4979. return history.state;
  4980. } catch (e) {
  4981. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  4982. }
  4983. }
  4984. // This variable should be used *only* inside the cacheState function.
  4985. var lastCachedState = null;
  4986. function cacheState() {
  4987. // This should be the only place in $browser where `history.state` is read.
  4988. cachedState = getCurrentState();
  4989. cachedState = isUndefined(cachedState) ? null : cachedState;
  4990. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4991. if (equals(cachedState, lastCachedState)) {
  4992. cachedState = lastCachedState;
  4993. }
  4994. lastCachedState = cachedState;
  4995. }
  4996. function fireUrlChange() {
  4997. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4998. return;
  4999. }
  5000. lastBrowserUrl = self.url();
  5001. lastHistoryState = cachedState;
  5002. forEach(urlChangeListeners, function(listener) {
  5003. listener(self.url(), cachedState);
  5004. });
  5005. }
  5006. /**
  5007. * @name $browser#onUrlChange
  5008. *
  5009. * @description
  5010. * Register callback function that will be called, when url changes.
  5011. *
  5012. * It's only called when the url is changed from outside of angular:
  5013. * - user types different url into address bar
  5014. * - user clicks on history (forward/back) button
  5015. * - user clicks on a link
  5016. *
  5017. * It's not called when url is changed by $browser.url() method
  5018. *
  5019. * The listener gets called with new url as parameter.
  5020. *
  5021. * NOTE: this api is intended for use only by the $location service. Please use the
  5022. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5023. *
  5024. * @param {function(string)} listener Listener function to be called when url changes.
  5025. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5026. */
  5027. self.onUrlChange = function(callback) {
  5028. // TODO(vojta): refactor to use node's syntax for events
  5029. if (!urlChangeInit) {
  5030. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5031. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5032. // changed by push/replaceState
  5033. // html5 history api - popstate event
  5034. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5035. // hashchange event
  5036. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5037. urlChangeInit = true;
  5038. }
  5039. urlChangeListeners.push(callback);
  5040. return callback;
  5041. };
  5042. /**
  5043. * @private
  5044. * Remove popstate and hashchange handler from window.
  5045. *
  5046. * NOTE: this api is intended for use only by $rootScope.
  5047. */
  5048. self.$$applicationDestroyed = function() {
  5049. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5050. };
  5051. /**
  5052. * Checks whether the url has changed outside of Angular.
  5053. * Needs to be exported to be able to check for changes that have been done in sync,
  5054. * as hashchange/popstate events fire in async.
  5055. */
  5056. self.$$checkUrlChange = fireUrlChange;
  5057. //////////////////////////////////////////////////////////////
  5058. // Misc API
  5059. //////////////////////////////////////////////////////////////
  5060. /**
  5061. * @name $browser#baseHref
  5062. *
  5063. * @description
  5064. * Returns current <base href>
  5065. * (always relative - without domain)
  5066. *
  5067. * @returns {string} The current base href
  5068. */
  5069. self.baseHref = function() {
  5070. var href = baseElement.attr('href');
  5071. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5072. };
  5073. /**
  5074. * @name $browser#defer
  5075. * @param {function()} fn A function, who's execution should be deferred.
  5076. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5077. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5078. *
  5079. * @description
  5080. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5081. *
  5082. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5083. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5084. * via `$browser.defer.flush()`.
  5085. *
  5086. */
  5087. self.defer = function(fn, delay) {
  5088. var timeoutId;
  5089. outstandingRequestCount++;
  5090. timeoutId = setTimeout(function() {
  5091. delete pendingDeferIds[timeoutId];
  5092. completeOutstandingRequest(fn);
  5093. }, delay || 0);
  5094. pendingDeferIds[timeoutId] = true;
  5095. return timeoutId;
  5096. };
  5097. /**
  5098. * @name $browser#defer.cancel
  5099. *
  5100. * @description
  5101. * Cancels a deferred task identified with `deferId`.
  5102. *
  5103. * @param {*} deferId Token returned by the `$browser.defer` function.
  5104. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5105. * canceled.
  5106. */
  5107. self.defer.cancel = function(deferId) {
  5108. if (pendingDeferIds[deferId]) {
  5109. delete pendingDeferIds[deferId];
  5110. clearTimeout(deferId);
  5111. completeOutstandingRequest(noop);
  5112. return true;
  5113. }
  5114. return false;
  5115. };
  5116. }
  5117. function $BrowserProvider() {
  5118. this.$get = ['$window', '$log', '$sniffer', '$document',
  5119. function($window, $log, $sniffer, $document) {
  5120. return new Browser($window, $document, $log, $sniffer);
  5121. }];
  5122. }
  5123. /**
  5124. * @ngdoc service
  5125. * @name $cacheFactory
  5126. *
  5127. * @description
  5128. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5129. * them.
  5130. *
  5131. * ```js
  5132. *
  5133. * var cache = $cacheFactory('cacheId');
  5134. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5135. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5136. *
  5137. * cache.put("key", "value");
  5138. * cache.put("another key", "another value");
  5139. *
  5140. * // We've specified no options on creation
  5141. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5142. *
  5143. * ```
  5144. *
  5145. *
  5146. * @param {string} cacheId Name or id of the newly created cache.
  5147. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5148. *
  5149. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5150. *
  5151. * @returns {object} Newly created cache object with the following set of methods:
  5152. *
  5153. * - `{object}` `info()` — Returns id, size, and options of cache.
  5154. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5155. * it.
  5156. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5157. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5158. * - `{void}` `removeAll()` — Removes all cached values.
  5159. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5160. *
  5161. * @example
  5162. <example module="cacheExampleApp">
  5163. <file name="index.html">
  5164. <div ng-controller="CacheController">
  5165. <input ng-model="newCacheKey" placeholder="Key">
  5166. <input ng-model="newCacheValue" placeholder="Value">
  5167. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5168. <p ng-if="keys.length">Cached Values</p>
  5169. <div ng-repeat="key in keys">
  5170. <span ng-bind="key"></span>
  5171. <span>: </span>
  5172. <b ng-bind="cache.get(key)"></b>
  5173. </div>
  5174. <p>Cache Info</p>
  5175. <div ng-repeat="(key, value) in cache.info()">
  5176. <span ng-bind="key"></span>
  5177. <span>: </span>
  5178. <b ng-bind="value"></b>
  5179. </div>
  5180. </div>
  5181. </file>
  5182. <file name="script.js">
  5183. angular.module('cacheExampleApp', []).
  5184. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5185. $scope.keys = [];
  5186. $scope.cache = $cacheFactory('cacheId');
  5187. $scope.put = function(key, value) {
  5188. if ($scope.cache.get(key) === undefined) {
  5189. $scope.keys.push(key);
  5190. }
  5191. $scope.cache.put(key, value === undefined ? null : value);
  5192. };
  5193. }]);
  5194. </file>
  5195. <file name="style.css">
  5196. p {
  5197. margin: 10px 0 3px;
  5198. }
  5199. </file>
  5200. </example>
  5201. */
  5202. function $CacheFactoryProvider() {
  5203. this.$get = function() {
  5204. var caches = {};
  5205. function cacheFactory(cacheId, options) {
  5206. if (cacheId in caches) {
  5207. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5208. }
  5209. var size = 0,
  5210. stats = extend({}, options, {id: cacheId}),
  5211. data = {},
  5212. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5213. lruHash = {},
  5214. freshEnd = null,
  5215. staleEnd = null;
  5216. /**
  5217. * @ngdoc type
  5218. * @name $cacheFactory.Cache
  5219. *
  5220. * @description
  5221. * A cache object used to store and retrieve data, primarily used by
  5222. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5223. * templates and other data.
  5224. *
  5225. * ```js
  5226. * angular.module('superCache')
  5227. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5228. * return $cacheFactory('super-cache');
  5229. * }]);
  5230. * ```
  5231. *
  5232. * Example test:
  5233. *
  5234. * ```js
  5235. * it('should behave like a cache', inject(function(superCache) {
  5236. * superCache.put('key', 'value');
  5237. * superCache.put('another key', 'another value');
  5238. *
  5239. * expect(superCache.info()).toEqual({
  5240. * id: 'super-cache',
  5241. * size: 2
  5242. * });
  5243. *
  5244. * superCache.remove('another key');
  5245. * expect(superCache.get('another key')).toBeUndefined();
  5246. *
  5247. * superCache.removeAll();
  5248. * expect(superCache.info()).toEqual({
  5249. * id: 'super-cache',
  5250. * size: 0
  5251. * });
  5252. * }));
  5253. * ```
  5254. */
  5255. return caches[cacheId] = {
  5256. /**
  5257. * @ngdoc method
  5258. * @name $cacheFactory.Cache#put
  5259. * @kind function
  5260. *
  5261. * @description
  5262. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5263. * retrieved later, and incrementing the size of the cache if the key was not already
  5264. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5265. * entries from the set.
  5266. *
  5267. * It will not insert undefined values into the cache.
  5268. *
  5269. * @param {string} key the key under which the cached data is stored.
  5270. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5271. * will not be stored.
  5272. * @returns {*} the value stored.
  5273. */
  5274. put: function(key, value) {
  5275. if (isUndefined(value)) return;
  5276. if (capacity < Number.MAX_VALUE) {
  5277. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5278. refresh(lruEntry);
  5279. }
  5280. if (!(key in data)) size++;
  5281. data[key] = value;
  5282. if (size > capacity) {
  5283. this.remove(staleEnd.key);
  5284. }
  5285. return value;
  5286. },
  5287. /**
  5288. * @ngdoc method
  5289. * @name $cacheFactory.Cache#get
  5290. * @kind function
  5291. *
  5292. * @description
  5293. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5294. *
  5295. * @param {string} key the key of the data to be retrieved
  5296. * @returns {*} the value stored.
  5297. */
  5298. get: function(key) {
  5299. if (capacity < Number.MAX_VALUE) {
  5300. var lruEntry = lruHash[key];
  5301. if (!lruEntry) return;
  5302. refresh(lruEntry);
  5303. }
  5304. return data[key];
  5305. },
  5306. /**
  5307. * @ngdoc method
  5308. * @name $cacheFactory.Cache#remove
  5309. * @kind function
  5310. *
  5311. * @description
  5312. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5313. *
  5314. * @param {string} key the key of the entry to be removed
  5315. */
  5316. remove: function(key) {
  5317. if (capacity < Number.MAX_VALUE) {
  5318. var lruEntry = lruHash[key];
  5319. if (!lruEntry) return;
  5320. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5321. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5322. link(lruEntry.n,lruEntry.p);
  5323. delete lruHash[key];
  5324. }
  5325. delete data[key];
  5326. size--;
  5327. },
  5328. /**
  5329. * @ngdoc method
  5330. * @name $cacheFactory.Cache#removeAll
  5331. * @kind function
  5332. *
  5333. * @description
  5334. * Clears the cache object of any entries.
  5335. */
  5336. removeAll: function() {
  5337. data = {};
  5338. size = 0;
  5339. lruHash = {};
  5340. freshEnd = staleEnd = null;
  5341. },
  5342. /**
  5343. * @ngdoc method
  5344. * @name $cacheFactory.Cache#destroy
  5345. * @kind function
  5346. *
  5347. * @description
  5348. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5349. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5350. */
  5351. destroy: function() {
  5352. data = null;
  5353. stats = null;
  5354. lruHash = null;
  5355. delete caches[cacheId];
  5356. },
  5357. /**
  5358. * @ngdoc method
  5359. * @name $cacheFactory.Cache#info
  5360. * @kind function
  5361. *
  5362. * @description
  5363. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5364. *
  5365. * @returns {object} an object with the following properties:
  5366. * <ul>
  5367. * <li>**id**: the id of the cache instance</li>
  5368. * <li>**size**: the number of entries kept in the cache instance</li>
  5369. * <li>**...**: any additional properties from the options object when creating the
  5370. * cache.</li>
  5371. * </ul>
  5372. */
  5373. info: function() {
  5374. return extend({}, stats, {size: size});
  5375. }
  5376. };
  5377. /**
  5378. * makes the `entry` the freshEnd of the LRU linked list
  5379. */
  5380. function refresh(entry) {
  5381. if (entry != freshEnd) {
  5382. if (!staleEnd) {
  5383. staleEnd = entry;
  5384. } else if (staleEnd == entry) {
  5385. staleEnd = entry.n;
  5386. }
  5387. link(entry.n, entry.p);
  5388. link(entry, freshEnd);
  5389. freshEnd = entry;
  5390. freshEnd.n = null;
  5391. }
  5392. }
  5393. /**
  5394. * bidirectionally links two entries of the LRU linked list
  5395. */
  5396. function link(nextEntry, prevEntry) {
  5397. if (nextEntry != prevEntry) {
  5398. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5399. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5400. }
  5401. }
  5402. }
  5403. /**
  5404. * @ngdoc method
  5405. * @name $cacheFactory#info
  5406. *
  5407. * @description
  5408. * Get information about all the caches that have been created
  5409. *
  5410. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5411. */
  5412. cacheFactory.info = function() {
  5413. var info = {};
  5414. forEach(caches, function(cache, cacheId) {
  5415. info[cacheId] = cache.info();
  5416. });
  5417. return info;
  5418. };
  5419. /**
  5420. * @ngdoc method
  5421. * @name $cacheFactory#get
  5422. *
  5423. * @description
  5424. * Get access to a cache object by the `cacheId` used when it was created.
  5425. *
  5426. * @param {string} cacheId Name or id of a cache to access.
  5427. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5428. */
  5429. cacheFactory.get = function(cacheId) {
  5430. return caches[cacheId];
  5431. };
  5432. return cacheFactory;
  5433. };
  5434. }
  5435. /**
  5436. * @ngdoc service
  5437. * @name $templateCache
  5438. *
  5439. * @description
  5440. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5441. * can load templates directly into the cache in a `script` tag, or by consuming the
  5442. * `$templateCache` service directly.
  5443. *
  5444. * Adding via the `script` tag:
  5445. *
  5446. * ```html
  5447. * <script type="text/ng-template" id="templateId.html">
  5448. * <p>This is the content of the template</p>
  5449. * </script>
  5450. * ```
  5451. *
  5452. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5453. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5454. * element with ng-app attribute), otherwise the template will be ignored.
  5455. *
  5456. * Adding via the `$templateCache` service:
  5457. *
  5458. * ```js
  5459. * var myApp = angular.module('myApp', []);
  5460. * myApp.run(function($templateCache) {
  5461. * $templateCache.put('templateId.html', 'This is the content of the template');
  5462. * });
  5463. * ```
  5464. *
  5465. * To retrieve the template later, simply use it in your HTML:
  5466. * ```html
  5467. * <div ng-include=" 'templateId.html' "></div>
  5468. * ```
  5469. *
  5470. * or get it via Javascript:
  5471. * ```js
  5472. * $templateCache.get('templateId.html')
  5473. * ```
  5474. *
  5475. * See {@link ng.$cacheFactory $cacheFactory}.
  5476. *
  5477. */
  5478. function $TemplateCacheProvider() {
  5479. this.$get = ['$cacheFactory', function($cacheFactory) {
  5480. return $cacheFactory('templates');
  5481. }];
  5482. }
  5483. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5484. * Any commits to this file should be reviewed with security in mind. *
  5485. * Changes to this file can potentially create security vulnerabilities. *
  5486. * An approval from 2 Core members with history of modifying *
  5487. * this file is required. *
  5488. * *
  5489. * Does the change somehow allow for arbitrary javascript to be executed? *
  5490. * Or allows for someone to change the prototype of built-in objects? *
  5491. * Or gives undesired access to variables likes document or window? *
  5492. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5493. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5494. *
  5495. * DOM-related variables:
  5496. *
  5497. * - "node" - DOM Node
  5498. * - "element" - DOM Element or Node
  5499. * - "$node" or "$element" - jqLite-wrapped node or element
  5500. *
  5501. *
  5502. * Compiler related stuff:
  5503. *
  5504. * - "linkFn" - linking fn of a single directive
  5505. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5506. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5507. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5508. */
  5509. /**
  5510. * @ngdoc service
  5511. * @name $compile
  5512. * @kind function
  5513. *
  5514. * @description
  5515. * Compiles an HTML string or DOM into a template and produces a template function, which
  5516. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5517. *
  5518. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5519. * {@link ng.$compileProvider#directive directives}.
  5520. *
  5521. * <div class="alert alert-warning">
  5522. * **Note:** This document is an in-depth reference of all directive options.
  5523. * For a gentle introduction to directives with examples of common use cases,
  5524. * see the {@link guide/directive directive guide}.
  5525. * </div>
  5526. *
  5527. * ## Comprehensive Directive API
  5528. *
  5529. * There are many different options for a directive.
  5530. *
  5531. * The difference resides in the return value of the factory function.
  5532. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5533. * or just the `postLink` function (all other properties will have the default values).
  5534. *
  5535. * <div class="alert alert-success">
  5536. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5537. * </div>
  5538. *
  5539. * Here's an example directive declared with a Directive Definition Object:
  5540. *
  5541. * ```js
  5542. * var myModule = angular.module(...);
  5543. *
  5544. * myModule.directive('directiveName', function factory(injectables) {
  5545. * var directiveDefinitionObject = {
  5546. * priority: 0,
  5547. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5548. * // or
  5549. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5550. * transclude: false,
  5551. * restrict: 'A',
  5552. * templateNamespace: 'html',
  5553. * scope: false,
  5554. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5555. * controllerAs: 'stringIdentifier',
  5556. * bindToController: false,
  5557. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5558. * compile: function compile(tElement, tAttrs, transclude) {
  5559. * return {
  5560. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5561. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5562. * }
  5563. * // or
  5564. * // return function postLink( ... ) { ... }
  5565. * },
  5566. * // or
  5567. * // link: {
  5568. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5569. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5570. * // }
  5571. * // or
  5572. * // link: function postLink( ... ) { ... }
  5573. * };
  5574. * return directiveDefinitionObject;
  5575. * });
  5576. * ```
  5577. *
  5578. * <div class="alert alert-warning">
  5579. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5580. * </div>
  5581. *
  5582. * Therefore the above can be simplified as:
  5583. *
  5584. * ```js
  5585. * var myModule = angular.module(...);
  5586. *
  5587. * myModule.directive('directiveName', function factory(injectables) {
  5588. * var directiveDefinitionObject = {
  5589. * link: function postLink(scope, iElement, iAttrs) { ... }
  5590. * };
  5591. * return directiveDefinitionObject;
  5592. * // or
  5593. * // return function postLink(scope, iElement, iAttrs) { ... }
  5594. * });
  5595. * ```
  5596. *
  5597. *
  5598. *
  5599. * ### Directive Definition Object
  5600. *
  5601. * The directive definition object provides instructions to the {@link ng.$compile
  5602. * compiler}. The attributes are:
  5603. *
  5604. * #### `multiElement`
  5605. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5606. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5607. * together as the directive elements. It is recommended that this feature be used on directives
  5608. * which are not strictly behavioural (such as {@link ngClick}), and which
  5609. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5610. *
  5611. * #### `priority`
  5612. * When there are multiple directives defined on a single DOM element, sometimes it
  5613. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5614. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5615. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5616. * are also run in priority order, but post-link functions are run in reverse order. The order
  5617. * of directives with the same priority is undefined. The default priority is `0`.
  5618. *
  5619. * #### `terminal`
  5620. * If set to true then the current `priority` will be the last set of directives
  5621. * which will execute (any directives at the current priority will still execute
  5622. * as the order of execution on same `priority` is undefined). Note that expressions
  5623. * and other directives used in the directive's template will also be excluded from execution.
  5624. *
  5625. * #### `scope`
  5626. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5627. * same element request a new scope, only one new scope is created. The new scope rule does not
  5628. * apply for the root of the template since the root of the template always gets a new scope.
  5629. *
  5630. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5631. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5632. * when creating reusable components, which should not accidentally read or modify data in the
  5633. * parent scope.
  5634. *
  5635. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5636. * derived from the parent scope. These local properties are useful for aliasing values for
  5637. * templates. Locals definition is a hash of local scope property to its source:
  5638. *
  5639. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5640. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5641. * attribute name is assumed to be the same as the local name.
  5642. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5643. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5644. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5645. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5646. * component scope).
  5647. *
  5648. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5649. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5650. * name is specified then the attribute name is assumed to be the same as the local name.
  5651. * Given `<widget my-attr="parentModel">` and widget definition of
  5652. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5653. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5654. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5655. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5656. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5657. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5658. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5659. *
  5660. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5661. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5662. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5663. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5664. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5665. * pass data from the isolated scope via an expression to the parent scope, this can be
  5666. * done by passing a map of local variable names and values into the expression wrapper fn.
  5667. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5668. * by calling the `localFn` as `localFn({amount: 22})`.
  5669. *
  5670. *
  5671. * #### `bindToController`
  5672. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5673. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5674. * is instantiated, the initial values of the isolate scope bindings are already available.
  5675. *
  5676. * #### `controller`
  5677. * Controller constructor function. The controller is instantiated before the
  5678. * pre-linking phase and it is shared with other directives (see
  5679. * `require` attribute). This allows the directives to communicate with each other and augment
  5680. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5681. *
  5682. * * `$scope` - Current scope associated with the element
  5683. * * `$element` - Current element
  5684. * * `$attrs` - Current attributes object for the element
  5685. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5686. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5687. * * `scope`: optional argument to override the scope.
  5688. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5689. * * `futureParentElement`:
  5690. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5691. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5692. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5693. * and when the `cloneLinkinFn` is passed,
  5694. * as those elements need to created and cloned in a special way when they are defined outside their
  5695. * usual containers (e.g. like `<svg>`).
  5696. * * See also the `directive.templateNamespace` property.
  5697. *
  5698. *
  5699. * #### `require`
  5700. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5701. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5702. * injected argument will be an array in corresponding order. If no such directive can be
  5703. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5704. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5705. *
  5706. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5707. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5708. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5709. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5710. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5711. * `null` to the `link` fn if not found.
  5712. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5713. * `null` to the `link` fn if not found.
  5714. *
  5715. *
  5716. * #### `controllerAs`
  5717. * Identifier name for a reference to the controller in the directive's scope.
  5718. * This allows the controller to be referenced from the directive template. The directive
  5719. * needs to define a scope for this configuration to be used. Useful in the case when
  5720. * directive is used as component.
  5721. *
  5722. *
  5723. * #### `restrict`
  5724. * String of subset of `EACM` which restricts the directive to a specific directive
  5725. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5726. *
  5727. * * `E` - Element name (default): `<my-directive></my-directive>`
  5728. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5729. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5730. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5731. *
  5732. *
  5733. * #### `templateNamespace`
  5734. * String representing the document type used by the markup in the template.
  5735. * AngularJS needs this information as those elements need to be created and cloned
  5736. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5737. *
  5738. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5739. * top-level elements such as `<svg>` or `<math>`.
  5740. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5741. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5742. *
  5743. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5744. *
  5745. * #### `template`
  5746. * HTML markup that may:
  5747. * * Replace the contents of the directive's element (default).
  5748. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5749. * * Wrap the contents of the directive's element (if `transclude` is true).
  5750. *
  5751. * Value may be:
  5752. *
  5753. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5754. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5755. * function api below) and returns a string value.
  5756. *
  5757. *
  5758. * #### `templateUrl`
  5759. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5760. *
  5761. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5762. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5763. * sibling and parent elements as though this element had not contained any directives.
  5764. *
  5765. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5766. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5767. * case when only one deeply nested directive has `templateUrl`.
  5768. *
  5769. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5770. *
  5771. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5772. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5773. * a string value representing the url. In either case, the template URL is passed through {@link
  5774. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5775. *
  5776. *
  5777. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5778. * specify what the template should replace. Defaults to `false`.
  5779. *
  5780. * * `true` - the template will replace the directive's element.
  5781. * * `false` - the template will replace the contents of the directive's element.
  5782. *
  5783. * The replacement process migrates all of the attributes / classes from the old element to the new
  5784. * one. See the {@link guide/directive#template-expanding-directive
  5785. * Directives Guide} for an example.
  5786. *
  5787. * There are very few scenarios where element replacement is required for the application function,
  5788. * the main one being reusable custom components that are used within SVG contexts
  5789. * (because SVG doesn't work with custom elements in the DOM tree).
  5790. *
  5791. * #### `transclude`
  5792. * Extract the contents of the element where the directive appears and make it available to the directive.
  5793. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5794. * {@link $compile#transclusion Transclusion} section below.
  5795. *
  5796. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5797. * directive's element or the entire element:
  5798. *
  5799. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5800. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5801. * element that defined at a lower priority than this directive. When used, the `template`
  5802. * property is ignored.
  5803. *
  5804. *
  5805. * #### `compile`
  5806. *
  5807. * ```js
  5808. * function compile(tElement, tAttrs, transclude) { ... }
  5809. * ```
  5810. *
  5811. * The compile function deals with transforming the template DOM. Since most directives do not do
  5812. * template transformation, it is not used often. The compile function takes the following arguments:
  5813. *
  5814. * * `tElement` - template element - The element where the directive has been declared. It is
  5815. * safe to do template transformation on the element and child elements only.
  5816. *
  5817. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5818. * between all directive compile functions.
  5819. *
  5820. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5821. *
  5822. * <div class="alert alert-warning">
  5823. * **Note:** The template instance and the link instance may be different objects if the template has
  5824. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5825. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5826. * should be done in a linking function rather than in a compile function.
  5827. * </div>
  5828. * <div class="alert alert-warning">
  5829. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5830. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5831. * stack overflow errors.
  5832. *
  5833. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5834. * a directive's template instead of relying on automatic template compilation via `template` or
  5835. * `templateUrl` declaration or manual compilation inside the compile function.
  5836. * </div>
  5837. *
  5838. * <div class="alert alert-danger">
  5839. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5840. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5841. * to the link function instead.
  5842. * </div>
  5843. * A compile function can have a return value which can be either a function or an object.
  5844. *
  5845. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5846. * `link` property of the config object when the compile function is empty.
  5847. *
  5848. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5849. * control when a linking function should be called during the linking phase. See info about
  5850. * pre-linking and post-linking functions below.
  5851. *
  5852. *
  5853. * #### `link`
  5854. * This property is used only if the `compile` property is not defined.
  5855. *
  5856. * ```js
  5857. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5858. * ```
  5859. *
  5860. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5861. * executed after the template has been cloned. This is where most of the directive logic will be
  5862. * put.
  5863. *
  5864. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5865. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5866. *
  5867. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5868. * manipulate the children of the element only in `postLink` function since the children have
  5869. * already been linked.
  5870. *
  5871. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5872. * between all directive linking functions.
  5873. *
  5874. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5875. * among all directives, which allows the directives to use the controllers as a communication
  5876. * channel. The exact value depends on the directive's `require` property:
  5877. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  5878. * * `string`: the controller instance
  5879. * * `array`: array of controller instances
  5880. *
  5881. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5882. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5883. *
  5884. * Note that you can also require the directive's own controller - it will be made available like
  5885. * like any other controller.
  5886. *
  5887. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5888. * This is the same as the `$transclude`
  5889. * parameter of directive controllers, see there for details.
  5890. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5891. *
  5892. * #### Pre-linking function
  5893. *
  5894. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5895. * compiler linking function will fail to locate the correct elements for linking.
  5896. *
  5897. * #### Post-linking function
  5898. *
  5899. * Executed after the child elements are linked.
  5900. *
  5901. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5902. * and linked since they are waiting for their template to load asynchronously and their own
  5903. * compilation and linking has been suspended until that occurs.
  5904. *
  5905. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5906. * for their async templates to be resolved.
  5907. *
  5908. *
  5909. * ### Transclusion
  5910. *
  5911. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5912. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5913. * scope from where they were taken.
  5914. *
  5915. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5916. * original contents of a directive's element into a specified place in the template of the directive.
  5917. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5918. * content has access to the properties on the scope from which it was taken, even if the directive
  5919. * has isolated scope.
  5920. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5921. *
  5922. * This makes it possible for the widget to have private state for its template, while the transcluded
  5923. * content has access to its originating scope.
  5924. *
  5925. * <div class="alert alert-warning">
  5926. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5927. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5928. * Testing Transclusion Directives}.
  5929. * </div>
  5930. *
  5931. * #### Transclusion Functions
  5932. *
  5933. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5934. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5935. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5936. *
  5937. * <div class="alert alert-info">
  5938. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5939. * ngTransclude will deal with it for us.
  5940. * </div>
  5941. *
  5942. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5943. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5944. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5945. *
  5946. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5947. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5948. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5949. *
  5950. * <div class="alert alert-info">
  5951. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5952. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5953. * </div>
  5954. *
  5955. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5956. * attach function**:
  5957. *
  5958. * ```js
  5959. * var transcludedContent, transclusionScope;
  5960. *
  5961. * $transclude(function(clone, scope) {
  5962. * element.append(clone);
  5963. * transcludedContent = clone;
  5964. * transclusionScope = scope;
  5965. * });
  5966. * ```
  5967. *
  5968. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5969. * associated transclusion scope:
  5970. *
  5971. * ```js
  5972. * transcludedContent.remove();
  5973. * transclusionScope.$destroy();
  5974. * ```
  5975. *
  5976. * <div class="alert alert-info">
  5977. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5978. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  5979. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5980. * </div>
  5981. *
  5982. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5983. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5984. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5985. *
  5986. *
  5987. * #### Transclusion Scopes
  5988. *
  5989. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5990. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5991. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5992. * was taken.
  5993. *
  5994. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5995. * like this:
  5996. *
  5997. * ```html
  5998. * <div ng-app>
  5999. * <div isolate>
  6000. * <div transclusion>
  6001. * </div>
  6002. * </div>
  6003. * </div>
  6004. * ```
  6005. *
  6006. * The `$parent` scope hierarchy will look like this:
  6007. *
  6008. * ```
  6009. * - $rootScope
  6010. * - isolate
  6011. * - transclusion
  6012. * ```
  6013. *
  6014. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6015. *
  6016. * ```
  6017. * - $rootScope
  6018. * - transclusion
  6019. * - isolate
  6020. * ```
  6021. *
  6022. *
  6023. * ### Attributes
  6024. *
  6025. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6026. * `link()` or `compile()` functions. It has a variety of uses.
  6027. *
  6028. * accessing *Normalized attribute names:*
  6029. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6030. * the attributes object allows for normalized access to
  6031. * the attributes.
  6032. *
  6033. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6034. * object which allows the directives to use the attributes object as inter directive
  6035. * communication.
  6036. *
  6037. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6038. * allowing other directives to read the interpolated value.
  6039. *
  6040. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6041. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6042. * the only way to easily get the actual value because during the linking phase the interpolation
  6043. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6044. *
  6045. * ```js
  6046. * function linkingFn(scope, elm, attrs, ctrl) {
  6047. * // get the attribute value
  6048. * console.log(attrs.ngModel);
  6049. *
  6050. * // change the attribute
  6051. * attrs.$set('ngModel', 'new value');
  6052. *
  6053. * // observe changes to interpolated attribute
  6054. * attrs.$observe('ngModel', function(value) {
  6055. * console.log('ngModel has changed value to ' + value);
  6056. * });
  6057. * }
  6058. * ```
  6059. *
  6060. * ## Example
  6061. *
  6062. * <div class="alert alert-warning">
  6063. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6064. * to illustrate how `$compile` works.
  6065. * </div>
  6066. *
  6067. <example module="compileExample">
  6068. <file name="index.html">
  6069. <script>
  6070. angular.module('compileExample', [], function($compileProvider) {
  6071. // configure new 'compile' directive by passing a directive
  6072. // factory function. The factory function injects the '$compile'
  6073. $compileProvider.directive('compile', function($compile) {
  6074. // directive factory creates a link function
  6075. return function(scope, element, attrs) {
  6076. scope.$watch(
  6077. function(scope) {
  6078. // watch the 'compile' expression for changes
  6079. return scope.$eval(attrs.compile);
  6080. },
  6081. function(value) {
  6082. // when the 'compile' expression changes
  6083. // assign it into the current DOM
  6084. element.html(value);
  6085. // compile the new DOM and link it to the current
  6086. // scope.
  6087. // NOTE: we only compile .childNodes so that
  6088. // we don't get into infinite loop compiling ourselves
  6089. $compile(element.contents())(scope);
  6090. }
  6091. );
  6092. };
  6093. });
  6094. })
  6095. .controller('GreeterController', ['$scope', function($scope) {
  6096. $scope.name = 'Angular';
  6097. $scope.html = 'Hello {{name}}';
  6098. }]);
  6099. </script>
  6100. <div ng-controller="GreeterController">
  6101. <input ng-model="name"> <br/>
  6102. <textarea ng-model="html"></textarea> <br/>
  6103. <div compile="html"></div>
  6104. </div>
  6105. </file>
  6106. <file name="protractor.js" type="protractor">
  6107. it('should auto compile', function() {
  6108. var textarea = $('textarea');
  6109. var output = $('div[compile]');
  6110. // The initial state reads 'Hello Angular'.
  6111. expect(output.getText()).toBe('Hello Angular');
  6112. textarea.clear();
  6113. textarea.sendKeys('{{name}}!');
  6114. expect(output.getText()).toBe('Angular!');
  6115. });
  6116. </file>
  6117. </example>
  6118. *
  6119. *
  6120. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6121. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6122. *
  6123. * <div class="alert alert-danger">
  6124. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6125. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6126. * `parentBoundTranscludeFn` to the link function instead.
  6127. * </div>
  6128. *
  6129. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6130. * root element(s), not their children)
  6131. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6132. * (a DOM element/tree) to a scope. Where:
  6133. *
  6134. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6135. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6136. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6137. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6138. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6139. *
  6140. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6141. * * `scope` - is the current scope with which the linking function is working with.
  6142. *
  6143. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6144. * keys may be used to control linking behavior:
  6145. *
  6146. * * `parentBoundTranscludeFn` - the transclude function made available to
  6147. * directives; if given, it will be passed through to the link functions of
  6148. * directives found in `element` during compilation.
  6149. * * `transcludeControllers` - an object hash with keys that map controller names
  6150. * to controller instances; if given, it will make the controllers
  6151. * available to directives.
  6152. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6153. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6154. * elements (e.g. SVG elements). See also the directive.controller property.
  6155. *
  6156. * Calling the linking function returns the element of the template. It is either the original
  6157. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6158. *
  6159. * After linking the view is not updated until after a call to $digest which typically is done by
  6160. * Angular automatically.
  6161. *
  6162. * If you need access to the bound view, there are two ways to do it:
  6163. *
  6164. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6165. * before you send them to the compiler and keep this reference around.
  6166. * ```js
  6167. * var element = $compile('<p>{{total}}</p>')(scope);
  6168. * ```
  6169. *
  6170. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6171. * example would not point to the clone, but rather to the original template that was cloned. In
  6172. * this case, you can access the clone via the cloneAttachFn:
  6173. * ```js
  6174. * var templateElement = angular.element('<p>{{total}}</p>'),
  6175. * scope = ....;
  6176. *
  6177. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6178. * //attach the clone to DOM document at the right place
  6179. * });
  6180. *
  6181. * //now we have reference to the cloned DOM via `clonedElement`
  6182. * ```
  6183. *
  6184. *
  6185. * For information on how the compiler works, see the
  6186. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6187. */
  6188. var $compileMinErr = minErr('$compile');
  6189. /**
  6190. * @ngdoc provider
  6191. * @name $compileProvider
  6192. *
  6193. * @description
  6194. */
  6195. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6196. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6197. var hasDirectives = {},
  6198. Suffix = 'Directive',
  6199. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6200. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6201. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6202. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6203. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6204. // The assumption is that future DOM event attribute names will begin with
  6205. // 'on' and be composed of only English letters.
  6206. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6207. function parseIsolateBindings(scope, directiveName, isController) {
  6208. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6209. var bindings = {};
  6210. forEach(scope, function(definition, scopeName) {
  6211. var match = definition.match(LOCAL_REGEXP);
  6212. if (!match) {
  6213. throw $compileMinErr('iscp',
  6214. "Invalid {3} for directive '{0}'." +
  6215. " Definition: {... {1}: '{2}' ...}",
  6216. directiveName, scopeName, definition,
  6217. (isController ? "controller bindings definition" :
  6218. "isolate scope definition"));
  6219. }
  6220. bindings[scopeName] = {
  6221. mode: match[1][0],
  6222. collection: match[2] === '*',
  6223. optional: match[3] === '?',
  6224. attrName: match[4] || scopeName
  6225. };
  6226. });
  6227. return bindings;
  6228. }
  6229. function parseDirectiveBindings(directive, directiveName) {
  6230. var bindings = {
  6231. isolateScope: null,
  6232. bindToController: null
  6233. };
  6234. if (isObject(directive.scope)) {
  6235. if (directive.bindToController === true) {
  6236. bindings.bindToController = parseIsolateBindings(directive.scope,
  6237. directiveName, true);
  6238. bindings.isolateScope = {};
  6239. } else {
  6240. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6241. directiveName, false);
  6242. }
  6243. }
  6244. if (isObject(directive.bindToController)) {
  6245. bindings.bindToController =
  6246. parseIsolateBindings(directive.bindToController, directiveName, true);
  6247. }
  6248. if (isObject(bindings.bindToController)) {
  6249. var controller = directive.controller;
  6250. var controllerAs = directive.controllerAs;
  6251. if (!controller) {
  6252. // There is no controller, there may or may not be a controllerAs property
  6253. throw $compileMinErr('noctrl',
  6254. "Cannot bind to controller without directive '{0}'s controller.",
  6255. directiveName);
  6256. } else if (!identifierForController(controller, controllerAs)) {
  6257. // There is a controller, but no identifier or controllerAs property
  6258. throw $compileMinErr('noident',
  6259. "Cannot bind to controller without identifier for directive '{0}'.",
  6260. directiveName);
  6261. }
  6262. }
  6263. return bindings;
  6264. }
  6265. function assertValidDirectiveName(name) {
  6266. var letter = name.charAt(0);
  6267. if (!letter || letter !== lowercase(letter)) {
  6268. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6269. }
  6270. if (name !== name.trim()) {
  6271. throw $compileMinErr('baddir',
  6272. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6273. name);
  6274. }
  6275. }
  6276. /**
  6277. * @ngdoc method
  6278. * @name $compileProvider#directive
  6279. * @kind function
  6280. *
  6281. * @description
  6282. * Register a new directive with the compiler.
  6283. *
  6284. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6285. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6286. * names and the values are the factories.
  6287. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6288. * {@link guide/directive} for more info.
  6289. * @returns {ng.$compileProvider} Self for chaining.
  6290. */
  6291. this.directive = function registerDirective(name, directiveFactory) {
  6292. assertNotHasOwnProperty(name, 'directive');
  6293. if (isString(name)) {
  6294. assertValidDirectiveName(name);
  6295. assertArg(directiveFactory, 'directiveFactory');
  6296. if (!hasDirectives.hasOwnProperty(name)) {
  6297. hasDirectives[name] = [];
  6298. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6299. function($injector, $exceptionHandler) {
  6300. var directives = [];
  6301. forEach(hasDirectives[name], function(directiveFactory, index) {
  6302. try {
  6303. var directive = $injector.invoke(directiveFactory);
  6304. if (isFunction(directive)) {
  6305. directive = { compile: valueFn(directive) };
  6306. } else if (!directive.compile && directive.link) {
  6307. directive.compile = valueFn(directive.link);
  6308. }
  6309. directive.priority = directive.priority || 0;
  6310. directive.index = index;
  6311. directive.name = directive.name || name;
  6312. directive.require = directive.require || (directive.controller && directive.name);
  6313. directive.restrict = directive.restrict || 'EA';
  6314. var bindings = directive.$$bindings =
  6315. parseDirectiveBindings(directive, directive.name);
  6316. if (isObject(bindings.isolateScope)) {
  6317. directive.$$isolateBindings = bindings.isolateScope;
  6318. }
  6319. directive.$$moduleName = directiveFactory.$$moduleName;
  6320. directives.push(directive);
  6321. } catch (e) {
  6322. $exceptionHandler(e);
  6323. }
  6324. });
  6325. return directives;
  6326. }]);
  6327. }
  6328. hasDirectives[name].push(directiveFactory);
  6329. } else {
  6330. forEach(name, reverseParams(registerDirective));
  6331. }
  6332. return this;
  6333. };
  6334. /**
  6335. * @ngdoc method
  6336. * @name $compileProvider#aHrefSanitizationWhitelist
  6337. * @kind function
  6338. *
  6339. * @description
  6340. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6341. * urls during a[href] sanitization.
  6342. *
  6343. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6344. *
  6345. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6346. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6347. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6348. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6349. *
  6350. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6351. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6352. * chaining otherwise.
  6353. */
  6354. this.aHrefSanitizationWhitelist = function(regexp) {
  6355. if (isDefined(regexp)) {
  6356. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6357. return this;
  6358. } else {
  6359. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6360. }
  6361. };
  6362. /**
  6363. * @ngdoc method
  6364. * @name $compileProvider#imgSrcSanitizationWhitelist
  6365. * @kind function
  6366. *
  6367. * @description
  6368. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6369. * urls during img[src] sanitization.
  6370. *
  6371. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6372. *
  6373. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6374. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6375. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6376. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6377. *
  6378. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6379. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6380. * chaining otherwise.
  6381. */
  6382. this.imgSrcSanitizationWhitelist = function(regexp) {
  6383. if (isDefined(regexp)) {
  6384. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6385. return this;
  6386. } else {
  6387. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6388. }
  6389. };
  6390. /**
  6391. * @ngdoc method
  6392. * @name $compileProvider#debugInfoEnabled
  6393. *
  6394. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6395. * current debugInfoEnabled state
  6396. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6397. *
  6398. * @kind function
  6399. *
  6400. * @description
  6401. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6402. * binding information and a reference to the current scope on to DOM elements.
  6403. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6404. * * `ng-binding` CSS class
  6405. * * `$binding` data property containing an array of the binding expressions
  6406. *
  6407. * You may want to disable this in production for a significant performance boost. See
  6408. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6409. *
  6410. * The default value is true.
  6411. */
  6412. var debugInfoEnabled = true;
  6413. this.debugInfoEnabled = function(enabled) {
  6414. if (isDefined(enabled)) {
  6415. debugInfoEnabled = enabled;
  6416. return this;
  6417. }
  6418. return debugInfoEnabled;
  6419. };
  6420. this.$get = [
  6421. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6422. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6423. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6424. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6425. var Attributes = function(element, attributesToCopy) {
  6426. if (attributesToCopy) {
  6427. var keys = Object.keys(attributesToCopy);
  6428. var i, l, key;
  6429. for (i = 0, l = keys.length; i < l; i++) {
  6430. key = keys[i];
  6431. this[key] = attributesToCopy[key];
  6432. }
  6433. } else {
  6434. this.$attr = {};
  6435. }
  6436. this.$$element = element;
  6437. };
  6438. Attributes.prototype = {
  6439. /**
  6440. * @ngdoc method
  6441. * @name $compile.directive.Attributes#$normalize
  6442. * @kind function
  6443. *
  6444. * @description
  6445. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6446. * `data-`) to its normalized, camelCase form.
  6447. *
  6448. * Also there is special case for Moz prefix starting with upper case letter.
  6449. *
  6450. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6451. *
  6452. * @param {string} name Name to normalize
  6453. */
  6454. $normalize: directiveNormalize,
  6455. /**
  6456. * @ngdoc method
  6457. * @name $compile.directive.Attributes#$addClass
  6458. * @kind function
  6459. *
  6460. * @description
  6461. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6462. * are enabled then an animation will be triggered for the class addition.
  6463. *
  6464. * @param {string} classVal The className value that will be added to the element
  6465. */
  6466. $addClass: function(classVal) {
  6467. if (classVal && classVal.length > 0) {
  6468. $animate.addClass(this.$$element, classVal);
  6469. }
  6470. },
  6471. /**
  6472. * @ngdoc method
  6473. * @name $compile.directive.Attributes#$removeClass
  6474. * @kind function
  6475. *
  6476. * @description
  6477. * Removes the CSS class value specified by the classVal parameter from the element. If
  6478. * animations are enabled then an animation will be triggered for the class removal.
  6479. *
  6480. * @param {string} classVal The className value that will be removed from the element
  6481. */
  6482. $removeClass: function(classVal) {
  6483. if (classVal && classVal.length > 0) {
  6484. $animate.removeClass(this.$$element, classVal);
  6485. }
  6486. },
  6487. /**
  6488. * @ngdoc method
  6489. * @name $compile.directive.Attributes#$updateClass
  6490. * @kind function
  6491. *
  6492. * @description
  6493. * Adds and removes the appropriate CSS class values to the element based on the difference
  6494. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6495. *
  6496. * @param {string} newClasses The current CSS className value
  6497. * @param {string} oldClasses The former CSS className value
  6498. */
  6499. $updateClass: function(newClasses, oldClasses) {
  6500. var toAdd = tokenDifference(newClasses, oldClasses);
  6501. if (toAdd && toAdd.length) {
  6502. $animate.addClass(this.$$element, toAdd);
  6503. }
  6504. var toRemove = tokenDifference(oldClasses, newClasses);
  6505. if (toRemove && toRemove.length) {
  6506. $animate.removeClass(this.$$element, toRemove);
  6507. }
  6508. },
  6509. /**
  6510. * Set a normalized attribute on the element in a way such that all directives
  6511. * can share the attribute. This function properly handles boolean attributes.
  6512. * @param {string} key Normalized key. (ie ngAttribute)
  6513. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6514. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6515. * Defaults to true.
  6516. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6517. */
  6518. $set: function(key, value, writeAttr, attrName) {
  6519. // TODO: decide whether or not to throw an error if "class"
  6520. //is set through this function since it may cause $updateClass to
  6521. //become unstable.
  6522. var node = this.$$element[0],
  6523. booleanKey = getBooleanAttrName(node, key),
  6524. aliasedKey = getAliasedAttrName(node, key),
  6525. observer = key,
  6526. nodeName;
  6527. if (booleanKey) {
  6528. this.$$element.prop(key, value);
  6529. attrName = booleanKey;
  6530. } else if (aliasedKey) {
  6531. this[aliasedKey] = value;
  6532. observer = aliasedKey;
  6533. }
  6534. this[key] = value;
  6535. // translate normalized key to actual key
  6536. if (attrName) {
  6537. this.$attr[key] = attrName;
  6538. } else {
  6539. attrName = this.$attr[key];
  6540. if (!attrName) {
  6541. this.$attr[key] = attrName = snake_case(key, '-');
  6542. }
  6543. }
  6544. nodeName = nodeName_(this.$$element);
  6545. if ((nodeName === 'a' && key === 'href') ||
  6546. (nodeName === 'img' && key === 'src')) {
  6547. // sanitize a[href] and img[src] values
  6548. this[key] = value = $$sanitizeUri(value, key === 'src');
  6549. } else if (nodeName === 'img' && key === 'srcset') {
  6550. // sanitize img[srcset] values
  6551. var result = "";
  6552. // first check if there are spaces because it's not the same pattern
  6553. var trimmedSrcset = trim(value);
  6554. // ( 999x ,| 999w ,| ,|, )
  6555. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6556. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6557. // split srcset into tuple of uri and descriptor except for the last item
  6558. var rawUris = trimmedSrcset.split(pattern);
  6559. // for each tuples
  6560. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6561. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6562. var innerIdx = i * 2;
  6563. // sanitize the uri
  6564. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6565. // add the descriptor
  6566. result += (" " + trim(rawUris[innerIdx + 1]));
  6567. }
  6568. // split the last item into uri and descriptor
  6569. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6570. // sanitize the last uri
  6571. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6572. // and add the last descriptor if any
  6573. if (lastTuple.length === 2) {
  6574. result += (" " + trim(lastTuple[1]));
  6575. }
  6576. this[key] = value = result;
  6577. }
  6578. if (writeAttr !== false) {
  6579. if (value === null || value === undefined) {
  6580. this.$$element.removeAttr(attrName);
  6581. } else {
  6582. this.$$element.attr(attrName, value);
  6583. }
  6584. }
  6585. // fire observers
  6586. var $$observers = this.$$observers;
  6587. $$observers && forEach($$observers[observer], function(fn) {
  6588. try {
  6589. fn(value);
  6590. } catch (e) {
  6591. $exceptionHandler(e);
  6592. }
  6593. });
  6594. },
  6595. /**
  6596. * @ngdoc method
  6597. * @name $compile.directive.Attributes#$observe
  6598. * @kind function
  6599. *
  6600. * @description
  6601. * Observes an interpolated attribute.
  6602. *
  6603. * The observer function will be invoked once during the next `$digest` following
  6604. * compilation. The observer is then invoked whenever the interpolated value
  6605. * changes.
  6606. *
  6607. * @param {string} key Normalized key. (ie ngAttribute) .
  6608. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6609. the interpolated value of the attribute changes.
  6610. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6611. * @returns {function()} Returns a deregistration function for this observer.
  6612. */
  6613. $observe: function(key, fn) {
  6614. var attrs = this,
  6615. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6616. listeners = ($$observers[key] || ($$observers[key] = []));
  6617. listeners.push(fn);
  6618. $rootScope.$evalAsync(function() {
  6619. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6620. // no one registered attribute interpolation function, so lets call it manually
  6621. fn(attrs[key]);
  6622. }
  6623. });
  6624. return function() {
  6625. arrayRemove(listeners, fn);
  6626. };
  6627. }
  6628. };
  6629. function safeAddClass($element, className) {
  6630. try {
  6631. $element.addClass(className);
  6632. } catch (e) {
  6633. // ignore, since it means that we are trying to set class on
  6634. // SVG element, where class name is read-only.
  6635. }
  6636. }
  6637. var startSymbol = $interpolate.startSymbol(),
  6638. endSymbol = $interpolate.endSymbol(),
  6639. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6640. ? identity
  6641. : function denormalizeTemplate(template) {
  6642. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6643. },
  6644. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6645. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6646. var bindings = $element.data('$binding') || [];
  6647. if (isArray(binding)) {
  6648. bindings = bindings.concat(binding);
  6649. } else {
  6650. bindings.push(binding);
  6651. }
  6652. $element.data('$binding', bindings);
  6653. } : noop;
  6654. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6655. safeAddClass($element, 'ng-binding');
  6656. } : noop;
  6657. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6658. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6659. $element.data(dataName, scope);
  6660. } : noop;
  6661. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6662. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6663. } : noop;
  6664. return compile;
  6665. //================================
  6666. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6667. previousCompileContext) {
  6668. if (!($compileNodes instanceof jqLite)) {
  6669. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6670. // modify it.
  6671. $compileNodes = jqLite($compileNodes);
  6672. }
  6673. // We can not compile top level text elements since text nodes can be merged and we will
  6674. // not be able to attach scope data to them, so we will wrap them in <span>
  6675. forEach($compileNodes, function(node, index) {
  6676. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6677. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6678. }
  6679. });
  6680. var compositeLinkFn =
  6681. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6682. maxPriority, ignoreDirective, previousCompileContext);
  6683. compile.$$addScopeClass($compileNodes);
  6684. var namespace = null;
  6685. return function publicLinkFn(scope, cloneConnectFn, options) {
  6686. assertArg(scope, 'scope');
  6687. options = options || {};
  6688. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6689. transcludeControllers = options.transcludeControllers,
  6690. futureParentElement = options.futureParentElement;
  6691. // When `parentBoundTranscludeFn` is passed, it is a
  6692. // `controllersBoundTransclude` function (it was previously passed
  6693. // as `transclude` to directive.link) so we must unwrap it to get
  6694. // its `boundTranscludeFn`
  6695. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6696. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6697. }
  6698. if (!namespace) {
  6699. namespace = detectNamespaceForChildElements(futureParentElement);
  6700. }
  6701. var $linkNode;
  6702. if (namespace !== 'html') {
  6703. // When using a directive with replace:true and templateUrl the $compileNodes
  6704. // (or a child element inside of them)
  6705. // might change, so we need to recreate the namespace adapted compileNodes
  6706. // for call to the link function.
  6707. // Note: This will already clone the nodes...
  6708. $linkNode = jqLite(
  6709. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6710. );
  6711. } else if (cloneConnectFn) {
  6712. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6713. // and sometimes changes the structure of the DOM.
  6714. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6715. } else {
  6716. $linkNode = $compileNodes;
  6717. }
  6718. if (transcludeControllers) {
  6719. for (var controllerName in transcludeControllers) {
  6720. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6721. }
  6722. }
  6723. compile.$$addScopeInfo($linkNode, scope);
  6724. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6725. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6726. return $linkNode;
  6727. };
  6728. }
  6729. function detectNamespaceForChildElements(parentElement) {
  6730. // TODO: Make this detect MathML as well...
  6731. var node = parentElement && parentElement[0];
  6732. if (!node) {
  6733. return 'html';
  6734. } else {
  6735. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6736. }
  6737. }
  6738. /**
  6739. * Compile function matches each node in nodeList against the directives. Once all directives
  6740. * for a particular node are collected their compile functions are executed. The compile
  6741. * functions return values - the linking functions - are combined into a composite linking
  6742. * function, which is the a linking function for the node.
  6743. *
  6744. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6745. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6746. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6747. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6748. * the rootElement must be set the jqLite collection of the compile root. This is
  6749. * needed so that the jqLite collection items can be replaced with widgets.
  6750. * @param {number=} maxPriority Max directive priority.
  6751. * @returns {Function} A composite linking function of all of the matched directives or null.
  6752. */
  6753. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6754. previousCompileContext) {
  6755. var linkFns = [],
  6756. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6757. for (var i = 0; i < nodeList.length; i++) {
  6758. attrs = new Attributes();
  6759. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6760. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6761. ignoreDirective);
  6762. nodeLinkFn = (directives.length)
  6763. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6764. null, [], [], previousCompileContext)
  6765. : null;
  6766. if (nodeLinkFn && nodeLinkFn.scope) {
  6767. compile.$$addScopeClass(attrs.$$element);
  6768. }
  6769. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6770. !(childNodes = nodeList[i].childNodes) ||
  6771. !childNodes.length)
  6772. ? null
  6773. : compileNodes(childNodes,
  6774. nodeLinkFn ? (
  6775. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6776. && nodeLinkFn.transclude) : transcludeFn);
  6777. if (nodeLinkFn || childLinkFn) {
  6778. linkFns.push(i, nodeLinkFn, childLinkFn);
  6779. linkFnFound = true;
  6780. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6781. }
  6782. //use the previous context only for the first element in the virtual group
  6783. previousCompileContext = null;
  6784. }
  6785. // return a linking function if we have found anything, null otherwise
  6786. return linkFnFound ? compositeLinkFn : null;
  6787. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6788. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6789. var stableNodeList;
  6790. if (nodeLinkFnFound) {
  6791. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6792. // offsets don't get screwed up
  6793. var nodeListLength = nodeList.length;
  6794. stableNodeList = new Array(nodeListLength);
  6795. // create a sparse array by only copying the elements which have a linkFn
  6796. for (i = 0; i < linkFns.length; i+=3) {
  6797. idx = linkFns[i];
  6798. stableNodeList[idx] = nodeList[idx];
  6799. }
  6800. } else {
  6801. stableNodeList = nodeList;
  6802. }
  6803. for (i = 0, ii = linkFns.length; i < ii;) {
  6804. node = stableNodeList[linkFns[i++]];
  6805. nodeLinkFn = linkFns[i++];
  6806. childLinkFn = linkFns[i++];
  6807. if (nodeLinkFn) {
  6808. if (nodeLinkFn.scope) {
  6809. childScope = scope.$new();
  6810. compile.$$addScopeInfo(jqLite(node), childScope);
  6811. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6812. if (destroyBindings) {
  6813. nodeLinkFn.$$destroyBindings = null;
  6814. childScope.$on('$destroyed', destroyBindings);
  6815. }
  6816. } else {
  6817. childScope = scope;
  6818. }
  6819. if (nodeLinkFn.transcludeOnThisElement) {
  6820. childBoundTranscludeFn = createBoundTranscludeFn(
  6821. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6822. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6823. childBoundTranscludeFn = parentBoundTranscludeFn;
  6824. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6825. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6826. } else {
  6827. childBoundTranscludeFn = null;
  6828. }
  6829. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6830. nodeLinkFn);
  6831. } else if (childLinkFn) {
  6832. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6833. }
  6834. }
  6835. }
  6836. }
  6837. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  6838. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6839. if (!transcludedScope) {
  6840. transcludedScope = scope.$new(false, containingScope);
  6841. transcludedScope.$$transcluded = true;
  6842. }
  6843. return transcludeFn(transcludedScope, cloneFn, {
  6844. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6845. transcludeControllers: controllers,
  6846. futureParentElement: futureParentElement
  6847. });
  6848. };
  6849. return boundTranscludeFn;
  6850. }
  6851. /**
  6852. * Looks for directives on the given node and adds them to the directive collection which is
  6853. * sorted.
  6854. *
  6855. * @param node Node to search.
  6856. * @param directives An array to which the directives are added to. This array is sorted before
  6857. * the function returns.
  6858. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6859. * @param {number=} maxPriority Max directive priority.
  6860. */
  6861. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6862. var nodeType = node.nodeType,
  6863. attrsMap = attrs.$attr,
  6864. match,
  6865. className;
  6866. switch (nodeType) {
  6867. case NODE_TYPE_ELEMENT: /* Element */
  6868. // use the node name: <directive>
  6869. addDirective(directives,
  6870. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6871. // iterate over the attributes
  6872. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6873. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6874. var attrStartName = false;
  6875. var attrEndName = false;
  6876. attr = nAttrs[j];
  6877. name = attr.name;
  6878. value = trim(attr.value);
  6879. // support ngAttr attribute binding
  6880. ngAttrName = directiveNormalize(name);
  6881. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6882. name = name.replace(PREFIX_REGEXP, '')
  6883. .substr(8).replace(/_(.)/g, function(match, letter) {
  6884. return letter.toUpperCase();
  6885. });
  6886. }
  6887. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6888. if (directiveIsMultiElement(directiveNName)) {
  6889. if (ngAttrName === directiveNName + 'Start') {
  6890. attrStartName = name;
  6891. attrEndName = name.substr(0, name.length - 5) + 'end';
  6892. name = name.substr(0, name.length - 6);
  6893. }
  6894. }
  6895. nName = directiveNormalize(name.toLowerCase());
  6896. attrsMap[nName] = name;
  6897. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6898. attrs[nName] = value;
  6899. if (getBooleanAttrName(node, nName)) {
  6900. attrs[nName] = true; // presence means true
  6901. }
  6902. }
  6903. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6904. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6905. attrEndName);
  6906. }
  6907. // use class as directive
  6908. className = node.className;
  6909. if (isObject(className)) {
  6910. // Maybe SVGAnimatedString
  6911. className = className.animVal;
  6912. }
  6913. if (isString(className) && className !== '') {
  6914. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6915. nName = directiveNormalize(match[2]);
  6916. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6917. attrs[nName] = trim(match[3]);
  6918. }
  6919. className = className.substr(match.index + match[0].length);
  6920. }
  6921. }
  6922. break;
  6923. case NODE_TYPE_TEXT: /* Text Node */
  6924. if (msie === 11) {
  6925. // Workaround for #11781
  6926. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  6927. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  6928. node.parentNode.removeChild(node.nextSibling);
  6929. }
  6930. }
  6931. addTextInterpolateDirective(directives, node.nodeValue);
  6932. break;
  6933. case NODE_TYPE_COMMENT: /* Comment */
  6934. try {
  6935. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6936. if (match) {
  6937. nName = directiveNormalize(match[1]);
  6938. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6939. attrs[nName] = trim(match[2]);
  6940. }
  6941. }
  6942. } catch (e) {
  6943. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6944. // comment's node value.
  6945. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6946. }
  6947. break;
  6948. }
  6949. directives.sort(byPriority);
  6950. return directives;
  6951. }
  6952. /**
  6953. * Given a node with an directive-start it collects all of the siblings until it finds
  6954. * directive-end.
  6955. * @param node
  6956. * @param attrStart
  6957. * @param attrEnd
  6958. * @returns {*}
  6959. */
  6960. function groupScan(node, attrStart, attrEnd) {
  6961. var nodes = [];
  6962. var depth = 0;
  6963. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6964. do {
  6965. if (!node) {
  6966. throw $compileMinErr('uterdir',
  6967. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6968. attrStart, attrEnd);
  6969. }
  6970. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6971. if (node.hasAttribute(attrStart)) depth++;
  6972. if (node.hasAttribute(attrEnd)) depth--;
  6973. }
  6974. nodes.push(node);
  6975. node = node.nextSibling;
  6976. } while (depth > 0);
  6977. } else {
  6978. nodes.push(node);
  6979. }
  6980. return jqLite(nodes);
  6981. }
  6982. /**
  6983. * Wrapper for linking function which converts normal linking function into a grouped
  6984. * linking function.
  6985. * @param linkFn
  6986. * @param attrStart
  6987. * @param attrEnd
  6988. * @returns {Function}
  6989. */
  6990. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6991. return function(scope, element, attrs, controllers, transcludeFn) {
  6992. element = groupScan(element[0], attrStart, attrEnd);
  6993. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6994. };
  6995. }
  6996. /**
  6997. * Once the directives have been collected, their compile functions are executed. This method
  6998. * is responsible for inlining directive templates as well as terminating the application
  6999. * of the directives if the terminal directive has been reached.
  7000. *
  7001. * @param {Array} directives Array of collected directives to execute their compile function.
  7002. * this needs to be pre-sorted by priority order.
  7003. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7004. * @param {Object} templateAttrs The shared attribute function
  7005. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7006. * scope argument is auto-generated to the new
  7007. * child of the transcluded parent scope.
  7008. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7009. * argument has the root jqLite array so that we can replace nodes
  7010. * on it.
  7011. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7012. * compiling the transclusion.
  7013. * @param {Array.<Function>} preLinkFns
  7014. * @param {Array.<Function>} postLinkFns
  7015. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7016. * node
  7017. * @returns {Function} linkFn
  7018. */
  7019. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7020. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7021. previousCompileContext) {
  7022. previousCompileContext = previousCompileContext || {};
  7023. var terminalPriority = -Number.MAX_VALUE,
  7024. newScopeDirective,
  7025. controllerDirectives = previousCompileContext.controllerDirectives,
  7026. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7027. templateDirective = previousCompileContext.templateDirective,
  7028. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7029. hasTranscludeDirective = false,
  7030. hasTemplate = false,
  7031. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7032. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7033. directive,
  7034. directiveName,
  7035. $template,
  7036. replaceDirective = originalReplaceDirective,
  7037. childTranscludeFn = transcludeFn,
  7038. linkFn,
  7039. directiveValue;
  7040. // executes all directives on the current element
  7041. for (var i = 0, ii = directives.length; i < ii; i++) {
  7042. directive = directives[i];
  7043. var attrStart = directive.$$start;
  7044. var attrEnd = directive.$$end;
  7045. // collect multiblock sections
  7046. if (attrStart) {
  7047. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7048. }
  7049. $template = undefined;
  7050. if (terminalPriority > directive.priority) {
  7051. break; // prevent further processing of directives
  7052. }
  7053. if (directiveValue = directive.scope) {
  7054. // skip the check for directives with async templates, we'll check the derived sync
  7055. // directive when the template arrives
  7056. if (!directive.templateUrl) {
  7057. if (isObject(directiveValue)) {
  7058. // This directive is trying to add an isolated scope.
  7059. // Check that there is no scope of any kind already
  7060. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7061. directive, $compileNode);
  7062. newIsolateScopeDirective = directive;
  7063. } else {
  7064. // This directive is trying to add a child scope.
  7065. // Check that there is no isolated scope already
  7066. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7067. $compileNode);
  7068. }
  7069. }
  7070. newScopeDirective = newScopeDirective || directive;
  7071. }
  7072. directiveName = directive.name;
  7073. if (!directive.templateUrl && directive.controller) {
  7074. directiveValue = directive.controller;
  7075. controllerDirectives = controllerDirectives || createMap();
  7076. assertNoDuplicate("'" + directiveName + "' controller",
  7077. controllerDirectives[directiveName], directive, $compileNode);
  7078. controllerDirectives[directiveName] = directive;
  7079. }
  7080. if (directiveValue = directive.transclude) {
  7081. hasTranscludeDirective = true;
  7082. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7083. // This option should only be used by directives that know how to safely handle element transclusion,
  7084. // where the transcluded nodes are added or replaced after linking.
  7085. if (!directive.$$tlb) {
  7086. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7087. nonTlbTranscludeDirective = directive;
  7088. }
  7089. if (directiveValue == 'element') {
  7090. hasElementTranscludeDirective = true;
  7091. terminalPriority = directive.priority;
  7092. $template = $compileNode;
  7093. $compileNode = templateAttrs.$$element =
  7094. jqLite(document.createComment(' ' + directiveName + ': ' +
  7095. templateAttrs[directiveName] + ' '));
  7096. compileNode = $compileNode[0];
  7097. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7098. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7099. replaceDirective && replaceDirective.name, {
  7100. // Don't pass in:
  7101. // - controllerDirectives - otherwise we'll create duplicates controllers
  7102. // - newIsolateScopeDirective or templateDirective - combining templates with
  7103. // element transclusion doesn't make sense.
  7104. //
  7105. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7106. // on the same element more than once.
  7107. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7108. });
  7109. } else {
  7110. $template = jqLite(jqLiteClone(compileNode)).contents();
  7111. $compileNode.empty(); // clear contents
  7112. childTranscludeFn = compile($template, transcludeFn);
  7113. }
  7114. }
  7115. if (directive.template) {
  7116. hasTemplate = true;
  7117. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7118. templateDirective = directive;
  7119. directiveValue = (isFunction(directive.template))
  7120. ? directive.template($compileNode, templateAttrs)
  7121. : directive.template;
  7122. directiveValue = denormalizeTemplate(directiveValue);
  7123. if (directive.replace) {
  7124. replaceDirective = directive;
  7125. if (jqLiteIsTextNode(directiveValue)) {
  7126. $template = [];
  7127. } else {
  7128. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7129. }
  7130. compileNode = $template[0];
  7131. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7132. throw $compileMinErr('tplrt',
  7133. "Template for directive '{0}' must have exactly one root element. {1}",
  7134. directiveName, '');
  7135. }
  7136. replaceWith(jqCollection, $compileNode, compileNode);
  7137. var newTemplateAttrs = {$attr: {}};
  7138. // combine directives from the original node and from the template:
  7139. // - take the array of directives for this element
  7140. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7141. // - collect directives from the template and sort them by priority
  7142. // - combine directives as: processed + template + unprocessed
  7143. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7144. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7145. if (newIsolateScopeDirective) {
  7146. markDirectivesAsIsolate(templateDirectives);
  7147. }
  7148. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7149. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7150. ii = directives.length;
  7151. } else {
  7152. $compileNode.html(directiveValue);
  7153. }
  7154. }
  7155. if (directive.templateUrl) {
  7156. hasTemplate = true;
  7157. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7158. templateDirective = directive;
  7159. if (directive.replace) {
  7160. replaceDirective = directive;
  7161. }
  7162. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7163. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7164. controllerDirectives: controllerDirectives,
  7165. newIsolateScopeDirective: newIsolateScopeDirective,
  7166. templateDirective: templateDirective,
  7167. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7168. });
  7169. ii = directives.length;
  7170. } else if (directive.compile) {
  7171. try {
  7172. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7173. if (isFunction(linkFn)) {
  7174. addLinkFns(null, linkFn, attrStart, attrEnd);
  7175. } else if (linkFn) {
  7176. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7177. }
  7178. } catch (e) {
  7179. $exceptionHandler(e, startingTag($compileNode));
  7180. }
  7181. }
  7182. if (directive.terminal) {
  7183. nodeLinkFn.terminal = true;
  7184. terminalPriority = Math.max(terminalPriority, directive.priority);
  7185. }
  7186. }
  7187. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7188. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7189. nodeLinkFn.templateOnThisElement = hasTemplate;
  7190. nodeLinkFn.transclude = childTranscludeFn;
  7191. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7192. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7193. return nodeLinkFn;
  7194. ////////////////////
  7195. function addLinkFns(pre, post, attrStart, attrEnd) {
  7196. if (pre) {
  7197. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7198. pre.require = directive.require;
  7199. pre.directiveName = directiveName;
  7200. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7201. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7202. }
  7203. preLinkFns.push(pre);
  7204. }
  7205. if (post) {
  7206. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7207. post.require = directive.require;
  7208. post.directiveName = directiveName;
  7209. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7210. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7211. }
  7212. postLinkFns.push(post);
  7213. }
  7214. }
  7215. function getControllers(directiveName, require, $element, elementControllers) {
  7216. var value;
  7217. if (isString(require)) {
  7218. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7219. var name = require.substring(match[0].length);
  7220. var inheritType = match[1] || match[3];
  7221. var optional = match[2] === '?';
  7222. //If only parents then start at the parent element
  7223. if (inheritType === '^^') {
  7224. $element = $element.parent();
  7225. //Otherwise attempt getting the controller from elementControllers in case
  7226. //the element is transcluded (and has no data) and to avoid .data if possible
  7227. } else {
  7228. value = elementControllers && elementControllers[name];
  7229. value = value && value.instance;
  7230. }
  7231. if (!value) {
  7232. var dataName = '$' + name + 'Controller';
  7233. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7234. }
  7235. if (!value && !optional) {
  7236. throw $compileMinErr('ctreq',
  7237. "Controller '{0}', required by directive '{1}', can't be found!",
  7238. name, directiveName);
  7239. }
  7240. } else if (isArray(require)) {
  7241. value = [];
  7242. for (var i = 0, ii = require.length; i < ii; i++) {
  7243. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7244. }
  7245. }
  7246. return value || null;
  7247. }
  7248. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7249. var elementControllers = createMap();
  7250. for (var controllerKey in controllerDirectives) {
  7251. var directive = controllerDirectives[controllerKey];
  7252. var locals = {
  7253. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7254. $element: $element,
  7255. $attrs: attrs,
  7256. $transclude: transcludeFn
  7257. };
  7258. var controller = directive.controller;
  7259. if (controller == '@') {
  7260. controller = attrs[directive.name];
  7261. }
  7262. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7263. // For directives with element transclusion the element is a comment,
  7264. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7265. // clean up (http://bugs.jquery.com/ticket/8335).
  7266. // Instead, we save the controllers for the element in a local hash and attach to .data
  7267. // later, once we have the actual element.
  7268. elementControllers[directive.name] = controllerInstance;
  7269. if (!hasElementTranscludeDirective) {
  7270. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7271. }
  7272. }
  7273. return elementControllers;
  7274. }
  7275. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7276. thisLinkFn) {
  7277. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7278. attrs;
  7279. if (compileNode === linkNode) {
  7280. attrs = templateAttrs;
  7281. $element = templateAttrs.$$element;
  7282. } else {
  7283. $element = jqLite(linkNode);
  7284. attrs = new Attributes($element, templateAttrs);
  7285. }
  7286. if (newIsolateScopeDirective) {
  7287. isolateScope = scope.$new(true);
  7288. }
  7289. if (boundTranscludeFn) {
  7290. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7291. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7292. transcludeFn = controllersBoundTransclude;
  7293. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7294. }
  7295. if (controllerDirectives) {
  7296. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7297. }
  7298. if (newIsolateScopeDirective) {
  7299. // Initialize isolate scope bindings for new isolate scope directive.
  7300. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7301. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7302. compile.$$addScopeClass($element, true);
  7303. isolateScope.$$isolateBindings =
  7304. newIsolateScopeDirective.$$isolateBindings;
  7305. initializeDirectiveBindings(scope, attrs, isolateScope,
  7306. isolateScope.$$isolateBindings,
  7307. newIsolateScopeDirective, isolateScope);
  7308. }
  7309. if (elementControllers) {
  7310. // Initialize bindToController bindings for new/isolate scopes
  7311. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7312. var bindings;
  7313. var controllerForBindings;
  7314. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7315. bindings = scopeDirective.$$bindings.bindToController;
  7316. controller = elementControllers[scopeDirective.name];
  7317. if (controller && controller.identifier && bindings) {
  7318. controllerForBindings = controller;
  7319. thisLinkFn.$$destroyBindings =
  7320. initializeDirectiveBindings(scope, attrs, controller.instance,
  7321. bindings, scopeDirective);
  7322. }
  7323. }
  7324. for (i in elementControllers) {
  7325. controller = elementControllers[i];
  7326. var controllerResult = controller();
  7327. if (controllerResult !== controller.instance) {
  7328. // If the controller constructor has a return value, overwrite the instance
  7329. // from setupControllers and update the element data
  7330. controller.instance = controllerResult;
  7331. $element.data('$' + i + 'Controller', controllerResult);
  7332. if (controller === controllerForBindings) {
  7333. // Remove and re-install bindToController bindings
  7334. thisLinkFn.$$destroyBindings();
  7335. thisLinkFn.$$destroyBindings =
  7336. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7337. }
  7338. }
  7339. }
  7340. }
  7341. // PRELINKING
  7342. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7343. linkFn = preLinkFns[i];
  7344. invokeLinkFn(linkFn,
  7345. linkFn.isolateScope ? isolateScope : scope,
  7346. $element,
  7347. attrs,
  7348. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7349. transcludeFn
  7350. );
  7351. }
  7352. // RECURSION
  7353. // We only pass the isolate scope, if the isolate directive has a template,
  7354. // otherwise the child elements do not belong to the isolate directive.
  7355. var scopeToChild = scope;
  7356. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7357. scopeToChild = isolateScope;
  7358. }
  7359. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7360. // POSTLINKING
  7361. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7362. linkFn = postLinkFns[i];
  7363. invokeLinkFn(linkFn,
  7364. linkFn.isolateScope ? isolateScope : scope,
  7365. $element,
  7366. attrs,
  7367. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7368. transcludeFn
  7369. );
  7370. }
  7371. // This is the function that is injected as `$transclude`.
  7372. // Note: all arguments are optional!
  7373. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7374. var transcludeControllers;
  7375. // No scope passed in:
  7376. if (!isScope(scope)) {
  7377. futureParentElement = cloneAttachFn;
  7378. cloneAttachFn = scope;
  7379. scope = undefined;
  7380. }
  7381. if (hasElementTranscludeDirective) {
  7382. transcludeControllers = elementControllers;
  7383. }
  7384. if (!futureParentElement) {
  7385. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7386. }
  7387. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7388. }
  7389. }
  7390. }
  7391. function markDirectivesAsIsolate(directives) {
  7392. // mark all directives as needing isolate scope.
  7393. for (var j = 0, jj = directives.length; j < jj; j++) {
  7394. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7395. }
  7396. }
  7397. /**
  7398. * looks up the directive and decorates it with exception handling and proper parameters. We
  7399. * call this the boundDirective.
  7400. *
  7401. * @param {string} name name of the directive to look up.
  7402. * @param {string} location The directive must be found in specific format.
  7403. * String containing any of theses characters:
  7404. *
  7405. * * `E`: element name
  7406. * * `A': attribute
  7407. * * `C`: class
  7408. * * `M`: comment
  7409. * @returns {boolean} true if directive was added.
  7410. */
  7411. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7412. endAttrName) {
  7413. if (name === ignoreDirective) return null;
  7414. var match = null;
  7415. if (hasDirectives.hasOwnProperty(name)) {
  7416. for (var directive, directives = $injector.get(name + Suffix),
  7417. i = 0, ii = directives.length; i < ii; i++) {
  7418. try {
  7419. directive = directives[i];
  7420. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7421. directive.restrict.indexOf(location) != -1) {
  7422. if (startAttrName) {
  7423. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7424. }
  7425. tDirectives.push(directive);
  7426. match = directive;
  7427. }
  7428. } catch (e) { $exceptionHandler(e); }
  7429. }
  7430. }
  7431. return match;
  7432. }
  7433. /**
  7434. * looks up the directive and returns true if it is a multi-element directive,
  7435. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7436. * together.
  7437. *
  7438. * @param {string} name name of the directive to look up.
  7439. * @returns true if directive was registered as multi-element.
  7440. */
  7441. function directiveIsMultiElement(name) {
  7442. if (hasDirectives.hasOwnProperty(name)) {
  7443. for (var directive, directives = $injector.get(name + Suffix),
  7444. i = 0, ii = directives.length; i < ii; i++) {
  7445. directive = directives[i];
  7446. if (directive.multiElement) {
  7447. return true;
  7448. }
  7449. }
  7450. }
  7451. return false;
  7452. }
  7453. /**
  7454. * When the element is replaced with HTML template then the new attributes
  7455. * on the template need to be merged with the existing attributes in the DOM.
  7456. * The desired effect is to have both of the attributes present.
  7457. *
  7458. * @param {object} dst destination attributes (original DOM)
  7459. * @param {object} src source attributes (from the directive template)
  7460. */
  7461. function mergeTemplateAttributes(dst, src) {
  7462. var srcAttr = src.$attr,
  7463. dstAttr = dst.$attr,
  7464. $element = dst.$$element;
  7465. // reapply the old attributes to the new element
  7466. forEach(dst, function(value, key) {
  7467. if (key.charAt(0) != '$') {
  7468. if (src[key] && src[key] !== value) {
  7469. value += (key === 'style' ? ';' : ' ') + src[key];
  7470. }
  7471. dst.$set(key, value, true, srcAttr[key]);
  7472. }
  7473. });
  7474. // copy the new attributes on the old attrs object
  7475. forEach(src, function(value, key) {
  7476. if (key == 'class') {
  7477. safeAddClass($element, value);
  7478. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7479. } else if (key == 'style') {
  7480. $element.attr('style', $element.attr('style') + ';' + value);
  7481. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7482. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7483. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7484. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7485. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7486. dst[key] = value;
  7487. dstAttr[key] = srcAttr[key];
  7488. }
  7489. });
  7490. }
  7491. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7492. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7493. var linkQueue = [],
  7494. afterTemplateNodeLinkFn,
  7495. afterTemplateChildLinkFn,
  7496. beforeTemplateCompileNode = $compileNode[0],
  7497. origAsyncDirective = directives.shift(),
  7498. derivedSyncDirective = inherit(origAsyncDirective, {
  7499. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7500. }),
  7501. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7502. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7503. : origAsyncDirective.templateUrl,
  7504. templateNamespace = origAsyncDirective.templateNamespace;
  7505. $compileNode.empty();
  7506. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7507. .then(function(content) {
  7508. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7509. content = denormalizeTemplate(content);
  7510. if (origAsyncDirective.replace) {
  7511. if (jqLiteIsTextNode(content)) {
  7512. $template = [];
  7513. } else {
  7514. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7515. }
  7516. compileNode = $template[0];
  7517. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7518. throw $compileMinErr('tplrt',
  7519. "Template for directive '{0}' must have exactly one root element. {1}",
  7520. origAsyncDirective.name, templateUrl);
  7521. }
  7522. tempTemplateAttrs = {$attr: {}};
  7523. replaceWith($rootElement, $compileNode, compileNode);
  7524. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7525. if (isObject(origAsyncDirective.scope)) {
  7526. markDirectivesAsIsolate(templateDirectives);
  7527. }
  7528. directives = templateDirectives.concat(directives);
  7529. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7530. } else {
  7531. compileNode = beforeTemplateCompileNode;
  7532. $compileNode.html(content);
  7533. }
  7534. directives.unshift(derivedSyncDirective);
  7535. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7536. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7537. previousCompileContext);
  7538. forEach($rootElement, function(node, i) {
  7539. if (node == compileNode) {
  7540. $rootElement[i] = $compileNode[0];
  7541. }
  7542. });
  7543. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7544. while (linkQueue.length) {
  7545. var scope = linkQueue.shift(),
  7546. beforeTemplateLinkNode = linkQueue.shift(),
  7547. linkRootElement = linkQueue.shift(),
  7548. boundTranscludeFn = linkQueue.shift(),
  7549. linkNode = $compileNode[0];
  7550. if (scope.$$destroyed) continue;
  7551. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7552. var oldClasses = beforeTemplateLinkNode.className;
  7553. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7554. origAsyncDirective.replace)) {
  7555. // it was cloned therefore we have to clone as well.
  7556. linkNode = jqLiteClone(compileNode);
  7557. }
  7558. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7559. // Copy in CSS classes from original node
  7560. safeAddClass(jqLite(linkNode), oldClasses);
  7561. }
  7562. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7563. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7564. } else {
  7565. childBoundTranscludeFn = boundTranscludeFn;
  7566. }
  7567. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7568. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7569. }
  7570. linkQueue = null;
  7571. });
  7572. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7573. var childBoundTranscludeFn = boundTranscludeFn;
  7574. if (scope.$$destroyed) return;
  7575. if (linkQueue) {
  7576. linkQueue.push(scope,
  7577. node,
  7578. rootElement,
  7579. childBoundTranscludeFn);
  7580. } else {
  7581. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7582. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7583. }
  7584. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7585. afterTemplateNodeLinkFn);
  7586. }
  7587. };
  7588. }
  7589. /**
  7590. * Sorting function for bound directives.
  7591. */
  7592. function byPriority(a, b) {
  7593. var diff = b.priority - a.priority;
  7594. if (diff !== 0) return diff;
  7595. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7596. return a.index - b.index;
  7597. }
  7598. function assertNoDuplicate(what, previousDirective, directive, element) {
  7599. function wrapModuleNameIfDefined(moduleName) {
  7600. return moduleName ?
  7601. (' (module: ' + moduleName + ')') :
  7602. '';
  7603. }
  7604. if (previousDirective) {
  7605. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7606. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7607. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7608. }
  7609. }
  7610. function addTextInterpolateDirective(directives, text) {
  7611. var interpolateFn = $interpolate(text, true);
  7612. if (interpolateFn) {
  7613. directives.push({
  7614. priority: 0,
  7615. compile: function textInterpolateCompileFn(templateNode) {
  7616. var templateNodeParent = templateNode.parent(),
  7617. hasCompileParent = !!templateNodeParent.length;
  7618. // When transcluding a template that has bindings in the root
  7619. // we don't have a parent and thus need to add the class during linking fn.
  7620. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7621. return function textInterpolateLinkFn(scope, node) {
  7622. var parent = node.parent();
  7623. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7624. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7625. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7626. node[0].nodeValue = value;
  7627. });
  7628. };
  7629. }
  7630. });
  7631. }
  7632. }
  7633. function wrapTemplate(type, template) {
  7634. type = lowercase(type || 'html');
  7635. switch (type) {
  7636. case 'svg':
  7637. case 'math':
  7638. var wrapper = document.createElement('div');
  7639. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7640. return wrapper.childNodes[0].childNodes;
  7641. default:
  7642. return template;
  7643. }
  7644. }
  7645. function getTrustedContext(node, attrNormalizedName) {
  7646. if (attrNormalizedName == "srcdoc") {
  7647. return $sce.HTML;
  7648. }
  7649. var tag = nodeName_(node);
  7650. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7651. if (attrNormalizedName == "xlinkHref" ||
  7652. (tag == "form" && attrNormalizedName == "action") ||
  7653. (tag != "img" && (attrNormalizedName == "src" ||
  7654. attrNormalizedName == "ngSrc"))) {
  7655. return $sce.RESOURCE_URL;
  7656. }
  7657. }
  7658. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7659. var trustedContext = getTrustedContext(node, name);
  7660. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7661. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7662. // no interpolation found -> ignore
  7663. if (!interpolateFn) return;
  7664. if (name === "multiple" && nodeName_(node) === "select") {
  7665. throw $compileMinErr("selmulti",
  7666. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7667. startingTag(node));
  7668. }
  7669. directives.push({
  7670. priority: 100,
  7671. compile: function() {
  7672. return {
  7673. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7674. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7675. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7676. throw $compileMinErr('nodomevents',
  7677. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7678. "ng- versions (such as ng-click instead of onclick) instead.");
  7679. }
  7680. // If the attribute has changed since last $interpolate()ed
  7681. var newValue = attr[name];
  7682. if (newValue !== value) {
  7683. // we need to interpolate again since the attribute value has been updated
  7684. // (e.g. by another directive's compile function)
  7685. // ensure unset/empty values make interpolateFn falsy
  7686. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7687. value = newValue;
  7688. }
  7689. // if attribute was updated so that there is no interpolation going on we don't want to
  7690. // register any observers
  7691. if (!interpolateFn) return;
  7692. // initialize attr object so that it's ready in case we need the value for isolate
  7693. // scope initialization, otherwise the value would not be available from isolate
  7694. // directive's linking fn during linking phase
  7695. attr[name] = interpolateFn(scope);
  7696. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7697. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7698. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7699. //special case for class attribute addition + removal
  7700. //so that class changes can tap into the animation
  7701. //hooks provided by the $animate service. Be sure to
  7702. //skip animations when the first digest occurs (when
  7703. //both the new and the old values are the same) since
  7704. //the CSS classes are the non-interpolated values
  7705. if (name === 'class' && newValue != oldValue) {
  7706. attr.$updateClass(newValue, oldValue);
  7707. } else {
  7708. attr.$set(name, newValue);
  7709. }
  7710. });
  7711. }
  7712. };
  7713. }
  7714. });
  7715. }
  7716. /**
  7717. * This is a special jqLite.replaceWith, which can replace items which
  7718. * have no parents, provided that the containing jqLite collection is provided.
  7719. *
  7720. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7721. * in the root of the tree.
  7722. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7723. * the shell, but replace its DOM node reference.
  7724. * @param {Node} newNode The new DOM node.
  7725. */
  7726. function replaceWith($rootElement, elementsToRemove, newNode) {
  7727. var firstElementToRemove = elementsToRemove[0],
  7728. removeCount = elementsToRemove.length,
  7729. parent = firstElementToRemove.parentNode,
  7730. i, ii;
  7731. if ($rootElement) {
  7732. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7733. if ($rootElement[i] == firstElementToRemove) {
  7734. $rootElement[i++] = newNode;
  7735. for (var j = i, j2 = j + removeCount - 1,
  7736. jj = $rootElement.length;
  7737. j < jj; j++, j2++) {
  7738. if (j2 < jj) {
  7739. $rootElement[j] = $rootElement[j2];
  7740. } else {
  7741. delete $rootElement[j];
  7742. }
  7743. }
  7744. $rootElement.length -= removeCount - 1;
  7745. // If the replaced element is also the jQuery .context then replace it
  7746. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7747. // http://api.jquery.com/context/
  7748. if ($rootElement.context === firstElementToRemove) {
  7749. $rootElement.context = newNode;
  7750. }
  7751. break;
  7752. }
  7753. }
  7754. }
  7755. if (parent) {
  7756. parent.replaceChild(newNode, firstElementToRemove);
  7757. }
  7758. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7759. var fragment = document.createDocumentFragment();
  7760. fragment.appendChild(firstElementToRemove);
  7761. if (jqLite.hasData(firstElementToRemove)) {
  7762. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7763. // data here because there's no public interface in jQuery to do that and copying over
  7764. // event listeners (which is the main use of private data) wouldn't work anyway.
  7765. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7766. // Remove data of the replaced element. We cannot just call .remove()
  7767. // on the element it since that would deallocate scope that is needed
  7768. // for the new node. Instead, remove the data "manually".
  7769. if (!jQuery) {
  7770. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7771. } else {
  7772. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7773. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7774. // the scope to be trashed and we do need the very same scope to work with the new
  7775. // element. However, we cannot just cache the non-patched version and use it here as
  7776. // that would break if another library patches the method after Angular does (one
  7777. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7778. // skipped this one time.
  7779. skipDestroyOnNextJQueryCleanData = true;
  7780. jQuery.cleanData([firstElementToRemove]);
  7781. }
  7782. }
  7783. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7784. var element = elementsToRemove[k];
  7785. jqLite(element).remove(); // must do this way to clean up expando
  7786. fragment.appendChild(element);
  7787. delete elementsToRemove[k];
  7788. }
  7789. elementsToRemove[0] = newNode;
  7790. elementsToRemove.length = 1;
  7791. }
  7792. function cloneAndAnnotateFn(fn, annotation) {
  7793. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7794. }
  7795. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7796. try {
  7797. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7798. } catch (e) {
  7799. $exceptionHandler(e, startingTag($element));
  7800. }
  7801. }
  7802. // Set up $watches for isolate scope and controller bindings. This process
  7803. // only occurs for isolate scopes and new scopes with controllerAs.
  7804. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7805. directive, newScope) {
  7806. var onNewScopeDestroyed;
  7807. forEach(bindings, function(definition, scopeName) {
  7808. var attrName = definition.attrName,
  7809. optional = definition.optional,
  7810. mode = definition.mode, // @, =, or &
  7811. lastValue,
  7812. parentGet, parentSet, compare;
  7813. if (!hasOwnProperty.call(attrs, attrName)) {
  7814. // In the case of user defined a binding with the same name as a method in Object.prototype but didn't set
  7815. // the corresponding attribute. We need to make sure subsequent code won't access to the prototype function
  7816. attrs[attrName] = undefined;
  7817. }
  7818. switch (mode) {
  7819. case '@':
  7820. if (!attrs[attrName] && !optional) {
  7821. destination[scopeName] = undefined;
  7822. }
  7823. attrs.$observe(attrName, function(value) {
  7824. destination[scopeName] = value;
  7825. });
  7826. attrs.$$observers[attrName].$$scope = scope;
  7827. if (attrs[attrName]) {
  7828. // If the attribute has been provided then we trigger an interpolation to ensure
  7829. // the value is there for use in the link fn
  7830. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7831. }
  7832. break;
  7833. case '=':
  7834. if (optional && !attrs[attrName]) {
  7835. return;
  7836. }
  7837. parentGet = $parse(attrs[attrName]);
  7838. if (parentGet.literal) {
  7839. compare = equals;
  7840. } else {
  7841. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7842. }
  7843. parentSet = parentGet.assign || function() {
  7844. // reset the change, or we will throw this exception on every $digest
  7845. lastValue = destination[scopeName] = parentGet(scope);
  7846. throw $compileMinErr('nonassign',
  7847. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7848. attrs[attrName], directive.name);
  7849. };
  7850. lastValue = destination[scopeName] = parentGet(scope);
  7851. var parentValueWatch = function parentValueWatch(parentValue) {
  7852. if (!compare(parentValue, destination[scopeName])) {
  7853. // we are out of sync and need to copy
  7854. if (!compare(parentValue, lastValue)) {
  7855. // parent changed and it has precedence
  7856. destination[scopeName] = parentValue;
  7857. } else {
  7858. // if the parent can be assigned then do so
  7859. parentSet(scope, parentValue = destination[scopeName]);
  7860. }
  7861. }
  7862. return lastValue = parentValue;
  7863. };
  7864. parentValueWatch.$stateful = true;
  7865. var unwatch;
  7866. if (definition.collection) {
  7867. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7868. } else {
  7869. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7870. }
  7871. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7872. onNewScopeDestroyed.push(unwatch);
  7873. break;
  7874. case '&':
  7875. parentGet = $parse(attrs[attrName]);
  7876. // Don't assign noop to destination if expression is not valid
  7877. if (parentGet === noop && optional) break;
  7878. destination[scopeName] = function(locals) {
  7879. return parentGet(scope, locals);
  7880. };
  7881. break;
  7882. }
  7883. });
  7884. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  7885. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  7886. onNewScopeDestroyed[i]();
  7887. }
  7888. } : noop;
  7889. if (newScope && destroyBindings !== noop) {
  7890. newScope.$on('$destroy', destroyBindings);
  7891. return noop;
  7892. }
  7893. return destroyBindings;
  7894. }
  7895. }];
  7896. }
  7897. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7898. /**
  7899. * Converts all accepted directives format into proper directive name.
  7900. * @param name Name to normalize
  7901. */
  7902. function directiveNormalize(name) {
  7903. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7904. }
  7905. /**
  7906. * @ngdoc type
  7907. * @name $compile.directive.Attributes
  7908. *
  7909. * @description
  7910. * A shared object between directive compile / linking functions which contains normalized DOM
  7911. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7912. * needed since all of these are treated as equivalent in Angular:
  7913. *
  7914. * ```
  7915. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7916. * ```
  7917. */
  7918. /**
  7919. * @ngdoc property
  7920. * @name $compile.directive.Attributes#$attr
  7921. *
  7922. * @description
  7923. * A map of DOM element attribute names to the normalized name. This is
  7924. * needed to do reverse lookup from normalized name back to actual name.
  7925. */
  7926. /**
  7927. * @ngdoc method
  7928. * @name $compile.directive.Attributes#$set
  7929. * @kind function
  7930. *
  7931. * @description
  7932. * Set DOM element attribute value.
  7933. *
  7934. *
  7935. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7936. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7937. * property to the original name.
  7938. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7939. */
  7940. /**
  7941. * Closure compiler type information
  7942. */
  7943. function nodesetLinkingFn(
  7944. /* angular.Scope */ scope,
  7945. /* NodeList */ nodeList,
  7946. /* Element */ rootElement,
  7947. /* function(Function) */ boundTranscludeFn
  7948. ) {}
  7949. function directiveLinkingFn(
  7950. /* nodesetLinkingFn */ nodesetLinkingFn,
  7951. /* angular.Scope */ scope,
  7952. /* Node */ node,
  7953. /* Element */ rootElement,
  7954. /* function(Function) */ boundTranscludeFn
  7955. ) {}
  7956. function tokenDifference(str1, str2) {
  7957. var values = '',
  7958. tokens1 = str1.split(/\s+/),
  7959. tokens2 = str2.split(/\s+/);
  7960. outer:
  7961. for (var i = 0; i < tokens1.length; i++) {
  7962. var token = tokens1[i];
  7963. for (var j = 0; j < tokens2.length; j++) {
  7964. if (token == tokens2[j]) continue outer;
  7965. }
  7966. values += (values.length > 0 ? ' ' : '') + token;
  7967. }
  7968. return values;
  7969. }
  7970. function removeComments(jqNodes) {
  7971. jqNodes = jqLite(jqNodes);
  7972. var i = jqNodes.length;
  7973. if (i <= 1) {
  7974. return jqNodes;
  7975. }
  7976. while (i--) {
  7977. var node = jqNodes[i];
  7978. if (node.nodeType === NODE_TYPE_COMMENT) {
  7979. splice.call(jqNodes, i, 1);
  7980. }
  7981. }
  7982. return jqNodes;
  7983. }
  7984. var $controllerMinErr = minErr('$controller');
  7985. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7986. function identifierForController(controller, ident) {
  7987. if (ident && isString(ident)) return ident;
  7988. if (isString(controller)) {
  7989. var match = CNTRL_REG.exec(controller);
  7990. if (match) return match[3];
  7991. }
  7992. }
  7993. /**
  7994. * @ngdoc provider
  7995. * @name $controllerProvider
  7996. * @description
  7997. * The {@link ng.$controller $controller service} is used by Angular to create new
  7998. * controllers.
  7999. *
  8000. * This provider allows controller registration via the
  8001. * {@link ng.$controllerProvider#register register} method.
  8002. */
  8003. function $ControllerProvider() {
  8004. var controllers = {},
  8005. globals = false;
  8006. /**
  8007. * @ngdoc method
  8008. * @name $controllerProvider#register
  8009. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8010. * the names and the values are the constructors.
  8011. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8012. * annotations in the array notation).
  8013. */
  8014. this.register = function(name, constructor) {
  8015. assertNotHasOwnProperty(name, 'controller');
  8016. if (isObject(name)) {
  8017. extend(controllers, name);
  8018. } else {
  8019. controllers[name] = constructor;
  8020. }
  8021. };
  8022. /**
  8023. * @ngdoc method
  8024. * @name $controllerProvider#allowGlobals
  8025. * @description If called, allows `$controller` to find controller constructors on `window`
  8026. */
  8027. this.allowGlobals = function() {
  8028. globals = true;
  8029. };
  8030. this.$get = ['$injector', '$window', function($injector, $window) {
  8031. /**
  8032. * @ngdoc service
  8033. * @name $controller
  8034. * @requires $injector
  8035. *
  8036. * @param {Function|string} constructor If called with a function then it's considered to be the
  8037. * controller constructor function. Otherwise it's considered to be a string which is used
  8038. * to retrieve the controller constructor using the following steps:
  8039. *
  8040. * * check if a controller with given name is registered via `$controllerProvider`
  8041. * * check if evaluating the string on the current scope returns a constructor
  8042. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8043. * `window` object (not recommended)
  8044. *
  8045. * The string can use the `controller as property` syntax, where the controller instance is published
  8046. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8047. * to work correctly.
  8048. *
  8049. * @param {Object} locals Injection locals for Controller.
  8050. * @return {Object} Instance of given controller.
  8051. *
  8052. * @description
  8053. * `$controller` service is responsible for instantiating controllers.
  8054. *
  8055. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8056. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8057. */
  8058. return function(expression, locals, later, ident) {
  8059. // PRIVATE API:
  8060. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8061. // If true, $controller will allocate the object with the correct
  8062. // prototype chain, but will not invoke the controller until a returned
  8063. // callback is invoked.
  8064. // param `ident` --- An optional label which overrides the label parsed from the controller
  8065. // expression, if any.
  8066. var instance, match, constructor, identifier;
  8067. later = later === true;
  8068. if (ident && isString(ident)) {
  8069. identifier = ident;
  8070. }
  8071. if (isString(expression)) {
  8072. match = expression.match(CNTRL_REG);
  8073. if (!match) {
  8074. throw $controllerMinErr('ctrlfmt',
  8075. "Badly formed controller string '{0}'. " +
  8076. "Must match `__name__ as __id__` or `__name__`.", expression);
  8077. }
  8078. constructor = match[1],
  8079. identifier = identifier || match[3];
  8080. expression = controllers.hasOwnProperty(constructor)
  8081. ? controllers[constructor]
  8082. : getter(locals.$scope, constructor, true) ||
  8083. (globals ? getter($window, constructor, true) : undefined);
  8084. assertArgFn(expression, constructor, true);
  8085. }
  8086. if (later) {
  8087. // Instantiate controller later:
  8088. // This machinery is used to create an instance of the object before calling the
  8089. // controller's constructor itself.
  8090. //
  8091. // This allows properties to be added to the controller before the constructor is
  8092. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8093. //
  8094. // This feature is not intended for use by applications, and is thus not documented
  8095. // publicly.
  8096. // Object creation: http://jsperf.com/create-constructor/2
  8097. var controllerPrototype = (isArray(expression) ?
  8098. expression[expression.length - 1] : expression).prototype;
  8099. instance = Object.create(controllerPrototype || null);
  8100. if (identifier) {
  8101. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8102. }
  8103. var instantiate;
  8104. return instantiate = extend(function() {
  8105. var result = $injector.invoke(expression, instance, locals, constructor);
  8106. if (result !== instance && (isObject(result) || isFunction(result))) {
  8107. instance = result;
  8108. if (identifier) {
  8109. // If result changed, re-assign controllerAs value to scope.
  8110. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8111. }
  8112. }
  8113. return instance;
  8114. }, {
  8115. instance: instance,
  8116. identifier: identifier
  8117. });
  8118. }
  8119. instance = $injector.instantiate(expression, locals, constructor);
  8120. if (identifier) {
  8121. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8122. }
  8123. return instance;
  8124. };
  8125. function addIdentifier(locals, identifier, instance, name) {
  8126. if (!(locals && isObject(locals.$scope))) {
  8127. throw minErr('$controller')('noscp',
  8128. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8129. name, identifier);
  8130. }
  8131. locals.$scope[identifier] = instance;
  8132. }
  8133. }];
  8134. }
  8135. /**
  8136. * @ngdoc service
  8137. * @name $document
  8138. * @requires $window
  8139. *
  8140. * @description
  8141. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8142. *
  8143. * @example
  8144. <example module="documentExample">
  8145. <file name="index.html">
  8146. <div ng-controller="ExampleController">
  8147. <p>$document title: <b ng-bind="title"></b></p>
  8148. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8149. </div>
  8150. </file>
  8151. <file name="script.js">
  8152. angular.module('documentExample', [])
  8153. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8154. $scope.title = $document[0].title;
  8155. $scope.windowTitle = angular.element(window.document)[0].title;
  8156. }]);
  8157. </file>
  8158. </example>
  8159. */
  8160. function $DocumentProvider() {
  8161. this.$get = ['$window', function(window) {
  8162. return jqLite(window.document);
  8163. }];
  8164. }
  8165. /**
  8166. * @ngdoc service
  8167. * @name $exceptionHandler
  8168. * @requires ng.$log
  8169. *
  8170. * @description
  8171. * Any uncaught exception in angular expressions is delegated to this service.
  8172. * The default implementation simply delegates to `$log.error` which logs it into
  8173. * the browser console.
  8174. *
  8175. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8176. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8177. *
  8178. * ## Example:
  8179. *
  8180. * ```js
  8181. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8182. * return function(exception, cause) {
  8183. * exception.message += ' (caused by "' + cause + '")';
  8184. * throw exception;
  8185. * };
  8186. * });
  8187. * ```
  8188. *
  8189. * This example will override the normal action of `$exceptionHandler`, to make angular
  8190. * exceptions fail hard when they happen, instead of just logging to the console.
  8191. *
  8192. * <hr />
  8193. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8194. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8195. * (unless executed during a digest).
  8196. *
  8197. * If you wish, you can manually delegate exceptions, e.g.
  8198. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8199. *
  8200. * @param {Error} exception Exception associated with the error.
  8201. * @param {string=} cause optional information about the context in which
  8202. * the error was thrown.
  8203. *
  8204. */
  8205. function $ExceptionHandlerProvider() {
  8206. this.$get = ['$log', function($log) {
  8207. return function(exception, cause) {
  8208. $log.error.apply($log, arguments);
  8209. };
  8210. }];
  8211. }
  8212. var APPLICATION_JSON = 'application/json';
  8213. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8214. var JSON_START = /^\[|^\{(?!\{)/;
  8215. var JSON_ENDS = {
  8216. '[': /]$/,
  8217. '{': /}$/
  8218. };
  8219. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8220. function serializeValue(v) {
  8221. if (isObject(v)) {
  8222. return isDate(v) ? v.toISOString() : toJson(v);
  8223. }
  8224. return v;
  8225. }
  8226. function $HttpParamSerializerProvider() {
  8227. /**
  8228. * @ngdoc service
  8229. * @name $httpParamSerializer
  8230. * @description
  8231. *
  8232. * Default {@link $http `$http`} params serializer that converts objects to strings
  8233. * according to the following rules:
  8234. *
  8235. * * `{'foo': 'bar'}` results in `foo=bar`
  8236. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8237. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8238. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8239. *
  8240. * Note that serializer will sort the request parameters alphabetically.
  8241. * */
  8242. this.$get = function() {
  8243. return function ngParamSerializer(params) {
  8244. if (!params) return '';
  8245. var parts = [];
  8246. forEachSorted(params, function(value, key) {
  8247. if (value === null || isUndefined(value)) return;
  8248. if (isArray(value)) {
  8249. forEach(value, function(v, k) {
  8250. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8251. });
  8252. } else {
  8253. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8254. }
  8255. });
  8256. return parts.join('&');
  8257. };
  8258. };
  8259. }
  8260. function $HttpParamSerializerJQLikeProvider() {
  8261. /**
  8262. * @ngdoc service
  8263. * @name $httpParamSerializerJQLike
  8264. * @description
  8265. *
  8266. * Alternative {@link $http `$http`} params serializer that follows
  8267. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8268. * The serializer will also sort the params alphabetically.
  8269. *
  8270. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8271. *
  8272. * ```js
  8273. * $http({
  8274. * url: myUrl,
  8275. * method: 'GET',
  8276. * params: myParams,
  8277. * paramSerializer: '$httpParamSerializerJQLike'
  8278. * });
  8279. * ```
  8280. *
  8281. * It is also possible to set it as the default `paramSerializer` in the
  8282. * {@link $httpProvider#defaults `$httpProvider`}.
  8283. *
  8284. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8285. * form data for submission:
  8286. *
  8287. * ```js
  8288. * .controller(function($http, $httpParamSerializerJQLike) {
  8289. * //...
  8290. *
  8291. * $http({
  8292. * url: myUrl,
  8293. * method: 'POST',
  8294. * data: $httpParamSerializerJQLike(myData),
  8295. * headers: {
  8296. * 'Content-Type': 'application/x-www-form-urlencoded'
  8297. * }
  8298. * });
  8299. *
  8300. * });
  8301. * ```
  8302. *
  8303. * */
  8304. this.$get = function() {
  8305. return function jQueryLikeParamSerializer(params) {
  8306. if (!params) return '';
  8307. var parts = [];
  8308. serialize(params, '', true);
  8309. return parts.join('&');
  8310. function serialize(toSerialize, prefix, topLevel) {
  8311. if (toSerialize === null || isUndefined(toSerialize)) return;
  8312. if (isArray(toSerialize)) {
  8313. forEach(toSerialize, function(value) {
  8314. serialize(value, prefix + '[]');
  8315. });
  8316. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8317. forEachSorted(toSerialize, function(value, key) {
  8318. serialize(value, prefix +
  8319. (topLevel ? '' : '[') +
  8320. key +
  8321. (topLevel ? '' : ']'));
  8322. });
  8323. } else {
  8324. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8325. }
  8326. }
  8327. };
  8328. };
  8329. }
  8330. function defaultHttpResponseTransform(data, headers) {
  8331. if (isString(data)) {
  8332. // Strip json vulnerability protection prefix and trim whitespace
  8333. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8334. if (tempData) {
  8335. var contentType = headers('Content-Type');
  8336. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8337. data = fromJson(tempData);
  8338. }
  8339. }
  8340. }
  8341. return data;
  8342. }
  8343. function isJsonLike(str) {
  8344. var jsonStart = str.match(JSON_START);
  8345. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8346. }
  8347. /**
  8348. * Parse headers into key value object
  8349. *
  8350. * @param {string} headers Raw headers as a string
  8351. * @returns {Object} Parsed headers as key value object
  8352. */
  8353. function parseHeaders(headers) {
  8354. var parsed = createMap(), i;
  8355. function fillInParsed(key, val) {
  8356. if (key) {
  8357. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8358. }
  8359. }
  8360. if (isString(headers)) {
  8361. forEach(headers.split('\n'), function(line) {
  8362. i = line.indexOf(':');
  8363. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8364. });
  8365. } else if (isObject(headers)) {
  8366. forEach(headers, function(headerVal, headerKey) {
  8367. fillInParsed(lowercase(headerKey), trim(headerVal));
  8368. });
  8369. }
  8370. return parsed;
  8371. }
  8372. /**
  8373. * Returns a function that provides access to parsed headers.
  8374. *
  8375. * Headers are lazy parsed when first requested.
  8376. * @see parseHeaders
  8377. *
  8378. * @param {(string|Object)} headers Headers to provide access to.
  8379. * @returns {function(string=)} Returns a getter function which if called with:
  8380. *
  8381. * - if called with single an argument returns a single header value or null
  8382. * - if called with no arguments returns an object containing all headers.
  8383. */
  8384. function headersGetter(headers) {
  8385. var headersObj;
  8386. return function(name) {
  8387. if (!headersObj) headersObj = parseHeaders(headers);
  8388. if (name) {
  8389. var value = headersObj[lowercase(name)];
  8390. if (value === void 0) {
  8391. value = null;
  8392. }
  8393. return value;
  8394. }
  8395. return headersObj;
  8396. };
  8397. }
  8398. /**
  8399. * Chain all given functions
  8400. *
  8401. * This function is used for both request and response transforming
  8402. *
  8403. * @param {*} data Data to transform.
  8404. * @param {function(string=)} headers HTTP headers getter fn.
  8405. * @param {number} status HTTP status code of the response.
  8406. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8407. * @returns {*} Transformed data.
  8408. */
  8409. function transformData(data, headers, status, fns) {
  8410. if (isFunction(fns)) {
  8411. return fns(data, headers, status);
  8412. }
  8413. forEach(fns, function(fn) {
  8414. data = fn(data, headers, status);
  8415. });
  8416. return data;
  8417. }
  8418. function isSuccess(status) {
  8419. return 200 <= status && status < 300;
  8420. }
  8421. /**
  8422. * @ngdoc provider
  8423. * @name $httpProvider
  8424. * @description
  8425. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8426. * */
  8427. function $HttpProvider() {
  8428. /**
  8429. * @ngdoc property
  8430. * @name $httpProvider#defaults
  8431. * @description
  8432. *
  8433. * Object containing default values for all {@link ng.$http $http} requests.
  8434. *
  8435. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8436. * that will provide the cache for all requests who set their `cache` property to `true`.
  8437. * If you set the `default.cache = false` then only requests that specify their own custom
  8438. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8439. *
  8440. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8441. * Defaults value is `'XSRF-TOKEN'`.
  8442. *
  8443. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8444. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8445. *
  8446. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8447. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8448. * setting default headers.
  8449. * - **`defaults.headers.common`**
  8450. * - **`defaults.headers.post`**
  8451. * - **`defaults.headers.put`**
  8452. * - **`defaults.headers.patch`**
  8453. *
  8454. *
  8455. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8456. * used to the prepare string representation of request parameters (specified as an object).
  8457. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8458. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8459. *
  8460. **/
  8461. var defaults = this.defaults = {
  8462. // transform incoming response data
  8463. transformResponse: [defaultHttpResponseTransform],
  8464. // transform outgoing request data
  8465. transformRequest: [function(d) {
  8466. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8467. }],
  8468. // default headers
  8469. headers: {
  8470. common: {
  8471. 'Accept': 'application/json, text/plain, */*'
  8472. },
  8473. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8474. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8475. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8476. },
  8477. xsrfCookieName: 'XSRF-TOKEN',
  8478. xsrfHeaderName: 'X-XSRF-TOKEN',
  8479. paramSerializer: '$httpParamSerializer'
  8480. };
  8481. var useApplyAsync = false;
  8482. /**
  8483. * @ngdoc method
  8484. * @name $httpProvider#useApplyAsync
  8485. * @description
  8486. *
  8487. * Configure $http service to combine processing of multiple http responses received at around
  8488. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8489. * significant performance improvement for bigger applications that make many HTTP requests
  8490. * concurrently (common during application bootstrap).
  8491. *
  8492. * Defaults to false. If no value is specified, returns the current configured value.
  8493. *
  8494. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8495. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8496. * to load and share the same digest cycle.
  8497. *
  8498. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8499. * otherwise, returns the current configured value.
  8500. **/
  8501. this.useApplyAsync = function(value) {
  8502. if (isDefined(value)) {
  8503. useApplyAsync = !!value;
  8504. return this;
  8505. }
  8506. return useApplyAsync;
  8507. };
  8508. /**
  8509. * @ngdoc property
  8510. * @name $httpProvider#interceptors
  8511. * @description
  8512. *
  8513. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8514. * pre-processing of request or postprocessing of responses.
  8515. *
  8516. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8517. * array, on request, but reverse order, on response.
  8518. *
  8519. * {@link ng.$http#interceptors Interceptors detailed info}
  8520. **/
  8521. var interceptorFactories = this.interceptors = [];
  8522. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8523. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8524. var defaultCache = $cacheFactory('$http');
  8525. /**
  8526. * Make sure that default param serializer is exposed as a function
  8527. */
  8528. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8529. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8530. /**
  8531. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8532. * The reversal is needed so that we can build up the interception chain around the
  8533. * server request.
  8534. */
  8535. var reversedInterceptors = [];
  8536. forEach(interceptorFactories, function(interceptorFactory) {
  8537. reversedInterceptors.unshift(isString(interceptorFactory)
  8538. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8539. });
  8540. /**
  8541. * @ngdoc service
  8542. * @kind function
  8543. * @name $http
  8544. * @requires ng.$httpBackend
  8545. * @requires $cacheFactory
  8546. * @requires $rootScope
  8547. * @requires $q
  8548. * @requires $injector
  8549. *
  8550. * @description
  8551. * The `$http` service is a core Angular service that facilitates communication with the remote
  8552. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8553. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8554. *
  8555. * For unit testing applications that use `$http` service, see
  8556. * {@link ngMock.$httpBackend $httpBackend mock}.
  8557. *
  8558. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8559. * $resource} service.
  8560. *
  8561. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8562. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8563. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8564. *
  8565. *
  8566. * ## General usage
  8567. * The `$http` service is a function which takes a single argument — a configuration object —
  8568. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  8569. * with two $http specific methods: `success` and `error`.
  8570. *
  8571. * ```js
  8572. * // Simple GET request example :
  8573. * $http.get('/someUrl').
  8574. * success(function(data, status, headers, config) {
  8575. * // this callback will be called asynchronously
  8576. * // when the response is available
  8577. * }).
  8578. * error(function(data, status, headers, config) {
  8579. * // called asynchronously if an error occurs
  8580. * // or server returns response with an error status.
  8581. * });
  8582. * ```
  8583. *
  8584. * ```js
  8585. * // Simple POST request example (passing data) :
  8586. * $http.post('/someUrl', {msg:'hello word!'}).
  8587. * success(function(data, status, headers, config) {
  8588. * // this callback will be called asynchronously
  8589. * // when the response is available
  8590. * }).
  8591. * error(function(data, status, headers, config) {
  8592. * // called asynchronously if an error occurs
  8593. * // or server returns response with an error status.
  8594. * });
  8595. * ```
  8596. *
  8597. *
  8598. * Since the returned value of calling the $http function is a `promise`, you can also use
  8599. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  8600. * an object representing the response. See the API signature and type info below for more
  8601. * details.
  8602. *
  8603. * A response status code between 200 and 299 is considered a success status and
  8604. * will result in the success callback being called. Note that if the response is a redirect,
  8605. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8606. * called for such responses.
  8607. *
  8608. * ## Writing Unit Tests that use $http
  8609. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8610. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8611. * request using trained responses.
  8612. *
  8613. * ```
  8614. * $httpBackend.expectGET(...);
  8615. * $http.get(...);
  8616. * $httpBackend.flush();
  8617. * ```
  8618. *
  8619. * ## Shortcut methods
  8620. *
  8621. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8622. * request data must be passed in for POST/PUT requests.
  8623. *
  8624. * ```js
  8625. * $http.get('/someUrl').success(successCallback);
  8626. * $http.post('/someUrl', data).success(successCallback);
  8627. * ```
  8628. *
  8629. * Complete list of shortcut methods:
  8630. *
  8631. * - {@link ng.$http#get $http.get}
  8632. * - {@link ng.$http#head $http.head}
  8633. * - {@link ng.$http#post $http.post}
  8634. * - {@link ng.$http#put $http.put}
  8635. * - {@link ng.$http#delete $http.delete}
  8636. * - {@link ng.$http#jsonp $http.jsonp}
  8637. * - {@link ng.$http#patch $http.patch}
  8638. *
  8639. *
  8640. * ## Setting HTTP Headers
  8641. *
  8642. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8643. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8644. * object, which currently contains this default configuration:
  8645. *
  8646. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8647. * - `Accept: application/json, text/plain, * / *`
  8648. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8649. * - `Content-Type: application/json`
  8650. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8651. * - `Content-Type: application/json`
  8652. *
  8653. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8654. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8655. * with the lowercased HTTP method name as the key, e.g.
  8656. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8657. *
  8658. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8659. * fashion. For example:
  8660. *
  8661. * ```
  8662. * module.run(function($http) {
  8663. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8664. * });
  8665. * ```
  8666. *
  8667. * In addition, you can supply a `headers` property in the config object passed when
  8668. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8669. *
  8670. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8671. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8672. *
  8673. * ```js
  8674. * var req = {
  8675. * method: 'POST',
  8676. * url: 'http://example.com',
  8677. * headers: {
  8678. * 'Content-Type': undefined
  8679. * },
  8680. * data: { test: 'test' }
  8681. * }
  8682. *
  8683. * $http(req).success(function(){...}).error(function(){...});
  8684. * ```
  8685. *
  8686. * ## Transforming Requests and Responses
  8687. *
  8688. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8689. * and `transformResponse`. These properties can be a single function that returns
  8690. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8691. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8692. *
  8693. * ### Default Transformations
  8694. *
  8695. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8696. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8697. * then these will be applied.
  8698. *
  8699. * You can augment or replace the default transformations by modifying these properties by adding to or
  8700. * replacing the array.
  8701. *
  8702. * Angular provides the following default transformations:
  8703. *
  8704. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8705. *
  8706. * - If the `data` property of the request configuration object contains an object, serialize it
  8707. * into JSON format.
  8708. *
  8709. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8710. *
  8711. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8712. * - If JSON response is detected, deserialize it using a JSON parser.
  8713. *
  8714. *
  8715. * ### Overriding the Default Transformations Per Request
  8716. *
  8717. * If you wish override the request/response transformations only for a single request then provide
  8718. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8719. * into `$http`.
  8720. *
  8721. * Note that if you provide these properties on the config object the default transformations will be
  8722. * overwritten. If you wish to augment the default transformations then you must include them in your
  8723. * local transformation array.
  8724. *
  8725. * The following code demonstrates adding a new response transformation to be run after the default response
  8726. * transformations have been run.
  8727. *
  8728. * ```js
  8729. * function appendTransform(defaults, transform) {
  8730. *
  8731. * // We can't guarantee that the default transformation is an array
  8732. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8733. *
  8734. * // Append the new transformation to the defaults
  8735. * return defaults.concat(transform);
  8736. * }
  8737. *
  8738. * $http({
  8739. * url: '...',
  8740. * method: 'GET',
  8741. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8742. * return doTransform(value);
  8743. * })
  8744. * });
  8745. * ```
  8746. *
  8747. *
  8748. * ## Caching
  8749. *
  8750. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8751. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8752. * When the cache is enabled, `$http` stores the response from the server in the specified
  8753. * cache. The next time the same request is made, the response is served from the cache without
  8754. * sending a request to the server.
  8755. *
  8756. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8757. * the same way that real requests are.
  8758. *
  8759. * If there are multiple GET requests for the same URL that should be cached using the same
  8760. * cache, but the cache is not populated yet, only one request to the server will be made and
  8761. * the remaining requests will be fulfilled using the response from the first request.
  8762. *
  8763. * You can change the default cache to a new object (built with
  8764. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8765. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8766. * their `cache` property to `true` will now use this cache object.
  8767. *
  8768. * If you set the default cache to `false` then only requests that specify their own custom
  8769. * cache object will be cached.
  8770. *
  8771. * ## Interceptors
  8772. *
  8773. * Before you start creating interceptors, be sure to understand the
  8774. * {@link ng.$q $q and deferred/promise APIs}.
  8775. *
  8776. * For purposes of global error handling, authentication, or any kind of synchronous or
  8777. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8778. * able to intercept requests before they are handed to the server and
  8779. * responses before they are handed over to the application code that
  8780. * initiated these requests. The interceptors leverage the {@link ng.$q
  8781. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8782. *
  8783. * The interceptors are service factories that are registered with the `$httpProvider` by
  8784. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8785. * injected with dependencies (if specified) and returns the interceptor.
  8786. *
  8787. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8788. *
  8789. * * `request`: interceptors get called with a http `config` object. The function is free to
  8790. * modify the `config` object or create a new one. The function needs to return the `config`
  8791. * object directly, or a promise containing the `config` or a new `config` object.
  8792. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8793. * resolved with a rejection.
  8794. * * `response`: interceptors get called with http `response` object. The function is free to
  8795. * modify the `response` object or create a new one. The function needs to return the `response`
  8796. * object directly, or as a promise containing the `response` or a new `response` object.
  8797. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8798. * resolved with a rejection.
  8799. *
  8800. *
  8801. * ```js
  8802. * // register the interceptor as a service
  8803. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8804. * return {
  8805. * // optional method
  8806. * 'request': function(config) {
  8807. * // do something on success
  8808. * return config;
  8809. * },
  8810. *
  8811. * // optional method
  8812. * 'requestError': function(rejection) {
  8813. * // do something on error
  8814. * if (canRecover(rejection)) {
  8815. * return responseOrNewPromise
  8816. * }
  8817. * return $q.reject(rejection);
  8818. * },
  8819. *
  8820. *
  8821. *
  8822. * // optional method
  8823. * 'response': function(response) {
  8824. * // do something on success
  8825. * return response;
  8826. * },
  8827. *
  8828. * // optional method
  8829. * 'responseError': function(rejection) {
  8830. * // do something on error
  8831. * if (canRecover(rejection)) {
  8832. * return responseOrNewPromise
  8833. * }
  8834. * return $q.reject(rejection);
  8835. * }
  8836. * };
  8837. * });
  8838. *
  8839. * $httpProvider.interceptors.push('myHttpInterceptor');
  8840. *
  8841. *
  8842. * // alternatively, register the interceptor via an anonymous factory
  8843. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8844. * return {
  8845. * 'request': function(config) {
  8846. * // same as above
  8847. * },
  8848. *
  8849. * 'response': function(response) {
  8850. * // same as above
  8851. * }
  8852. * };
  8853. * });
  8854. * ```
  8855. *
  8856. * ## Security Considerations
  8857. *
  8858. * When designing web applications, consider security threats from:
  8859. *
  8860. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8861. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8862. *
  8863. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8864. * pre-configured with strategies that address these issues, but for this to work backend server
  8865. * cooperation is required.
  8866. *
  8867. * ### JSON Vulnerability Protection
  8868. *
  8869. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8870. * allows third party website to turn your JSON resource URL into
  8871. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8872. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8873. * Angular will automatically strip the prefix before processing it as JSON.
  8874. *
  8875. * For example if your server needs to return:
  8876. * ```js
  8877. * ['one','two']
  8878. * ```
  8879. *
  8880. * which is vulnerable to attack, your server can return:
  8881. * ```js
  8882. * )]}',
  8883. * ['one','two']
  8884. * ```
  8885. *
  8886. * Angular will strip the prefix, before processing the JSON.
  8887. *
  8888. *
  8889. * ### Cross Site Request Forgery (XSRF) Protection
  8890. *
  8891. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8892. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8893. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8894. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8895. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8896. * the XHR came from JavaScript running on your domain. The header will not be set for
  8897. * cross-domain requests.
  8898. *
  8899. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8900. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8901. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8902. * that only JavaScript running on your domain could have sent the request. The token must be
  8903. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8904. * making up its own tokens). We recommend that the token is a digest of your site's
  8905. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8906. * for added security.
  8907. *
  8908. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8909. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8910. * or the per-request config object.
  8911. *
  8912. * In order to prevent collisions in environments where multiple Angular apps share the
  8913. * same domain or subdomain, we recommend that each application uses unique cookie name.
  8914. *
  8915. *
  8916. * @param {object} config Object describing the request to be made and how it should be
  8917. * processed. The object has following properties:
  8918. *
  8919. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8920. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8921. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  8922. * with the `paramSerializer` and appended as GET parameters.
  8923. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8924. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8925. * HTTP headers to send to the server. If the return value of a function is null, the
  8926. * header will not be sent. Functions accept a config object as an argument.
  8927. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8928. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8929. * - **transformRequest** –
  8930. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8931. * transform function or an array of such functions. The transform function takes the http
  8932. * request body and headers and returns its transformed (typically serialized) version.
  8933. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8934. * Overriding the Default Transformations}
  8935. * - **transformResponse** –
  8936. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8937. * transform function or an array of such functions. The transform function takes the http
  8938. * response body, headers and status and returns its transformed (typically deserialized) version.
  8939. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8940. * Overriding the Default TransformationjqLiks}
  8941. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  8942. * prepare the string representation of request parameters (specified as an object).
  8943. * If specified as string, it is interpreted as function registered with the
  8944. * {@link $injector $injector}, which means you can create your own serializer
  8945. * by registering it as a {@link auto.$provide#service service}.
  8946. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  8947. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  8948. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8949. * GET request, otherwise if a cache instance built with
  8950. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8951. * caching.
  8952. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8953. * that should abort the request when resolved.
  8954. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8955. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8956. * for more information.
  8957. * - **responseType** - `{string}` - see
  8958. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8959. *
  8960. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8961. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8962. * method takes two arguments a success and an error callback which will be called with a
  8963. * response object. The `success` and `error` methods take a single argument - a function that
  8964. * will be called when the request succeeds or fails respectively. The arguments passed into
  8965. * these functions are destructured representation of the response object passed into the
  8966. * `then` method. The response object has these properties:
  8967. *
  8968. * - **data** – `{string|Object}` – The response body transformed with the transform
  8969. * functions.
  8970. * - **status** – `{number}` – HTTP status code of the response.
  8971. * - **headers** – `{function([headerName])}` – Header getter function.
  8972. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8973. * - **statusText** – `{string}` – HTTP status text of the response.
  8974. *
  8975. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8976. * requests. This is primarily meant to be used for debugging purposes.
  8977. *
  8978. *
  8979. * @example
  8980. <example module="httpExample">
  8981. <file name="index.html">
  8982. <div ng-controller="FetchController">
  8983. <select ng-model="method" aria-label="Request method">
  8984. <option>GET</option>
  8985. <option>JSONP</option>
  8986. </select>
  8987. <input type="text" ng-model="url" size="80" aria-label="URL" />
  8988. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8989. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8990. <button id="samplejsonpbtn"
  8991. ng-click="updateModel('JSONP',
  8992. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8993. Sample JSONP
  8994. </button>
  8995. <button id="invalidjsonpbtn"
  8996. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8997. Invalid JSONP
  8998. </button>
  8999. <pre>http status code: {{status}}</pre>
  9000. <pre>http response data: {{data}}</pre>
  9001. </div>
  9002. </file>
  9003. <file name="script.js">
  9004. angular.module('httpExample', [])
  9005. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9006. function($scope, $http, $templateCache) {
  9007. $scope.method = 'GET';
  9008. $scope.url = 'http-hello.html';
  9009. $scope.fetch = function() {
  9010. $scope.code = null;
  9011. $scope.response = null;
  9012. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9013. success(function(data, status) {
  9014. $scope.status = status;
  9015. $scope.data = data;
  9016. }).
  9017. error(function(data, status) {
  9018. $scope.data = data || "Request failed";
  9019. $scope.status = status;
  9020. });
  9021. };
  9022. $scope.updateModel = function(method, url) {
  9023. $scope.method = method;
  9024. $scope.url = url;
  9025. };
  9026. }]);
  9027. </file>
  9028. <file name="http-hello.html">
  9029. Hello, $http!
  9030. </file>
  9031. <file name="protractor.js" type="protractor">
  9032. var status = element(by.binding('status'));
  9033. var data = element(by.binding('data'));
  9034. var fetchBtn = element(by.id('fetchbtn'));
  9035. var sampleGetBtn = element(by.id('samplegetbtn'));
  9036. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9037. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9038. it('should make an xhr GET request', function() {
  9039. sampleGetBtn.click();
  9040. fetchBtn.click();
  9041. expect(status.getText()).toMatch('200');
  9042. expect(data.getText()).toMatch(/Hello, \$http!/);
  9043. });
  9044. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9045. // it('should make a JSONP request to angularjs.org', function() {
  9046. // sampleJsonpBtn.click();
  9047. // fetchBtn.click();
  9048. // expect(status.getText()).toMatch('200');
  9049. // expect(data.getText()).toMatch(/Super Hero!/);
  9050. // });
  9051. it('should make JSONP request to invalid URL and invoke the error handler',
  9052. function() {
  9053. invalidJsonpBtn.click();
  9054. fetchBtn.click();
  9055. expect(status.getText()).toMatch('0');
  9056. expect(data.getText()).toMatch('Request failed');
  9057. });
  9058. </file>
  9059. </example>
  9060. */
  9061. function $http(requestConfig) {
  9062. if (!angular.isObject(requestConfig)) {
  9063. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9064. }
  9065. var config = extend({
  9066. method: 'get',
  9067. transformRequest: defaults.transformRequest,
  9068. transformResponse: defaults.transformResponse,
  9069. paramSerializer: defaults.paramSerializer
  9070. }, requestConfig);
  9071. config.headers = mergeHeaders(requestConfig);
  9072. config.method = uppercase(config.method);
  9073. config.paramSerializer = isString(config.paramSerializer) ?
  9074. $injector.get(config.paramSerializer) : config.paramSerializer;
  9075. var serverRequest = function(config) {
  9076. var headers = config.headers;
  9077. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9078. // strip content-type if data is undefined
  9079. if (isUndefined(reqData)) {
  9080. forEach(headers, function(value, header) {
  9081. if (lowercase(header) === 'content-type') {
  9082. delete headers[header];
  9083. }
  9084. });
  9085. }
  9086. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9087. config.withCredentials = defaults.withCredentials;
  9088. }
  9089. // send request
  9090. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9091. };
  9092. var chain = [serverRequest, undefined];
  9093. var promise = $q.when(config);
  9094. // apply interceptors
  9095. forEach(reversedInterceptors, function(interceptor) {
  9096. if (interceptor.request || interceptor.requestError) {
  9097. chain.unshift(interceptor.request, interceptor.requestError);
  9098. }
  9099. if (interceptor.response || interceptor.responseError) {
  9100. chain.push(interceptor.response, interceptor.responseError);
  9101. }
  9102. });
  9103. while (chain.length) {
  9104. var thenFn = chain.shift();
  9105. var rejectFn = chain.shift();
  9106. promise = promise.then(thenFn, rejectFn);
  9107. }
  9108. promise.success = function(fn) {
  9109. assertArgFn(fn, 'fn');
  9110. promise.then(function(response) {
  9111. fn(response.data, response.status, response.headers, config);
  9112. });
  9113. return promise;
  9114. };
  9115. promise.error = function(fn) {
  9116. assertArgFn(fn, 'fn');
  9117. promise.then(null, function(response) {
  9118. fn(response.data, response.status, response.headers, config);
  9119. });
  9120. return promise;
  9121. };
  9122. return promise;
  9123. function transformResponse(response) {
  9124. // make a copy since the response must be cacheable
  9125. var resp = extend({}, response);
  9126. if (!response.data) {
  9127. resp.data = response.data;
  9128. } else {
  9129. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9130. }
  9131. return (isSuccess(response.status))
  9132. ? resp
  9133. : $q.reject(resp);
  9134. }
  9135. function executeHeaderFns(headers, config) {
  9136. var headerContent, processedHeaders = {};
  9137. forEach(headers, function(headerFn, header) {
  9138. if (isFunction(headerFn)) {
  9139. headerContent = headerFn(config);
  9140. if (headerContent != null) {
  9141. processedHeaders[header] = headerContent;
  9142. }
  9143. } else {
  9144. processedHeaders[header] = headerFn;
  9145. }
  9146. });
  9147. return processedHeaders;
  9148. }
  9149. function mergeHeaders(config) {
  9150. var defHeaders = defaults.headers,
  9151. reqHeaders = extend({}, config.headers),
  9152. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9153. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9154. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9155. defaultHeadersIteration:
  9156. for (defHeaderName in defHeaders) {
  9157. lowercaseDefHeaderName = lowercase(defHeaderName);
  9158. for (reqHeaderName in reqHeaders) {
  9159. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9160. continue defaultHeadersIteration;
  9161. }
  9162. }
  9163. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9164. }
  9165. // execute if header value is a function for merged headers
  9166. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9167. }
  9168. }
  9169. $http.pendingRequests = [];
  9170. /**
  9171. * @ngdoc method
  9172. * @name $http#get
  9173. *
  9174. * @description
  9175. * Shortcut method to perform `GET` request.
  9176. *
  9177. * @param {string} url Relative or absolute URL specifying the destination of the request
  9178. * @param {Object=} config Optional configuration object
  9179. * @returns {HttpPromise} Future object
  9180. */
  9181. /**
  9182. * @ngdoc method
  9183. * @name $http#delete
  9184. *
  9185. * @description
  9186. * Shortcut method to perform `DELETE` request.
  9187. *
  9188. * @param {string} url Relative or absolute URL specifying the destination of the request
  9189. * @param {Object=} config Optional configuration object
  9190. * @returns {HttpPromise} Future object
  9191. */
  9192. /**
  9193. * @ngdoc method
  9194. * @name $http#head
  9195. *
  9196. * @description
  9197. * Shortcut method to perform `HEAD` request.
  9198. *
  9199. * @param {string} url Relative or absolute URL specifying the destination of the request
  9200. * @param {Object=} config Optional configuration object
  9201. * @returns {HttpPromise} Future object
  9202. */
  9203. /**
  9204. * @ngdoc method
  9205. * @name $http#jsonp
  9206. *
  9207. * @description
  9208. * Shortcut method to perform `JSONP` request.
  9209. *
  9210. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9211. * The name of the callback should be the string `JSON_CALLBACK`.
  9212. * @param {Object=} config Optional configuration object
  9213. * @returns {HttpPromise} Future object
  9214. */
  9215. createShortMethods('get', 'delete', 'head', 'jsonp');
  9216. /**
  9217. * @ngdoc method
  9218. * @name $http#post
  9219. *
  9220. * @description
  9221. * Shortcut method to perform `POST` request.
  9222. *
  9223. * @param {string} url Relative or absolute URL specifying the destination of the request
  9224. * @param {*} data Request content
  9225. * @param {Object=} config Optional configuration object
  9226. * @returns {HttpPromise} Future object
  9227. */
  9228. /**
  9229. * @ngdoc method
  9230. * @name $http#put
  9231. *
  9232. * @description
  9233. * Shortcut method to perform `PUT` request.
  9234. *
  9235. * @param {string} url Relative or absolute URL specifying the destination of the request
  9236. * @param {*} data Request content
  9237. * @param {Object=} config Optional configuration object
  9238. * @returns {HttpPromise} Future object
  9239. */
  9240. /**
  9241. * @ngdoc method
  9242. * @name $http#patch
  9243. *
  9244. * @description
  9245. * Shortcut method to perform `PATCH` request.
  9246. *
  9247. * @param {string} url Relative or absolute URL specifying the destination of the request
  9248. * @param {*} data Request content
  9249. * @param {Object=} config Optional configuration object
  9250. * @returns {HttpPromise} Future object
  9251. */
  9252. createShortMethodsWithData('post', 'put', 'patch');
  9253. /**
  9254. * @ngdoc property
  9255. * @name $http#defaults
  9256. *
  9257. * @description
  9258. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9259. * default headers, withCredentials as well as request and response transformations.
  9260. *
  9261. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9262. */
  9263. $http.defaults = defaults;
  9264. return $http;
  9265. function createShortMethods(names) {
  9266. forEach(arguments, function(name) {
  9267. $http[name] = function(url, config) {
  9268. return $http(extend({}, config || {}, {
  9269. method: name,
  9270. url: url
  9271. }));
  9272. };
  9273. });
  9274. }
  9275. function createShortMethodsWithData(name) {
  9276. forEach(arguments, function(name) {
  9277. $http[name] = function(url, data, config) {
  9278. return $http(extend({}, config || {}, {
  9279. method: name,
  9280. url: url,
  9281. data: data
  9282. }));
  9283. };
  9284. });
  9285. }
  9286. /**
  9287. * Makes the request.
  9288. *
  9289. * !!! ACCESSES CLOSURE VARS:
  9290. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9291. */
  9292. function sendReq(config, reqData) {
  9293. var deferred = $q.defer(),
  9294. promise = deferred.promise,
  9295. cache,
  9296. cachedResp,
  9297. reqHeaders = config.headers,
  9298. url = buildUrl(config.url, config.paramSerializer(config.params));
  9299. $http.pendingRequests.push(config);
  9300. promise.then(removePendingReq, removePendingReq);
  9301. if ((config.cache || defaults.cache) && config.cache !== false &&
  9302. (config.method === 'GET' || config.method === 'JSONP')) {
  9303. cache = isObject(config.cache) ? config.cache
  9304. : isObject(defaults.cache) ? defaults.cache
  9305. : defaultCache;
  9306. }
  9307. if (cache) {
  9308. cachedResp = cache.get(url);
  9309. if (isDefined(cachedResp)) {
  9310. if (isPromiseLike(cachedResp)) {
  9311. // cached request has already been sent, but there is no response yet
  9312. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9313. } else {
  9314. // serving from cache
  9315. if (isArray(cachedResp)) {
  9316. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9317. } else {
  9318. resolvePromise(cachedResp, 200, {}, 'OK');
  9319. }
  9320. }
  9321. } else {
  9322. // put the promise for the non-transformed response into cache as a placeholder
  9323. cache.put(url, promise);
  9324. }
  9325. }
  9326. // if we won't have the response in cache, set the xsrf headers and
  9327. // send the request to the backend
  9328. if (isUndefined(cachedResp)) {
  9329. var xsrfValue = urlIsSameOrigin(config.url)
  9330. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9331. : undefined;
  9332. if (xsrfValue) {
  9333. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9334. }
  9335. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9336. config.withCredentials, config.responseType);
  9337. }
  9338. return promise;
  9339. /**
  9340. * Callback registered to $httpBackend():
  9341. * - caches the response if desired
  9342. * - resolves the raw $http promise
  9343. * - calls $apply
  9344. */
  9345. function done(status, response, headersString, statusText) {
  9346. if (cache) {
  9347. if (isSuccess(status)) {
  9348. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9349. } else {
  9350. // remove promise from the cache
  9351. cache.remove(url);
  9352. }
  9353. }
  9354. function resolveHttpPromise() {
  9355. resolvePromise(response, status, headersString, statusText);
  9356. }
  9357. if (useApplyAsync) {
  9358. $rootScope.$applyAsync(resolveHttpPromise);
  9359. } else {
  9360. resolveHttpPromise();
  9361. if (!$rootScope.$$phase) $rootScope.$apply();
  9362. }
  9363. }
  9364. /**
  9365. * Resolves the raw $http promise.
  9366. */
  9367. function resolvePromise(response, status, headers, statusText) {
  9368. // normalize internal statuses to 0
  9369. status = Math.max(status, 0);
  9370. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9371. data: response,
  9372. status: status,
  9373. headers: headersGetter(headers),
  9374. config: config,
  9375. statusText: statusText
  9376. });
  9377. }
  9378. function resolvePromiseWithResult(result) {
  9379. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9380. }
  9381. function removePendingReq() {
  9382. var idx = $http.pendingRequests.indexOf(config);
  9383. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9384. }
  9385. }
  9386. function buildUrl(url, serializedParams) {
  9387. if (serializedParams.length > 0) {
  9388. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9389. }
  9390. return url;
  9391. }
  9392. }];
  9393. }
  9394. function createXhr() {
  9395. return new window.XMLHttpRequest();
  9396. }
  9397. /**
  9398. * @ngdoc service
  9399. * @name $httpBackend
  9400. * @requires $window
  9401. * @requires $document
  9402. *
  9403. * @description
  9404. * HTTP backend used by the {@link ng.$http service} that delegates to
  9405. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9406. *
  9407. * You should never need to use this service directly, instead use the higher-level abstractions:
  9408. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9409. *
  9410. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9411. * $httpBackend} which can be trained with responses.
  9412. */
  9413. function $HttpBackendProvider() {
  9414. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9415. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9416. }];
  9417. }
  9418. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9419. // TODO(vojta): fix the signature
  9420. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9421. $browser.$$incOutstandingRequestCount();
  9422. url = url || $browser.url();
  9423. if (lowercase(method) == 'jsonp') {
  9424. var callbackId = '_' + (callbacks.counter++).toString(36);
  9425. callbacks[callbackId] = function(data) {
  9426. callbacks[callbackId].data = data;
  9427. callbacks[callbackId].called = true;
  9428. };
  9429. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9430. callbackId, function(status, text) {
  9431. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9432. callbacks[callbackId] = noop;
  9433. });
  9434. } else {
  9435. var xhr = createXhr();
  9436. xhr.open(method, url, true);
  9437. forEach(headers, function(value, key) {
  9438. if (isDefined(value)) {
  9439. xhr.setRequestHeader(key, value);
  9440. }
  9441. });
  9442. xhr.onload = function requestLoaded() {
  9443. var statusText = xhr.statusText || '';
  9444. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  9445. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9446. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9447. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9448. var status = xhr.status === 1223 ? 204 : xhr.status;
  9449. // fix status code when it is 0 (0 status is undocumented).
  9450. // Occurs when accessing file resources or on Android 4.1 stock browser
  9451. // while retrieving files from application cache.
  9452. if (status === 0) {
  9453. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9454. }
  9455. completeRequest(callback,
  9456. status,
  9457. response,
  9458. xhr.getAllResponseHeaders(),
  9459. statusText);
  9460. };
  9461. var requestError = function() {
  9462. // The response is always empty
  9463. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9464. completeRequest(callback, -1, null, null, '');
  9465. };
  9466. xhr.onerror = requestError;
  9467. xhr.onabort = requestError;
  9468. if (withCredentials) {
  9469. xhr.withCredentials = true;
  9470. }
  9471. if (responseType) {
  9472. try {
  9473. xhr.responseType = responseType;
  9474. } catch (e) {
  9475. // WebKit added support for the json responseType value on 09/03/2013
  9476. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9477. // known to throw when setting the value "json" as the response type. Other older
  9478. // browsers implementing the responseType
  9479. //
  9480. // The json response type can be ignored if not supported, because JSON payloads are
  9481. // parsed on the client-side regardless.
  9482. if (responseType !== 'json') {
  9483. throw e;
  9484. }
  9485. }
  9486. }
  9487. xhr.send(post);
  9488. }
  9489. if (timeout > 0) {
  9490. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9491. } else if (isPromiseLike(timeout)) {
  9492. timeout.then(timeoutRequest);
  9493. }
  9494. function timeoutRequest() {
  9495. jsonpDone && jsonpDone();
  9496. xhr && xhr.abort();
  9497. }
  9498. function completeRequest(callback, status, response, headersString, statusText) {
  9499. // cancel timeout and subsequent timeout promise resolution
  9500. if (timeoutId !== undefined) {
  9501. $browserDefer.cancel(timeoutId);
  9502. }
  9503. jsonpDone = xhr = null;
  9504. callback(status, response, headersString, statusText);
  9505. $browser.$$completeOutstandingRequest(noop);
  9506. }
  9507. };
  9508. function jsonpReq(url, callbackId, done) {
  9509. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9510. // - fetches local scripts via XHR and evals them
  9511. // - adds and immediately removes script elements from the document
  9512. var script = rawDocument.createElement('script'), callback = null;
  9513. script.type = "text/javascript";
  9514. script.src = url;
  9515. script.async = true;
  9516. callback = function(event) {
  9517. removeEventListenerFn(script, "load", callback);
  9518. removeEventListenerFn(script, "error", callback);
  9519. rawDocument.body.removeChild(script);
  9520. script = null;
  9521. var status = -1;
  9522. var text = "unknown";
  9523. if (event) {
  9524. if (event.type === "load" && !callbacks[callbackId].called) {
  9525. event = { type: "error" };
  9526. }
  9527. text = event.type;
  9528. status = event.type === "error" ? 404 : 200;
  9529. }
  9530. if (done) {
  9531. done(status, text);
  9532. }
  9533. };
  9534. addEventListenerFn(script, "load", callback);
  9535. addEventListenerFn(script, "error", callback);
  9536. rawDocument.body.appendChild(script);
  9537. return callback;
  9538. }
  9539. }
  9540. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9541. $interpolateMinErr.throwNoconcat = function(text) {
  9542. throw $interpolateMinErr('noconcat',
  9543. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9544. "interpolations that concatenate multiple expressions when a trusted value is " +
  9545. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9546. };
  9547. $interpolateMinErr.interr = function(text, err) {
  9548. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9549. };
  9550. /**
  9551. * @ngdoc provider
  9552. * @name $interpolateProvider
  9553. *
  9554. * @description
  9555. *
  9556. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9557. *
  9558. * @example
  9559. <example module="customInterpolationApp">
  9560. <file name="index.html">
  9561. <script>
  9562. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9563. customInterpolationApp.config(function($interpolateProvider) {
  9564. $interpolateProvider.startSymbol('//');
  9565. $interpolateProvider.endSymbol('//');
  9566. });
  9567. customInterpolationApp.controller('DemoController', function() {
  9568. this.label = "This binding is brought you by // interpolation symbols.";
  9569. });
  9570. </script>
  9571. <div ng-app="App" ng-controller="DemoController as demo">
  9572. //demo.label//
  9573. </div>
  9574. </file>
  9575. <file name="protractor.js" type="protractor">
  9576. it('should interpolate binding with custom symbols', function() {
  9577. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9578. });
  9579. </file>
  9580. </example>
  9581. */
  9582. function $InterpolateProvider() {
  9583. var startSymbol = '{{';
  9584. var endSymbol = '}}';
  9585. /**
  9586. * @ngdoc method
  9587. * @name $interpolateProvider#startSymbol
  9588. * @description
  9589. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9590. *
  9591. * @param {string=} value new value to set the starting symbol to.
  9592. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9593. */
  9594. this.startSymbol = function(value) {
  9595. if (value) {
  9596. startSymbol = value;
  9597. return this;
  9598. } else {
  9599. return startSymbol;
  9600. }
  9601. };
  9602. /**
  9603. * @ngdoc method
  9604. * @name $interpolateProvider#endSymbol
  9605. * @description
  9606. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9607. *
  9608. * @param {string=} value new value to set the ending symbol to.
  9609. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9610. */
  9611. this.endSymbol = function(value) {
  9612. if (value) {
  9613. endSymbol = value;
  9614. return this;
  9615. } else {
  9616. return endSymbol;
  9617. }
  9618. };
  9619. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9620. var startSymbolLength = startSymbol.length,
  9621. endSymbolLength = endSymbol.length,
  9622. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9623. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9624. function escape(ch) {
  9625. return '\\\\\\' + ch;
  9626. }
  9627. function unescapeText(text) {
  9628. return text.replace(escapedStartRegexp, startSymbol).
  9629. replace(escapedEndRegexp, endSymbol);
  9630. }
  9631. function stringify(value) {
  9632. if (value == null) { // null || undefined
  9633. return '';
  9634. }
  9635. switch (typeof value) {
  9636. case 'string':
  9637. break;
  9638. case 'number':
  9639. value = '' + value;
  9640. break;
  9641. default:
  9642. value = toJson(value);
  9643. }
  9644. return value;
  9645. }
  9646. /**
  9647. * @ngdoc service
  9648. * @name $interpolate
  9649. * @kind function
  9650. *
  9651. * @requires $parse
  9652. * @requires $sce
  9653. *
  9654. * @description
  9655. *
  9656. * Compiles a string with markup into an interpolation function. This service is used by the
  9657. * HTML {@link ng.$compile $compile} service for data binding. See
  9658. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9659. * interpolation markup.
  9660. *
  9661. *
  9662. * ```js
  9663. * var $interpolate = ...; // injected
  9664. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9665. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9666. * ```
  9667. *
  9668. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9669. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9670. * evaluate to a value other than `undefined`.
  9671. *
  9672. * ```js
  9673. * var $interpolate = ...; // injected
  9674. * var context = {greeting: 'Hello', name: undefined };
  9675. *
  9676. * // default "forgiving" mode
  9677. * var exp = $interpolate('{{greeting}} {{name}}!');
  9678. * expect(exp(context)).toEqual('Hello !');
  9679. *
  9680. * // "allOrNothing" mode
  9681. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9682. * expect(exp(context)).toBeUndefined();
  9683. * context.name = 'Angular';
  9684. * expect(exp(context)).toEqual('Hello Angular!');
  9685. * ```
  9686. *
  9687. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9688. *
  9689. * ####Escaped Interpolation
  9690. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9691. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9692. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9693. * or binding.
  9694. *
  9695. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9696. * degree, while also enabling code examples to work without relying on the
  9697. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9698. *
  9699. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9700. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9701. * interpolation start/end markers with their escaped counterparts.**
  9702. *
  9703. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9704. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9705. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9706. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9707. * this is typically useful only when user-data is used in rendering a template from the server, or
  9708. * when otherwise untrusted data is used by a directive.
  9709. *
  9710. * <example>
  9711. * <file name="index.html">
  9712. * <div ng-init="username='A user'">
  9713. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9714. * </p>
  9715. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9716. * application, but fails to accomplish their task, because the server has correctly
  9717. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9718. * characters.</p>
  9719. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9720. * from the database by an administrator.</p>
  9721. * </div>
  9722. * </file>
  9723. * </example>
  9724. *
  9725. * @param {string} text The text with markup to interpolate.
  9726. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9727. * embedded expression in order to return an interpolation function. Strings with no
  9728. * embedded expression will return null for the interpolation function.
  9729. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9730. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9731. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9732. * provides Strict Contextual Escaping for details.
  9733. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9734. * unless all embedded expressions evaluate to a value other than `undefined`.
  9735. * @returns {function(context)} an interpolation function which is used to compute the
  9736. * interpolated string. The function has these parameters:
  9737. *
  9738. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9739. */
  9740. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9741. allOrNothing = !!allOrNothing;
  9742. var startIndex,
  9743. endIndex,
  9744. index = 0,
  9745. expressions = [],
  9746. parseFns = [],
  9747. textLength = text.length,
  9748. exp,
  9749. concat = [],
  9750. expressionPositions = [];
  9751. while (index < textLength) {
  9752. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9753. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9754. if (index !== startIndex) {
  9755. concat.push(unescapeText(text.substring(index, startIndex)));
  9756. }
  9757. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9758. expressions.push(exp);
  9759. parseFns.push($parse(exp, parseStringifyInterceptor));
  9760. index = endIndex + endSymbolLength;
  9761. expressionPositions.push(concat.length);
  9762. concat.push('');
  9763. } else {
  9764. // we did not find an interpolation, so we have to add the remainder to the separators array
  9765. if (index !== textLength) {
  9766. concat.push(unescapeText(text.substring(index)));
  9767. }
  9768. break;
  9769. }
  9770. }
  9771. // Concatenating expressions makes it hard to reason about whether some combination of
  9772. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9773. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9774. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9775. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9776. // the load when auditing for XSS issues.
  9777. if (trustedContext && concat.length > 1) {
  9778. $interpolateMinErr.throwNoconcat(text);
  9779. }
  9780. if (!mustHaveExpression || expressions.length) {
  9781. var compute = function(values) {
  9782. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9783. if (allOrNothing && isUndefined(values[i])) return;
  9784. concat[expressionPositions[i]] = values[i];
  9785. }
  9786. return concat.join('');
  9787. };
  9788. var getValue = function(value) {
  9789. return trustedContext ?
  9790. $sce.getTrusted(trustedContext, value) :
  9791. $sce.valueOf(value);
  9792. };
  9793. return extend(function interpolationFn(context) {
  9794. var i = 0;
  9795. var ii = expressions.length;
  9796. var values = new Array(ii);
  9797. try {
  9798. for (; i < ii; i++) {
  9799. values[i] = parseFns[i](context);
  9800. }
  9801. return compute(values);
  9802. } catch (err) {
  9803. $exceptionHandler($interpolateMinErr.interr(text, err));
  9804. }
  9805. }, {
  9806. // all of these properties are undocumented for now
  9807. exp: text, //just for compatibility with regular watchers created via $watch
  9808. expressions: expressions,
  9809. $$watchDelegate: function(scope, listener) {
  9810. var lastValue;
  9811. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9812. var currValue = compute(values);
  9813. if (isFunction(listener)) {
  9814. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9815. }
  9816. lastValue = currValue;
  9817. });
  9818. }
  9819. });
  9820. }
  9821. function parseStringifyInterceptor(value) {
  9822. try {
  9823. value = getValue(value);
  9824. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9825. } catch (err) {
  9826. $exceptionHandler($interpolateMinErr.interr(text, err));
  9827. }
  9828. }
  9829. }
  9830. /**
  9831. * @ngdoc method
  9832. * @name $interpolate#startSymbol
  9833. * @description
  9834. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9835. *
  9836. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9837. * the symbol.
  9838. *
  9839. * @returns {string} start symbol.
  9840. */
  9841. $interpolate.startSymbol = function() {
  9842. return startSymbol;
  9843. };
  9844. /**
  9845. * @ngdoc method
  9846. * @name $interpolate#endSymbol
  9847. * @description
  9848. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9849. *
  9850. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9851. * the symbol.
  9852. *
  9853. * @returns {string} end symbol.
  9854. */
  9855. $interpolate.endSymbol = function() {
  9856. return endSymbol;
  9857. };
  9858. return $interpolate;
  9859. }];
  9860. }
  9861. function $IntervalProvider() {
  9862. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9863. function($rootScope, $window, $q, $$q) {
  9864. var intervals = {};
  9865. /**
  9866. * @ngdoc service
  9867. * @name $interval
  9868. *
  9869. * @description
  9870. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9871. * milliseconds.
  9872. *
  9873. * The return value of registering an interval function is a promise. This promise will be
  9874. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9875. * run indefinitely if `count` is not defined. The value of the notification will be the
  9876. * number of iterations that have run.
  9877. * To cancel an interval, call `$interval.cancel(promise)`.
  9878. *
  9879. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9880. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9881. * time.
  9882. *
  9883. * <div class="alert alert-warning">
  9884. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9885. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9886. * directive's element are destroyed.
  9887. * You should take this into consideration and make sure to always cancel the interval at the
  9888. * appropriate moment. See the example below for more details on how and when to do this.
  9889. * </div>
  9890. *
  9891. * @param {function()} fn A function that should be called repeatedly.
  9892. * @param {number} delay Number of milliseconds between each function call.
  9893. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9894. * indefinitely.
  9895. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9896. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9897. * @param {...*=} Pass additional parameters to the executed function.
  9898. * @returns {promise} A promise which will be notified on each iteration.
  9899. *
  9900. * @example
  9901. * <example module="intervalExample">
  9902. * <file name="index.html">
  9903. * <script>
  9904. * angular.module('intervalExample', [])
  9905. * .controller('ExampleController', ['$scope', '$interval',
  9906. * function($scope, $interval) {
  9907. * $scope.format = 'M/d/yy h:mm:ss a';
  9908. * $scope.blood_1 = 100;
  9909. * $scope.blood_2 = 120;
  9910. *
  9911. * var stop;
  9912. * $scope.fight = function() {
  9913. * // Don't start a new fight if we are already fighting
  9914. * if ( angular.isDefined(stop) ) return;
  9915. *
  9916. * stop = $interval(function() {
  9917. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9918. * $scope.blood_1 = $scope.blood_1 - 3;
  9919. * $scope.blood_2 = $scope.blood_2 - 4;
  9920. * } else {
  9921. * $scope.stopFight();
  9922. * }
  9923. * }, 100);
  9924. * };
  9925. *
  9926. * $scope.stopFight = function() {
  9927. * if (angular.isDefined(stop)) {
  9928. * $interval.cancel(stop);
  9929. * stop = undefined;
  9930. * }
  9931. * };
  9932. *
  9933. * $scope.resetFight = function() {
  9934. * $scope.blood_1 = 100;
  9935. * $scope.blood_2 = 120;
  9936. * };
  9937. *
  9938. * $scope.$on('$destroy', function() {
  9939. * // Make sure that the interval is destroyed too
  9940. * $scope.stopFight();
  9941. * });
  9942. * }])
  9943. * // Register the 'myCurrentTime' directive factory method.
  9944. * // We inject $interval and dateFilter service since the factory method is DI.
  9945. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9946. * function($interval, dateFilter) {
  9947. * // return the directive link function. (compile function not needed)
  9948. * return function(scope, element, attrs) {
  9949. * var format, // date format
  9950. * stopTime; // so that we can cancel the time updates
  9951. *
  9952. * // used to update the UI
  9953. * function updateTime() {
  9954. * element.text(dateFilter(new Date(), format));
  9955. * }
  9956. *
  9957. * // watch the expression, and update the UI on change.
  9958. * scope.$watch(attrs.myCurrentTime, function(value) {
  9959. * format = value;
  9960. * updateTime();
  9961. * });
  9962. *
  9963. * stopTime = $interval(updateTime, 1000);
  9964. *
  9965. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9966. * // to prevent updating time after the DOM element was removed.
  9967. * element.on('$destroy', function() {
  9968. * $interval.cancel(stopTime);
  9969. * });
  9970. * }
  9971. * }]);
  9972. * </script>
  9973. *
  9974. * <div>
  9975. * <div ng-controller="ExampleController">
  9976. * <label>Date format: <input ng-model="format"></label> <hr/>
  9977. * Current time is: <span my-current-time="format"></span>
  9978. * <hr/>
  9979. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9980. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9981. * <button type="button" data-ng-click="fight()">Fight</button>
  9982. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9983. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9984. * </div>
  9985. * </div>
  9986. *
  9987. * </file>
  9988. * </example>
  9989. */
  9990. function interval(fn, delay, count, invokeApply) {
  9991. var hasParams = arguments.length > 4,
  9992. args = hasParams ? sliceArgs(arguments, 4) : [],
  9993. setInterval = $window.setInterval,
  9994. clearInterval = $window.clearInterval,
  9995. iteration = 0,
  9996. skipApply = (isDefined(invokeApply) && !invokeApply),
  9997. deferred = (skipApply ? $$q : $q).defer(),
  9998. promise = deferred.promise;
  9999. count = isDefined(count) ? count : 0;
  10000. promise.then(null, null, (!hasParams) ? fn : function() {
  10001. fn.apply(null, args);
  10002. });
  10003. promise.$$intervalId = setInterval(function tick() {
  10004. deferred.notify(iteration++);
  10005. if (count > 0 && iteration >= count) {
  10006. deferred.resolve(iteration);
  10007. clearInterval(promise.$$intervalId);
  10008. delete intervals[promise.$$intervalId];
  10009. }
  10010. if (!skipApply) $rootScope.$apply();
  10011. }, delay);
  10012. intervals[promise.$$intervalId] = deferred;
  10013. return promise;
  10014. }
  10015. /**
  10016. * @ngdoc method
  10017. * @name $interval#cancel
  10018. *
  10019. * @description
  10020. * Cancels a task associated with the `promise`.
  10021. *
  10022. * @param {promise} promise returned by the `$interval` function.
  10023. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10024. */
  10025. interval.cancel = function(promise) {
  10026. if (promise && promise.$$intervalId in intervals) {
  10027. intervals[promise.$$intervalId].reject('canceled');
  10028. $window.clearInterval(promise.$$intervalId);
  10029. delete intervals[promise.$$intervalId];
  10030. return true;
  10031. }
  10032. return false;
  10033. };
  10034. return interval;
  10035. }];
  10036. }
  10037. /**
  10038. * @ngdoc service
  10039. * @name $locale
  10040. *
  10041. * @description
  10042. * $locale service provides localization rules for various Angular components. As of right now the
  10043. * only public api is:
  10044. *
  10045. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10046. */
  10047. function $LocaleProvider() {
  10048. this.$get = function() {
  10049. return {
  10050. id: 'en-us',
  10051. NUMBER_FORMATS: {
  10052. DECIMAL_SEP: '.',
  10053. GROUP_SEP: ',',
  10054. PATTERNS: [
  10055. { // Decimal Pattern
  10056. minInt: 1,
  10057. minFrac: 0,
  10058. maxFrac: 3,
  10059. posPre: '',
  10060. posSuf: '',
  10061. negPre: '-',
  10062. negSuf: '',
  10063. gSize: 3,
  10064. lgSize: 3
  10065. },{ //Currency Pattern
  10066. minInt: 1,
  10067. minFrac: 2,
  10068. maxFrac: 2,
  10069. posPre: '\u00A4',
  10070. posSuf: '',
  10071. negPre: '(\u00A4',
  10072. negSuf: ')',
  10073. gSize: 3,
  10074. lgSize: 3
  10075. }
  10076. ],
  10077. CURRENCY_SYM: '$'
  10078. },
  10079. DATETIME_FORMATS: {
  10080. MONTH:
  10081. 'January,February,March,April,May,June,July,August,September,October,November,December'
  10082. .split(','),
  10083. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  10084. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  10085. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  10086. AMPMS: ['AM','PM'],
  10087. medium: 'MMM d, y h:mm:ss a',
  10088. 'short': 'M/d/yy h:mm a',
  10089. fullDate: 'EEEE, MMMM d, y',
  10090. longDate: 'MMMM d, y',
  10091. mediumDate: 'MMM d, y',
  10092. shortDate: 'M/d/yy',
  10093. mediumTime: 'h:mm:ss a',
  10094. shortTime: 'h:mm a',
  10095. ERANAMES: [
  10096. "Before Christ",
  10097. "Anno Domini"
  10098. ],
  10099. ERAS: [
  10100. "BC",
  10101. "AD"
  10102. ]
  10103. },
  10104. pluralCat: function(num) {
  10105. if (num === 1) {
  10106. return 'one';
  10107. }
  10108. return 'other';
  10109. }
  10110. };
  10111. };
  10112. }
  10113. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10114. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10115. var $locationMinErr = minErr('$location');
  10116. /**
  10117. * Encode path using encodeUriSegment, ignoring forward slashes
  10118. *
  10119. * @param {string} path Path to encode
  10120. * @returns {string}
  10121. */
  10122. function encodePath(path) {
  10123. var segments = path.split('/'),
  10124. i = segments.length;
  10125. while (i--) {
  10126. segments[i] = encodeUriSegment(segments[i]);
  10127. }
  10128. return segments.join('/');
  10129. }
  10130. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10131. var parsedUrl = urlResolve(absoluteUrl);
  10132. locationObj.$$protocol = parsedUrl.protocol;
  10133. locationObj.$$host = parsedUrl.hostname;
  10134. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10135. }
  10136. function parseAppUrl(relativeUrl, locationObj) {
  10137. var prefixed = (relativeUrl.charAt(0) !== '/');
  10138. if (prefixed) {
  10139. relativeUrl = '/' + relativeUrl;
  10140. }
  10141. var match = urlResolve(relativeUrl);
  10142. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10143. match.pathname.substring(1) : match.pathname);
  10144. locationObj.$$search = parseKeyValue(match.search);
  10145. locationObj.$$hash = decodeURIComponent(match.hash);
  10146. // make sure path starts with '/';
  10147. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10148. locationObj.$$path = '/' + locationObj.$$path;
  10149. }
  10150. }
  10151. /**
  10152. *
  10153. * @param {string} begin
  10154. * @param {string} whole
  10155. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10156. * expected string.
  10157. */
  10158. function beginsWith(begin, whole) {
  10159. if (whole.indexOf(begin) === 0) {
  10160. return whole.substr(begin.length);
  10161. }
  10162. }
  10163. function stripHash(url) {
  10164. var index = url.indexOf('#');
  10165. return index == -1 ? url : url.substr(0, index);
  10166. }
  10167. function trimEmptyHash(url) {
  10168. return url.replace(/(#.+)|#$/, '$1');
  10169. }
  10170. function stripFile(url) {
  10171. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10172. }
  10173. /* return the server only (scheme://host:port) */
  10174. function serverBase(url) {
  10175. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10176. }
  10177. /**
  10178. * LocationHtml5Url represents an url
  10179. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10180. *
  10181. * @constructor
  10182. * @param {string} appBase application base URL
  10183. * @param {string} basePrefix url path prefix
  10184. */
  10185. function LocationHtml5Url(appBase, basePrefix) {
  10186. this.$$html5 = true;
  10187. basePrefix = basePrefix || '';
  10188. var appBaseNoFile = stripFile(appBase);
  10189. parseAbsoluteUrl(appBase, this);
  10190. /**
  10191. * Parse given html5 (regular) url string into properties
  10192. * @param {string} url HTML5 url
  10193. * @private
  10194. */
  10195. this.$$parse = function(url) {
  10196. var pathUrl = beginsWith(appBaseNoFile, url);
  10197. if (!isString(pathUrl)) {
  10198. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10199. appBaseNoFile);
  10200. }
  10201. parseAppUrl(pathUrl, this);
  10202. if (!this.$$path) {
  10203. this.$$path = '/';
  10204. }
  10205. this.$$compose();
  10206. };
  10207. /**
  10208. * Compose url and update `absUrl` property
  10209. * @private
  10210. */
  10211. this.$$compose = function() {
  10212. var search = toKeyValue(this.$$search),
  10213. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10214. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10215. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10216. };
  10217. this.$$parseLinkUrl = function(url, relHref) {
  10218. if (relHref && relHref[0] === '#') {
  10219. // special case for links to hash fragments:
  10220. // keep the old url and only replace the hash fragment
  10221. this.hash(relHref.slice(1));
  10222. return true;
  10223. }
  10224. var appUrl, prevAppUrl;
  10225. var rewrittenUrl;
  10226. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  10227. prevAppUrl = appUrl;
  10228. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  10229. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10230. } else {
  10231. rewrittenUrl = appBase + prevAppUrl;
  10232. }
  10233. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  10234. rewrittenUrl = appBaseNoFile + appUrl;
  10235. } else if (appBaseNoFile == url + '/') {
  10236. rewrittenUrl = appBaseNoFile;
  10237. }
  10238. if (rewrittenUrl) {
  10239. this.$$parse(rewrittenUrl);
  10240. }
  10241. return !!rewrittenUrl;
  10242. };
  10243. }
  10244. /**
  10245. * LocationHashbangUrl represents url
  10246. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10247. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10248. *
  10249. * @constructor
  10250. * @param {string} appBase application base URL
  10251. * @param {string} hashPrefix hashbang prefix
  10252. */
  10253. function LocationHashbangUrl(appBase, hashPrefix) {
  10254. var appBaseNoFile = stripFile(appBase);
  10255. parseAbsoluteUrl(appBase, this);
  10256. /**
  10257. * Parse given hashbang url into properties
  10258. * @param {string} url Hashbang url
  10259. * @private
  10260. */
  10261. this.$$parse = function(url) {
  10262. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10263. var withoutHashUrl;
  10264. if (withoutBaseUrl.charAt(0) === '#') {
  10265. // The rest of the url starts with a hash so we have
  10266. // got either a hashbang path or a plain hash fragment
  10267. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10268. if (isUndefined(withoutHashUrl)) {
  10269. // There was no hashbang prefix so we just have a hash fragment
  10270. withoutHashUrl = withoutBaseUrl;
  10271. }
  10272. } else {
  10273. // There was no hashbang path nor hash fragment:
  10274. // If we are in HTML5 mode we use what is left as the path;
  10275. // Otherwise we ignore what is left
  10276. withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
  10277. }
  10278. parseAppUrl(withoutHashUrl, this);
  10279. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10280. this.$$compose();
  10281. /*
  10282. * In Windows, on an anchor node on documents loaded from
  10283. * the filesystem, the browser will return a pathname
  10284. * prefixed with the drive name ('/C:/path') when a
  10285. * pathname without a drive is set:
  10286. * * a.setAttribute('href', '/foo')
  10287. * * a.pathname === '/C:/foo' //true
  10288. *
  10289. * Inside of Angular, we're always using pathnames that
  10290. * do not include drive names for routing.
  10291. */
  10292. function removeWindowsDriveName(path, url, base) {
  10293. /*
  10294. Matches paths for file protocol on windows,
  10295. such as /C:/foo/bar, and captures only /foo/bar.
  10296. */
  10297. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10298. var firstPathSegmentMatch;
  10299. //Get the relative path from the input URL.
  10300. if (url.indexOf(base) === 0) {
  10301. url = url.replace(base, '');
  10302. }
  10303. // The input URL intentionally contains a first path segment that ends with a colon.
  10304. if (windowsFilePathExp.exec(url)) {
  10305. return path;
  10306. }
  10307. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10308. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10309. }
  10310. };
  10311. /**
  10312. * Compose hashbang url and update `absUrl` property
  10313. * @private
  10314. */
  10315. this.$$compose = function() {
  10316. var search = toKeyValue(this.$$search),
  10317. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10318. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10319. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10320. };
  10321. this.$$parseLinkUrl = function(url, relHref) {
  10322. if (stripHash(appBase) == stripHash(url)) {
  10323. this.$$parse(url);
  10324. return true;
  10325. }
  10326. return false;
  10327. };
  10328. }
  10329. /**
  10330. * LocationHashbangUrl represents url
  10331. * This object is exposed as $location service when html5 history api is enabled but the browser
  10332. * does not support it.
  10333. *
  10334. * @constructor
  10335. * @param {string} appBase application base URL
  10336. * @param {string} hashPrefix hashbang prefix
  10337. */
  10338. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  10339. this.$$html5 = true;
  10340. LocationHashbangUrl.apply(this, arguments);
  10341. var appBaseNoFile = stripFile(appBase);
  10342. this.$$parseLinkUrl = function(url, relHref) {
  10343. if (relHref && relHref[0] === '#') {
  10344. // special case for links to hash fragments:
  10345. // keep the old url and only replace the hash fragment
  10346. this.hash(relHref.slice(1));
  10347. return true;
  10348. }
  10349. var rewrittenUrl;
  10350. var appUrl;
  10351. if (appBase == stripHash(url)) {
  10352. rewrittenUrl = url;
  10353. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10354. rewrittenUrl = appBase + hashPrefix + appUrl;
  10355. } else if (appBaseNoFile === url + '/') {
  10356. rewrittenUrl = appBaseNoFile;
  10357. }
  10358. if (rewrittenUrl) {
  10359. this.$$parse(rewrittenUrl);
  10360. }
  10361. return !!rewrittenUrl;
  10362. };
  10363. this.$$compose = function() {
  10364. var search = toKeyValue(this.$$search),
  10365. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10366. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10367. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  10368. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10369. };
  10370. }
  10371. var locationPrototype = {
  10372. /**
  10373. * Are we in html5 mode?
  10374. * @private
  10375. */
  10376. $$html5: false,
  10377. /**
  10378. * Has any change been replacing?
  10379. * @private
  10380. */
  10381. $$replace: false,
  10382. /**
  10383. * @ngdoc method
  10384. * @name $location#absUrl
  10385. *
  10386. * @description
  10387. * This method is getter only.
  10388. *
  10389. * Return full url representation with all segments encoded according to rules specified in
  10390. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10391. *
  10392. *
  10393. * ```js
  10394. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10395. * var absUrl = $location.absUrl();
  10396. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10397. * ```
  10398. *
  10399. * @return {string} full url
  10400. */
  10401. absUrl: locationGetter('$$absUrl'),
  10402. /**
  10403. * @ngdoc method
  10404. * @name $location#url
  10405. *
  10406. * @description
  10407. * This method is getter / setter.
  10408. *
  10409. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10410. *
  10411. * Change path, search and hash, when called with parameter and return `$location`.
  10412. *
  10413. *
  10414. * ```js
  10415. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10416. * var url = $location.url();
  10417. * // => "/some/path?foo=bar&baz=xoxo"
  10418. * ```
  10419. *
  10420. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10421. * @return {string} url
  10422. */
  10423. url: function(url) {
  10424. if (isUndefined(url)) {
  10425. return this.$$url;
  10426. }
  10427. var match = PATH_MATCH.exec(url);
  10428. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10429. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10430. this.hash(match[5] || '');
  10431. return this;
  10432. },
  10433. /**
  10434. * @ngdoc method
  10435. * @name $location#protocol
  10436. *
  10437. * @description
  10438. * This method is getter only.
  10439. *
  10440. * Return protocol of current url.
  10441. *
  10442. *
  10443. * ```js
  10444. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10445. * var protocol = $location.protocol();
  10446. * // => "http"
  10447. * ```
  10448. *
  10449. * @return {string} protocol of current url
  10450. */
  10451. protocol: locationGetter('$$protocol'),
  10452. /**
  10453. * @ngdoc method
  10454. * @name $location#host
  10455. *
  10456. * @description
  10457. * This method is getter only.
  10458. *
  10459. * Return host of current url.
  10460. *
  10461. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10462. *
  10463. *
  10464. * ```js
  10465. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10466. * var host = $location.host();
  10467. * // => "example.com"
  10468. *
  10469. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10470. * host = $location.host();
  10471. * // => "example.com"
  10472. * host = location.host;
  10473. * // => "example.com:8080"
  10474. * ```
  10475. *
  10476. * @return {string} host of current url.
  10477. */
  10478. host: locationGetter('$$host'),
  10479. /**
  10480. * @ngdoc method
  10481. * @name $location#port
  10482. *
  10483. * @description
  10484. * This method is getter only.
  10485. *
  10486. * Return port of current url.
  10487. *
  10488. *
  10489. * ```js
  10490. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10491. * var port = $location.port();
  10492. * // => 80
  10493. * ```
  10494. *
  10495. * @return {Number} port
  10496. */
  10497. port: locationGetter('$$port'),
  10498. /**
  10499. * @ngdoc method
  10500. * @name $location#path
  10501. *
  10502. * @description
  10503. * This method is getter / setter.
  10504. *
  10505. * Return path of current url when called without any parameter.
  10506. *
  10507. * Change path when called with parameter and return `$location`.
  10508. *
  10509. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10510. * if it is missing.
  10511. *
  10512. *
  10513. * ```js
  10514. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10515. * var path = $location.path();
  10516. * // => "/some/path"
  10517. * ```
  10518. *
  10519. * @param {(string|number)=} path New path
  10520. * @return {string} path
  10521. */
  10522. path: locationGetterSetter('$$path', function(path) {
  10523. path = path !== null ? path.toString() : '';
  10524. return path.charAt(0) == '/' ? path : '/' + path;
  10525. }),
  10526. /**
  10527. * @ngdoc method
  10528. * @name $location#search
  10529. *
  10530. * @description
  10531. * This method is getter / setter.
  10532. *
  10533. * Return search part (as object) of current url when called without any parameter.
  10534. *
  10535. * Change search part when called with parameter and return `$location`.
  10536. *
  10537. *
  10538. * ```js
  10539. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10540. * var searchObject = $location.search();
  10541. * // => {foo: 'bar', baz: 'xoxo'}
  10542. *
  10543. * // set foo to 'yipee'
  10544. * $location.search('foo', 'yipee');
  10545. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10546. * ```
  10547. *
  10548. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10549. * hash object.
  10550. *
  10551. * When called with a single argument the method acts as a setter, setting the `search` component
  10552. * of `$location` to the specified value.
  10553. *
  10554. * If the argument is a hash object containing an array of values, these values will be encoded
  10555. * as duplicate search parameters in the url.
  10556. *
  10557. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10558. * will override only a single search property.
  10559. *
  10560. * If `paramValue` is an array, it will override the property of the `search` component of
  10561. * `$location` specified via the first argument.
  10562. *
  10563. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10564. *
  10565. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10566. * value nor trailing equal sign.
  10567. *
  10568. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10569. * one or more arguments returns `$location` object itself.
  10570. */
  10571. search: function(search, paramValue) {
  10572. switch (arguments.length) {
  10573. case 0:
  10574. return this.$$search;
  10575. case 1:
  10576. if (isString(search) || isNumber(search)) {
  10577. search = search.toString();
  10578. this.$$search = parseKeyValue(search);
  10579. } else if (isObject(search)) {
  10580. search = copy(search, {});
  10581. // remove object undefined or null properties
  10582. forEach(search, function(value, key) {
  10583. if (value == null) delete search[key];
  10584. });
  10585. this.$$search = search;
  10586. } else {
  10587. throw $locationMinErr('isrcharg',
  10588. 'The first argument of the `$location#search()` call must be a string or an object.');
  10589. }
  10590. break;
  10591. default:
  10592. if (isUndefined(paramValue) || paramValue === null) {
  10593. delete this.$$search[search];
  10594. } else {
  10595. this.$$search[search] = paramValue;
  10596. }
  10597. }
  10598. this.$$compose();
  10599. return this;
  10600. },
  10601. /**
  10602. * @ngdoc method
  10603. * @name $location#hash
  10604. *
  10605. * @description
  10606. * This method is getter / setter.
  10607. *
  10608. * Return hash fragment when called without any parameter.
  10609. *
  10610. * Change hash fragment when called with parameter and return `$location`.
  10611. *
  10612. *
  10613. * ```js
  10614. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10615. * var hash = $location.hash();
  10616. * // => "hashValue"
  10617. * ```
  10618. *
  10619. * @param {(string|number)=} hash New hash fragment
  10620. * @return {string} hash
  10621. */
  10622. hash: locationGetterSetter('$$hash', function(hash) {
  10623. return hash !== null ? hash.toString() : '';
  10624. }),
  10625. /**
  10626. * @ngdoc method
  10627. * @name $location#replace
  10628. *
  10629. * @description
  10630. * If called, all changes to $location during current `$digest` will be replacing current history
  10631. * record, instead of adding new one.
  10632. */
  10633. replace: function() {
  10634. this.$$replace = true;
  10635. return this;
  10636. }
  10637. };
  10638. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10639. Location.prototype = Object.create(locationPrototype);
  10640. /**
  10641. * @ngdoc method
  10642. * @name $location#state
  10643. *
  10644. * @description
  10645. * This method is getter / setter.
  10646. *
  10647. * Return the history state object when called without any parameter.
  10648. *
  10649. * Change the history state object when called with one parameter and return `$location`.
  10650. * The state object is later passed to `pushState` or `replaceState`.
  10651. *
  10652. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10653. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10654. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10655. *
  10656. * @param {object=} state State object for pushState or replaceState
  10657. * @return {object} state
  10658. */
  10659. Location.prototype.state = function(state) {
  10660. if (!arguments.length) {
  10661. return this.$$state;
  10662. }
  10663. if (Location !== LocationHtml5Url || !this.$$html5) {
  10664. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10665. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10666. }
  10667. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10668. // but we're changing the $$state reference to $browser.state() during the $digest
  10669. // so the modification window is narrow.
  10670. this.$$state = isUndefined(state) ? null : state;
  10671. return this;
  10672. };
  10673. });
  10674. function locationGetter(property) {
  10675. return function() {
  10676. return this[property];
  10677. };
  10678. }
  10679. function locationGetterSetter(property, preprocess) {
  10680. return function(value) {
  10681. if (isUndefined(value)) {
  10682. return this[property];
  10683. }
  10684. this[property] = preprocess(value);
  10685. this.$$compose();
  10686. return this;
  10687. };
  10688. }
  10689. /**
  10690. * @ngdoc service
  10691. * @name $location
  10692. *
  10693. * @requires $rootElement
  10694. *
  10695. * @description
  10696. * The $location service parses the URL in the browser address bar (based on the
  10697. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10698. * available to your application. Changes to the URL in the address bar are reflected into
  10699. * $location service and changes to $location are reflected into the browser address bar.
  10700. *
  10701. * **The $location service:**
  10702. *
  10703. * - Exposes the current URL in the browser address bar, so you can
  10704. * - Watch and observe the URL.
  10705. * - Change the URL.
  10706. * - Synchronizes the URL with the browser when the user
  10707. * - Changes the address bar.
  10708. * - Clicks the back or forward button (or clicks a History link).
  10709. * - Clicks on a link.
  10710. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10711. *
  10712. * For more information see {@link guide/$location Developer Guide: Using $location}
  10713. */
  10714. /**
  10715. * @ngdoc provider
  10716. * @name $locationProvider
  10717. * @description
  10718. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10719. */
  10720. function $LocationProvider() {
  10721. var hashPrefix = '',
  10722. html5Mode = {
  10723. enabled: false,
  10724. requireBase: true,
  10725. rewriteLinks: true
  10726. };
  10727. /**
  10728. * @ngdoc method
  10729. * @name $locationProvider#hashPrefix
  10730. * @description
  10731. * @param {string=} prefix Prefix for hash part (containing path and search)
  10732. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10733. */
  10734. this.hashPrefix = function(prefix) {
  10735. if (isDefined(prefix)) {
  10736. hashPrefix = prefix;
  10737. return this;
  10738. } else {
  10739. return hashPrefix;
  10740. }
  10741. };
  10742. /**
  10743. * @ngdoc method
  10744. * @name $locationProvider#html5Mode
  10745. * @description
  10746. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10747. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10748. * properties:
  10749. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10750. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10751. * support `pushState`.
  10752. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10753. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10754. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10755. * See the {@link guide/$location $location guide for more information}
  10756. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10757. * enables/disables url rewriting for relative links.
  10758. *
  10759. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10760. */
  10761. this.html5Mode = function(mode) {
  10762. if (isBoolean(mode)) {
  10763. html5Mode.enabled = mode;
  10764. return this;
  10765. } else if (isObject(mode)) {
  10766. if (isBoolean(mode.enabled)) {
  10767. html5Mode.enabled = mode.enabled;
  10768. }
  10769. if (isBoolean(mode.requireBase)) {
  10770. html5Mode.requireBase = mode.requireBase;
  10771. }
  10772. if (isBoolean(mode.rewriteLinks)) {
  10773. html5Mode.rewriteLinks = mode.rewriteLinks;
  10774. }
  10775. return this;
  10776. } else {
  10777. return html5Mode;
  10778. }
  10779. };
  10780. /**
  10781. * @ngdoc event
  10782. * @name $location#$locationChangeStart
  10783. * @eventType broadcast on root scope
  10784. * @description
  10785. * Broadcasted before a URL will change.
  10786. *
  10787. * This change can be prevented by calling
  10788. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10789. * details about event object. Upon successful change
  10790. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10791. *
  10792. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10793. * the browser supports the HTML5 History API.
  10794. *
  10795. * @param {Object} angularEvent Synthetic event object.
  10796. * @param {string} newUrl New URL
  10797. * @param {string=} oldUrl URL that was before it was changed.
  10798. * @param {string=} newState New history state object
  10799. * @param {string=} oldState History state object that was before it was changed.
  10800. */
  10801. /**
  10802. * @ngdoc event
  10803. * @name $location#$locationChangeSuccess
  10804. * @eventType broadcast on root scope
  10805. * @description
  10806. * Broadcasted after a URL was changed.
  10807. *
  10808. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10809. * the browser supports the HTML5 History API.
  10810. *
  10811. * @param {Object} angularEvent Synthetic event object.
  10812. * @param {string} newUrl New URL
  10813. * @param {string=} oldUrl URL that was before it was changed.
  10814. * @param {string=} newState New history state object
  10815. * @param {string=} oldState History state object that was before it was changed.
  10816. */
  10817. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10818. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10819. var $location,
  10820. LocationMode,
  10821. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10822. initialUrl = $browser.url(),
  10823. appBase;
  10824. if (html5Mode.enabled) {
  10825. if (!baseHref && html5Mode.requireBase) {
  10826. throw $locationMinErr('nobase',
  10827. "$location in HTML5 mode requires a <base> tag to be present!");
  10828. }
  10829. appBase = serverBase(initialUrl) + (baseHref || '/');
  10830. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10831. } else {
  10832. appBase = stripHash(initialUrl);
  10833. LocationMode = LocationHashbangUrl;
  10834. }
  10835. $location = new LocationMode(appBase, '#' + hashPrefix);
  10836. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10837. $location.$$state = $browser.state();
  10838. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10839. function setBrowserUrlWithFallback(url, replace, state) {
  10840. var oldUrl = $location.url();
  10841. var oldState = $location.$$state;
  10842. try {
  10843. $browser.url(url, replace, state);
  10844. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10845. // state object; this makes possible quick checking if the state changed in the digest
  10846. // loop. Checking deep equality would be too expensive.
  10847. $location.$$state = $browser.state();
  10848. } catch (e) {
  10849. // Restore old values if pushState fails
  10850. $location.url(oldUrl);
  10851. $location.$$state = oldState;
  10852. throw e;
  10853. }
  10854. }
  10855. $rootElement.on('click', function(event) {
  10856. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10857. // currently we open nice url link and redirect then
  10858. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10859. var elm = jqLite(event.target);
  10860. // traverse the DOM up to find first A tag
  10861. while (nodeName_(elm[0]) !== 'a') {
  10862. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10863. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10864. }
  10865. var absHref = elm.prop('href');
  10866. // get the actual href attribute - see
  10867. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10868. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10869. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10870. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10871. // an animation.
  10872. absHref = urlResolve(absHref.animVal).href;
  10873. }
  10874. // Ignore when url is started with javascript: or mailto:
  10875. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10876. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10877. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10878. // We do a preventDefault for all urls that are part of the angular application,
  10879. // in html5mode and also without, so that we are able to abort navigation without
  10880. // getting double entries in the location history.
  10881. event.preventDefault();
  10882. // update location manually
  10883. if ($location.absUrl() != $browser.url()) {
  10884. $rootScope.$apply();
  10885. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10886. $window.angular['ff-684208-preventDefault'] = true;
  10887. }
  10888. }
  10889. }
  10890. });
  10891. // rewrite hashbang url <> html5 url
  10892. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10893. $browser.url($location.absUrl(), true);
  10894. }
  10895. var initializing = true;
  10896. // update $location when $browser url changes
  10897. $browser.onUrlChange(function(newUrl, newState) {
  10898. $rootScope.$evalAsync(function() {
  10899. var oldUrl = $location.absUrl();
  10900. var oldState = $location.$$state;
  10901. var defaultPrevented;
  10902. $location.$$parse(newUrl);
  10903. $location.$$state = newState;
  10904. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10905. newState, oldState).defaultPrevented;
  10906. // if the location was changed by a `$locationChangeStart` handler then stop
  10907. // processing this location change
  10908. if ($location.absUrl() !== newUrl) return;
  10909. if (defaultPrevented) {
  10910. $location.$$parse(oldUrl);
  10911. $location.$$state = oldState;
  10912. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10913. } else {
  10914. initializing = false;
  10915. afterLocationChange(oldUrl, oldState);
  10916. }
  10917. });
  10918. if (!$rootScope.$$phase) $rootScope.$digest();
  10919. });
  10920. // update browser
  10921. $rootScope.$watch(function $locationWatch() {
  10922. var oldUrl = trimEmptyHash($browser.url());
  10923. var newUrl = trimEmptyHash($location.absUrl());
  10924. var oldState = $browser.state();
  10925. var currentReplace = $location.$$replace;
  10926. var urlOrStateChanged = oldUrl !== newUrl ||
  10927. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10928. if (initializing || urlOrStateChanged) {
  10929. initializing = false;
  10930. $rootScope.$evalAsync(function() {
  10931. var newUrl = $location.absUrl();
  10932. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10933. $location.$$state, oldState).defaultPrevented;
  10934. // if the location was changed by a `$locationChangeStart` handler then stop
  10935. // processing this location change
  10936. if ($location.absUrl() !== newUrl) return;
  10937. if (defaultPrevented) {
  10938. $location.$$parse(oldUrl);
  10939. $location.$$state = oldState;
  10940. } else {
  10941. if (urlOrStateChanged) {
  10942. setBrowserUrlWithFallback(newUrl, currentReplace,
  10943. oldState === $location.$$state ? null : $location.$$state);
  10944. }
  10945. afterLocationChange(oldUrl, oldState);
  10946. }
  10947. });
  10948. }
  10949. $location.$$replace = false;
  10950. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10951. // there is a change
  10952. });
  10953. return $location;
  10954. function afterLocationChange(oldUrl, oldState) {
  10955. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10956. $location.$$state, oldState);
  10957. }
  10958. }];
  10959. }
  10960. /**
  10961. * @ngdoc service
  10962. * @name $log
  10963. * @requires $window
  10964. *
  10965. * @description
  10966. * Simple service for logging. Default implementation safely writes the message
  10967. * into the browser's console (if present).
  10968. *
  10969. * The main purpose of this service is to simplify debugging and troubleshooting.
  10970. *
  10971. * The default is to log `debug` messages. You can use
  10972. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10973. *
  10974. * @example
  10975. <example module="logExample">
  10976. <file name="script.js">
  10977. angular.module('logExample', [])
  10978. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10979. $scope.$log = $log;
  10980. $scope.message = 'Hello World!';
  10981. }]);
  10982. </file>
  10983. <file name="index.html">
  10984. <div ng-controller="LogController">
  10985. <p>Reload this page with open console, enter text and hit the log button...</p>
  10986. <label>Message:
  10987. <input type="text" ng-model="message" /></label>
  10988. <button ng-click="$log.log(message)">log</button>
  10989. <button ng-click="$log.warn(message)">warn</button>
  10990. <button ng-click="$log.info(message)">info</button>
  10991. <button ng-click="$log.error(message)">error</button>
  10992. <button ng-click="$log.debug(message)">debug</button>
  10993. </div>
  10994. </file>
  10995. </example>
  10996. */
  10997. /**
  10998. * @ngdoc provider
  10999. * @name $logProvider
  11000. * @description
  11001. * Use the `$logProvider` to configure how the application logs messages
  11002. */
  11003. function $LogProvider() {
  11004. var debug = true,
  11005. self = this;
  11006. /**
  11007. * @ngdoc method
  11008. * @name $logProvider#debugEnabled
  11009. * @description
  11010. * @param {boolean=} flag enable or disable debug level messages
  11011. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11012. */
  11013. this.debugEnabled = function(flag) {
  11014. if (isDefined(flag)) {
  11015. debug = flag;
  11016. return this;
  11017. } else {
  11018. return debug;
  11019. }
  11020. };
  11021. this.$get = ['$window', function($window) {
  11022. return {
  11023. /**
  11024. * @ngdoc method
  11025. * @name $log#log
  11026. *
  11027. * @description
  11028. * Write a log message
  11029. */
  11030. log: consoleLog('log'),
  11031. /**
  11032. * @ngdoc method
  11033. * @name $log#info
  11034. *
  11035. * @description
  11036. * Write an information message
  11037. */
  11038. info: consoleLog('info'),
  11039. /**
  11040. * @ngdoc method
  11041. * @name $log#warn
  11042. *
  11043. * @description
  11044. * Write a warning message
  11045. */
  11046. warn: consoleLog('warn'),
  11047. /**
  11048. * @ngdoc method
  11049. * @name $log#error
  11050. *
  11051. * @description
  11052. * Write an error message
  11053. */
  11054. error: consoleLog('error'),
  11055. /**
  11056. * @ngdoc method
  11057. * @name $log#debug
  11058. *
  11059. * @description
  11060. * Write a debug message
  11061. */
  11062. debug: (function() {
  11063. var fn = consoleLog('debug');
  11064. return function() {
  11065. if (debug) {
  11066. fn.apply(self, arguments);
  11067. }
  11068. };
  11069. }())
  11070. };
  11071. function formatError(arg) {
  11072. if (arg instanceof Error) {
  11073. if (arg.stack) {
  11074. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11075. ? 'Error: ' + arg.message + '\n' + arg.stack
  11076. : arg.stack;
  11077. } else if (arg.sourceURL) {
  11078. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11079. }
  11080. }
  11081. return arg;
  11082. }
  11083. function consoleLog(type) {
  11084. var console = $window.console || {},
  11085. logFn = console[type] || console.log || noop,
  11086. hasApply = false;
  11087. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11088. // The reason behind this is that console.log has type "object" in IE8...
  11089. try {
  11090. hasApply = !!logFn.apply;
  11091. } catch (e) {}
  11092. if (hasApply) {
  11093. return function() {
  11094. var args = [];
  11095. forEach(arguments, function(arg) {
  11096. args.push(formatError(arg));
  11097. });
  11098. return logFn.apply(console, args);
  11099. };
  11100. }
  11101. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11102. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11103. return function(arg1, arg2) {
  11104. logFn(arg1, arg2 == null ? '' : arg2);
  11105. };
  11106. }
  11107. }];
  11108. }
  11109. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11110. * Any commits to this file should be reviewed with security in mind. *
  11111. * Changes to this file can potentially create security vulnerabilities. *
  11112. * An approval from 2 Core members with history of modifying *
  11113. * this file is required. *
  11114. * *
  11115. * Does the change somehow allow for arbitrary javascript to be executed? *
  11116. * Or allows for someone to change the prototype of built-in objects? *
  11117. * Or gives undesired access to variables likes document or window? *
  11118. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11119. var $parseMinErr = minErr('$parse');
  11120. // Sandboxing Angular Expressions
  11121. // ------------------------------
  11122. // Angular expressions are generally considered safe because these expressions only have direct
  11123. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11124. // obtaining a reference to native JS functions such as the Function constructor.
  11125. //
  11126. // As an example, consider the following Angular expression:
  11127. //
  11128. // {}.toString.constructor('alert("evil JS code")')
  11129. //
  11130. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11131. // against the expression language, but not to prevent exploits that were enabled by exposing
  11132. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11133. // practice and therefore we are not even trying to protect against interaction with an object
  11134. // explicitly exposed in this way.
  11135. //
  11136. // In general, it is not possible to access a Window object from an angular expression unless a
  11137. // window or some DOM object that has a reference to window is published onto a Scope.
  11138. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11139. // native objects.
  11140. //
  11141. // See https://docs.angularjs.org/guide/security
  11142. function ensureSafeMemberName(name, fullExpression) {
  11143. if (name === "__defineGetter__" || name === "__defineSetter__"
  11144. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11145. || name === "__proto__") {
  11146. throw $parseMinErr('isecfld',
  11147. 'Attempting to access a disallowed field in Angular expressions! '
  11148. + 'Expression: {0}', fullExpression);
  11149. }
  11150. return name;
  11151. }
  11152. function ensureSafeObject(obj, fullExpression) {
  11153. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11154. if (obj) {
  11155. if (obj.constructor === obj) {
  11156. throw $parseMinErr('isecfn',
  11157. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11158. fullExpression);
  11159. } else if (// isWindow(obj)
  11160. obj.window === obj) {
  11161. throw $parseMinErr('isecwindow',
  11162. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11163. fullExpression);
  11164. } else if (// isElement(obj)
  11165. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11166. throw $parseMinErr('isecdom',
  11167. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11168. fullExpression);
  11169. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11170. obj === Object) {
  11171. throw $parseMinErr('isecobj',
  11172. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11173. fullExpression);
  11174. }
  11175. }
  11176. return obj;
  11177. }
  11178. var CALL = Function.prototype.call;
  11179. var APPLY = Function.prototype.apply;
  11180. var BIND = Function.prototype.bind;
  11181. function ensureSafeFunction(obj, fullExpression) {
  11182. if (obj) {
  11183. if (obj.constructor === obj) {
  11184. throw $parseMinErr('isecfn',
  11185. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11186. fullExpression);
  11187. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11188. throw $parseMinErr('isecff',
  11189. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11190. fullExpression);
  11191. }
  11192. }
  11193. }
  11194. var OPERATORS = createMap();
  11195. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11196. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11197. /////////////////////////////////////////
  11198. /**
  11199. * @constructor
  11200. */
  11201. var Lexer = function(options) {
  11202. this.options = options;
  11203. };
  11204. Lexer.prototype = {
  11205. constructor: Lexer,
  11206. lex: function(text) {
  11207. this.text = text;
  11208. this.index = 0;
  11209. this.tokens = [];
  11210. while (this.index < this.text.length) {
  11211. var ch = this.text.charAt(this.index);
  11212. if (ch === '"' || ch === "'") {
  11213. this.readString(ch);
  11214. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11215. this.readNumber();
  11216. } else if (this.isIdent(ch)) {
  11217. this.readIdent();
  11218. } else if (this.is(ch, '(){}[].,;:?')) {
  11219. this.tokens.push({index: this.index, text: ch});
  11220. this.index++;
  11221. } else if (this.isWhitespace(ch)) {
  11222. this.index++;
  11223. } else {
  11224. var ch2 = ch + this.peek();
  11225. var ch3 = ch2 + this.peek(2);
  11226. var op1 = OPERATORS[ch];
  11227. var op2 = OPERATORS[ch2];
  11228. var op3 = OPERATORS[ch3];
  11229. if (op1 || op2 || op3) {
  11230. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11231. this.tokens.push({index: this.index, text: token, operator: true});
  11232. this.index += token.length;
  11233. } else {
  11234. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11235. }
  11236. }
  11237. }
  11238. return this.tokens;
  11239. },
  11240. is: function(ch, chars) {
  11241. return chars.indexOf(ch) !== -1;
  11242. },
  11243. peek: function(i) {
  11244. var num = i || 1;
  11245. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11246. },
  11247. isNumber: function(ch) {
  11248. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11249. },
  11250. isWhitespace: function(ch) {
  11251. // IE treats non-breaking space as \u00A0
  11252. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11253. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11254. },
  11255. isIdent: function(ch) {
  11256. return ('a' <= ch && ch <= 'z' ||
  11257. 'A' <= ch && ch <= 'Z' ||
  11258. '_' === ch || ch === '$');
  11259. },
  11260. isExpOperator: function(ch) {
  11261. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11262. },
  11263. throwError: function(error, start, end) {
  11264. end = end || this.index;
  11265. var colStr = (isDefined(start)
  11266. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11267. : ' ' + end);
  11268. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11269. error, colStr, this.text);
  11270. },
  11271. readNumber: function() {
  11272. var number = '';
  11273. var start = this.index;
  11274. while (this.index < this.text.length) {
  11275. var ch = lowercase(this.text.charAt(this.index));
  11276. if (ch == '.' || this.isNumber(ch)) {
  11277. number += ch;
  11278. } else {
  11279. var peekCh = this.peek();
  11280. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11281. number += ch;
  11282. } else if (this.isExpOperator(ch) &&
  11283. peekCh && this.isNumber(peekCh) &&
  11284. number.charAt(number.length - 1) == 'e') {
  11285. number += ch;
  11286. } else if (this.isExpOperator(ch) &&
  11287. (!peekCh || !this.isNumber(peekCh)) &&
  11288. number.charAt(number.length - 1) == 'e') {
  11289. this.throwError('Invalid exponent');
  11290. } else {
  11291. break;
  11292. }
  11293. }
  11294. this.index++;
  11295. }
  11296. this.tokens.push({
  11297. index: start,
  11298. text: number,
  11299. constant: true,
  11300. value: Number(number)
  11301. });
  11302. },
  11303. readIdent: function() {
  11304. var start = this.index;
  11305. while (this.index < this.text.length) {
  11306. var ch = this.text.charAt(this.index);
  11307. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11308. break;
  11309. }
  11310. this.index++;
  11311. }
  11312. this.tokens.push({
  11313. index: start,
  11314. text: this.text.slice(start, this.index),
  11315. identifier: true
  11316. });
  11317. },
  11318. readString: function(quote) {
  11319. var start = this.index;
  11320. this.index++;
  11321. var string = '';
  11322. var rawString = quote;
  11323. var escape = false;
  11324. while (this.index < this.text.length) {
  11325. var ch = this.text.charAt(this.index);
  11326. rawString += ch;
  11327. if (escape) {
  11328. if (ch === 'u') {
  11329. var hex = this.text.substring(this.index + 1, this.index + 5);
  11330. if (!hex.match(/[\da-f]{4}/i)) {
  11331. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11332. }
  11333. this.index += 4;
  11334. string += String.fromCharCode(parseInt(hex, 16));
  11335. } else {
  11336. var rep = ESCAPE[ch];
  11337. string = string + (rep || ch);
  11338. }
  11339. escape = false;
  11340. } else if (ch === '\\') {
  11341. escape = true;
  11342. } else if (ch === quote) {
  11343. this.index++;
  11344. this.tokens.push({
  11345. index: start,
  11346. text: rawString,
  11347. constant: true,
  11348. value: string
  11349. });
  11350. return;
  11351. } else {
  11352. string += ch;
  11353. }
  11354. this.index++;
  11355. }
  11356. this.throwError('Unterminated quote', start);
  11357. }
  11358. };
  11359. var AST = function(lexer, options) {
  11360. this.lexer = lexer;
  11361. this.options = options;
  11362. };
  11363. AST.Program = 'Program';
  11364. AST.ExpressionStatement = 'ExpressionStatement';
  11365. AST.AssignmentExpression = 'AssignmentExpression';
  11366. AST.ConditionalExpression = 'ConditionalExpression';
  11367. AST.LogicalExpression = 'LogicalExpression';
  11368. AST.BinaryExpression = 'BinaryExpression';
  11369. AST.UnaryExpression = 'UnaryExpression';
  11370. AST.CallExpression = 'CallExpression';
  11371. AST.MemberExpression = 'MemberExpression';
  11372. AST.Identifier = 'Identifier';
  11373. AST.Literal = 'Literal';
  11374. AST.ArrayExpression = 'ArrayExpression';
  11375. AST.Property = 'Property';
  11376. AST.ObjectExpression = 'ObjectExpression';
  11377. AST.ThisExpression = 'ThisExpression';
  11378. // Internal use only
  11379. AST.NGValueParameter = 'NGValueParameter';
  11380. AST.prototype = {
  11381. ast: function(text) {
  11382. this.text = text;
  11383. this.tokens = this.lexer.lex(text);
  11384. var value = this.program();
  11385. if (this.tokens.length !== 0) {
  11386. this.throwError('is an unexpected token', this.tokens[0]);
  11387. }
  11388. return value;
  11389. },
  11390. program: function() {
  11391. var body = [];
  11392. while (true) {
  11393. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11394. body.push(this.expressionStatement());
  11395. if (!this.expect(';')) {
  11396. return { type: AST.Program, body: body};
  11397. }
  11398. }
  11399. },
  11400. expressionStatement: function() {
  11401. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11402. },
  11403. filterChain: function() {
  11404. var left = this.expression();
  11405. var token;
  11406. while ((token = this.expect('|'))) {
  11407. left = this.filter(left);
  11408. }
  11409. return left;
  11410. },
  11411. expression: function() {
  11412. return this.assignment();
  11413. },
  11414. assignment: function() {
  11415. var result = this.ternary();
  11416. if (this.expect('=')) {
  11417. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11418. }
  11419. return result;
  11420. },
  11421. ternary: function() {
  11422. var test = this.logicalOR();
  11423. var alternate;
  11424. var consequent;
  11425. if (this.expect('?')) {
  11426. alternate = this.expression();
  11427. if (this.consume(':')) {
  11428. consequent = this.expression();
  11429. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11430. }
  11431. }
  11432. return test;
  11433. },
  11434. logicalOR: function() {
  11435. var left = this.logicalAND();
  11436. while (this.expect('||')) {
  11437. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11438. }
  11439. return left;
  11440. },
  11441. logicalAND: function() {
  11442. var left = this.equality();
  11443. while (this.expect('&&')) {
  11444. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11445. }
  11446. return left;
  11447. },
  11448. equality: function() {
  11449. var left = this.relational();
  11450. var token;
  11451. while ((token = this.expect('==','!=','===','!=='))) {
  11452. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11453. }
  11454. return left;
  11455. },
  11456. relational: function() {
  11457. var left = this.additive();
  11458. var token;
  11459. while ((token = this.expect('<', '>', '<=', '>='))) {
  11460. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11461. }
  11462. return left;
  11463. },
  11464. additive: function() {
  11465. var left = this.multiplicative();
  11466. var token;
  11467. while ((token = this.expect('+','-'))) {
  11468. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11469. }
  11470. return left;
  11471. },
  11472. multiplicative: function() {
  11473. var left = this.unary();
  11474. var token;
  11475. while ((token = this.expect('*','/','%'))) {
  11476. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11477. }
  11478. return left;
  11479. },
  11480. unary: function() {
  11481. var token;
  11482. if ((token = this.expect('+', '-', '!'))) {
  11483. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11484. } else {
  11485. return this.primary();
  11486. }
  11487. },
  11488. primary: function() {
  11489. var primary;
  11490. if (this.expect('(')) {
  11491. primary = this.filterChain();
  11492. this.consume(')');
  11493. } else if (this.expect('[')) {
  11494. primary = this.arrayDeclaration();
  11495. } else if (this.expect('{')) {
  11496. primary = this.object();
  11497. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11498. primary = copy(this.constants[this.consume().text]);
  11499. } else if (this.peek().identifier) {
  11500. primary = this.identifier();
  11501. } else if (this.peek().constant) {
  11502. primary = this.constant();
  11503. } else {
  11504. this.throwError('not a primary expression', this.peek());
  11505. }
  11506. var next;
  11507. while ((next = this.expect('(', '[', '.'))) {
  11508. if (next.text === '(') {
  11509. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11510. this.consume(')');
  11511. } else if (next.text === '[') {
  11512. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11513. this.consume(']');
  11514. } else if (next.text === '.') {
  11515. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11516. } else {
  11517. this.throwError('IMPOSSIBLE');
  11518. }
  11519. }
  11520. return primary;
  11521. },
  11522. filter: function(baseExpression) {
  11523. var args = [baseExpression];
  11524. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11525. while (this.expect(':')) {
  11526. args.push(this.expression());
  11527. }
  11528. return result;
  11529. },
  11530. parseArguments: function() {
  11531. var args = [];
  11532. if (this.peekToken().text !== ')') {
  11533. do {
  11534. args.push(this.expression());
  11535. } while (this.expect(','));
  11536. }
  11537. return args;
  11538. },
  11539. identifier: function() {
  11540. var token = this.consume();
  11541. if (!token.identifier) {
  11542. this.throwError('is not a valid identifier', token);
  11543. }
  11544. return { type: AST.Identifier, name: token.text };
  11545. },
  11546. constant: function() {
  11547. // TODO check that it is a constant
  11548. return { type: AST.Literal, value: this.consume().value };
  11549. },
  11550. arrayDeclaration: function() {
  11551. var elements = [];
  11552. if (this.peekToken().text !== ']') {
  11553. do {
  11554. if (this.peek(']')) {
  11555. // Support trailing commas per ES5.1.
  11556. break;
  11557. }
  11558. elements.push(this.expression());
  11559. } while (this.expect(','));
  11560. }
  11561. this.consume(']');
  11562. return { type: AST.ArrayExpression, elements: elements };
  11563. },
  11564. object: function() {
  11565. var properties = [], property;
  11566. if (this.peekToken().text !== '}') {
  11567. do {
  11568. if (this.peek('}')) {
  11569. // Support trailing commas per ES5.1.
  11570. break;
  11571. }
  11572. property = {type: AST.Property, kind: 'init'};
  11573. if (this.peek().constant) {
  11574. property.key = this.constant();
  11575. } else if (this.peek().identifier) {
  11576. property.key = this.identifier();
  11577. } else {
  11578. this.throwError("invalid key", this.peek());
  11579. }
  11580. this.consume(':');
  11581. property.value = this.expression();
  11582. properties.push(property);
  11583. } while (this.expect(','));
  11584. }
  11585. this.consume('}');
  11586. return {type: AST.ObjectExpression, properties: properties };
  11587. },
  11588. throwError: function(msg, token) {
  11589. throw $parseMinErr('syntax',
  11590. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11591. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11592. },
  11593. consume: function(e1) {
  11594. if (this.tokens.length === 0) {
  11595. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11596. }
  11597. var token = this.expect(e1);
  11598. if (!token) {
  11599. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11600. }
  11601. return token;
  11602. },
  11603. peekToken: function() {
  11604. if (this.tokens.length === 0) {
  11605. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11606. }
  11607. return this.tokens[0];
  11608. },
  11609. peek: function(e1, e2, e3, e4) {
  11610. return this.peekAhead(0, e1, e2, e3, e4);
  11611. },
  11612. peekAhead: function(i, e1, e2, e3, e4) {
  11613. if (this.tokens.length > i) {
  11614. var token = this.tokens[i];
  11615. var t = token.text;
  11616. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11617. (!e1 && !e2 && !e3 && !e4)) {
  11618. return token;
  11619. }
  11620. }
  11621. return false;
  11622. },
  11623. expect: function(e1, e2, e3, e4) {
  11624. var token = this.peek(e1, e2, e3, e4);
  11625. if (token) {
  11626. this.tokens.shift();
  11627. return token;
  11628. }
  11629. return false;
  11630. },
  11631. /* `undefined` is not a constant, it is an identifier,
  11632. * but using it as an identifier is not supported
  11633. */
  11634. constants: {
  11635. 'true': { type: AST.Literal, value: true },
  11636. 'false': { type: AST.Literal, value: false },
  11637. 'null': { type: AST.Literal, value: null },
  11638. 'undefined': {type: AST.Literal, value: undefined },
  11639. 'this': {type: AST.ThisExpression }
  11640. }
  11641. };
  11642. function ifDefined(v, d) {
  11643. return typeof v !== 'undefined' ? v : d;
  11644. }
  11645. function plusFn(l, r) {
  11646. if (typeof l === 'undefined') return r;
  11647. if (typeof r === 'undefined') return l;
  11648. return l + r;
  11649. }
  11650. function isStateless($filter, filterName) {
  11651. var fn = $filter(filterName);
  11652. return !fn.$stateful;
  11653. }
  11654. function findConstantAndWatchExpressions(ast, $filter) {
  11655. var allConstants;
  11656. var argsToWatch;
  11657. switch (ast.type) {
  11658. case AST.Program:
  11659. allConstants = true;
  11660. forEach(ast.body, function(expr) {
  11661. findConstantAndWatchExpressions(expr.expression, $filter);
  11662. allConstants = allConstants && expr.expression.constant;
  11663. });
  11664. ast.constant = allConstants;
  11665. break;
  11666. case AST.Literal:
  11667. ast.constant = true;
  11668. ast.toWatch = [];
  11669. break;
  11670. case AST.UnaryExpression:
  11671. findConstantAndWatchExpressions(ast.argument, $filter);
  11672. ast.constant = ast.argument.constant;
  11673. ast.toWatch = ast.argument.toWatch;
  11674. break;
  11675. case AST.BinaryExpression:
  11676. findConstantAndWatchExpressions(ast.left, $filter);
  11677. findConstantAndWatchExpressions(ast.right, $filter);
  11678. ast.constant = ast.left.constant && ast.right.constant;
  11679. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11680. break;
  11681. case AST.LogicalExpression:
  11682. findConstantAndWatchExpressions(ast.left, $filter);
  11683. findConstantAndWatchExpressions(ast.right, $filter);
  11684. ast.constant = ast.left.constant && ast.right.constant;
  11685. ast.toWatch = ast.constant ? [] : [ast];
  11686. break;
  11687. case AST.ConditionalExpression:
  11688. findConstantAndWatchExpressions(ast.test, $filter);
  11689. findConstantAndWatchExpressions(ast.alternate, $filter);
  11690. findConstantAndWatchExpressions(ast.consequent, $filter);
  11691. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11692. ast.toWatch = ast.constant ? [] : [ast];
  11693. break;
  11694. case AST.Identifier:
  11695. ast.constant = false;
  11696. ast.toWatch = [ast];
  11697. break;
  11698. case AST.MemberExpression:
  11699. findConstantAndWatchExpressions(ast.object, $filter);
  11700. if (ast.computed) {
  11701. findConstantAndWatchExpressions(ast.property, $filter);
  11702. }
  11703. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11704. ast.toWatch = [ast];
  11705. break;
  11706. case AST.CallExpression:
  11707. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11708. argsToWatch = [];
  11709. forEach(ast.arguments, function(expr) {
  11710. findConstantAndWatchExpressions(expr, $filter);
  11711. allConstants = allConstants && expr.constant;
  11712. if (!expr.constant) {
  11713. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11714. }
  11715. });
  11716. ast.constant = allConstants;
  11717. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11718. break;
  11719. case AST.AssignmentExpression:
  11720. findConstantAndWatchExpressions(ast.left, $filter);
  11721. findConstantAndWatchExpressions(ast.right, $filter);
  11722. ast.constant = ast.left.constant && ast.right.constant;
  11723. ast.toWatch = [ast];
  11724. break;
  11725. case AST.ArrayExpression:
  11726. allConstants = true;
  11727. argsToWatch = [];
  11728. forEach(ast.elements, function(expr) {
  11729. findConstantAndWatchExpressions(expr, $filter);
  11730. allConstants = allConstants && expr.constant;
  11731. if (!expr.constant) {
  11732. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11733. }
  11734. });
  11735. ast.constant = allConstants;
  11736. ast.toWatch = argsToWatch;
  11737. break;
  11738. case AST.ObjectExpression:
  11739. allConstants = true;
  11740. argsToWatch = [];
  11741. forEach(ast.properties, function(property) {
  11742. findConstantAndWatchExpressions(property.value, $filter);
  11743. allConstants = allConstants && property.value.constant;
  11744. if (!property.value.constant) {
  11745. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11746. }
  11747. });
  11748. ast.constant = allConstants;
  11749. ast.toWatch = argsToWatch;
  11750. break;
  11751. case AST.ThisExpression:
  11752. ast.constant = false;
  11753. ast.toWatch = [];
  11754. break;
  11755. }
  11756. }
  11757. function getInputs(body) {
  11758. if (body.length != 1) return;
  11759. var lastExpression = body[0].expression;
  11760. var candidate = lastExpression.toWatch;
  11761. if (candidate.length !== 1) return candidate;
  11762. return candidate[0] !== lastExpression ? candidate : undefined;
  11763. }
  11764. function isAssignable(ast) {
  11765. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11766. }
  11767. function assignableAST(ast) {
  11768. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11769. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11770. }
  11771. }
  11772. function isLiteral(ast) {
  11773. return ast.body.length === 0 ||
  11774. ast.body.length === 1 && (
  11775. ast.body[0].expression.type === AST.Literal ||
  11776. ast.body[0].expression.type === AST.ArrayExpression ||
  11777. ast.body[0].expression.type === AST.ObjectExpression);
  11778. }
  11779. function isConstant(ast) {
  11780. return ast.constant;
  11781. }
  11782. function ASTCompiler(astBuilder, $filter) {
  11783. this.astBuilder = astBuilder;
  11784. this.$filter = $filter;
  11785. }
  11786. ASTCompiler.prototype = {
  11787. compile: function(expression, expensiveChecks) {
  11788. var self = this;
  11789. var ast = this.astBuilder.ast(expression);
  11790. this.state = {
  11791. nextId: 0,
  11792. filters: {},
  11793. expensiveChecks: expensiveChecks,
  11794. fn: {vars: [], body: [], own: {}},
  11795. assign: {vars: [], body: [], own: {}},
  11796. inputs: []
  11797. };
  11798. findConstantAndWatchExpressions(ast, self.$filter);
  11799. var extra = '';
  11800. var assignable;
  11801. this.stage = 'assign';
  11802. if ((assignable = assignableAST(ast))) {
  11803. this.state.computing = 'assign';
  11804. var result = this.nextId();
  11805. this.recurse(assignable, result);
  11806. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11807. }
  11808. var toWatch = getInputs(ast.body);
  11809. self.stage = 'inputs';
  11810. forEach(toWatch, function(watch, key) {
  11811. var fnKey = 'fn' + key;
  11812. self.state[fnKey] = {vars: [], body: [], own: {}};
  11813. self.state.computing = fnKey;
  11814. var intoId = self.nextId();
  11815. self.recurse(watch, intoId);
  11816. self.return_(intoId);
  11817. self.state.inputs.push(fnKey);
  11818. watch.watchId = key;
  11819. });
  11820. this.state.computing = 'fn';
  11821. this.stage = 'main';
  11822. this.recurse(ast);
  11823. var fnString =
  11824. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11825. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11826. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11827. this.filterPrefix() +
  11828. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11829. extra +
  11830. this.watchFns() +
  11831. 'return fn;';
  11832. /* jshint -W054 */
  11833. var fn = (new Function('$filter',
  11834. 'ensureSafeMemberName',
  11835. 'ensureSafeObject',
  11836. 'ensureSafeFunction',
  11837. 'ifDefined',
  11838. 'plus',
  11839. 'text',
  11840. fnString))(
  11841. this.$filter,
  11842. ensureSafeMemberName,
  11843. ensureSafeObject,
  11844. ensureSafeFunction,
  11845. ifDefined,
  11846. plusFn,
  11847. expression);
  11848. /* jshint +W054 */
  11849. this.state = this.stage = undefined;
  11850. fn.literal = isLiteral(ast);
  11851. fn.constant = isConstant(ast);
  11852. return fn;
  11853. },
  11854. USE: 'use',
  11855. STRICT: 'strict',
  11856. watchFns: function() {
  11857. var result = [];
  11858. var fns = this.state.inputs;
  11859. var self = this;
  11860. forEach(fns, function(name) {
  11861. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11862. });
  11863. if (fns.length) {
  11864. result.push('fn.inputs=[' + fns.join(',') + '];');
  11865. }
  11866. return result.join('');
  11867. },
  11868. generateFunction: function(name, params) {
  11869. return 'function(' + params + '){' +
  11870. this.varsPrefix(name) +
  11871. this.body(name) +
  11872. '};';
  11873. },
  11874. filterPrefix: function() {
  11875. var parts = [];
  11876. var self = this;
  11877. forEach(this.state.filters, function(id, filter) {
  11878. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  11879. });
  11880. if (parts.length) return 'var ' + parts.join(',') + ';';
  11881. return '';
  11882. },
  11883. varsPrefix: function(section) {
  11884. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  11885. },
  11886. body: function(section) {
  11887. return this.state[section].body.join('');
  11888. },
  11889. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  11890. var left, right, self = this, args, expression;
  11891. recursionFn = recursionFn || noop;
  11892. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  11893. intoId = intoId || this.nextId();
  11894. this.if_('i',
  11895. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  11896. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  11897. );
  11898. return;
  11899. }
  11900. switch (ast.type) {
  11901. case AST.Program:
  11902. forEach(ast.body, function(expression, pos) {
  11903. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  11904. if (pos !== ast.body.length - 1) {
  11905. self.current().body.push(right, ';');
  11906. } else {
  11907. self.return_(right);
  11908. }
  11909. });
  11910. break;
  11911. case AST.Literal:
  11912. expression = this.escape(ast.value);
  11913. this.assign(intoId, expression);
  11914. recursionFn(expression);
  11915. break;
  11916. case AST.UnaryExpression:
  11917. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  11918. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  11919. this.assign(intoId, expression);
  11920. recursionFn(expression);
  11921. break;
  11922. case AST.BinaryExpression:
  11923. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  11924. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  11925. if (ast.operator === '+') {
  11926. expression = this.plus(left, right);
  11927. } else if (ast.operator === '-') {
  11928. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  11929. } else {
  11930. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  11931. }
  11932. this.assign(intoId, expression);
  11933. recursionFn(expression);
  11934. break;
  11935. case AST.LogicalExpression:
  11936. intoId = intoId || this.nextId();
  11937. self.recurse(ast.left, intoId);
  11938. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  11939. recursionFn(intoId);
  11940. break;
  11941. case AST.ConditionalExpression:
  11942. intoId = intoId || this.nextId();
  11943. self.recurse(ast.test, intoId);
  11944. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  11945. recursionFn(intoId);
  11946. break;
  11947. case AST.Identifier:
  11948. intoId = intoId || this.nextId();
  11949. if (nameId) {
  11950. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  11951. nameId.computed = false;
  11952. nameId.name = ast.name;
  11953. }
  11954. ensureSafeMemberName(ast.name);
  11955. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  11956. function() {
  11957. self.if_(self.stage === 'inputs' || 's', function() {
  11958. if (create && create !== 1) {
  11959. self.if_(
  11960. self.not(self.nonComputedMember('s', ast.name)),
  11961. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  11962. }
  11963. self.assign(intoId, self.nonComputedMember('s', ast.name));
  11964. });
  11965. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  11966. );
  11967. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  11968. self.addEnsureSafeObject(intoId);
  11969. }
  11970. recursionFn(intoId);
  11971. break;
  11972. case AST.MemberExpression:
  11973. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  11974. intoId = intoId || this.nextId();
  11975. self.recurse(ast.object, left, undefined, function() {
  11976. self.if_(self.notNull(left), function() {
  11977. if (ast.computed) {
  11978. right = self.nextId();
  11979. self.recurse(ast.property, right);
  11980. self.addEnsureSafeMemberName(right);
  11981. if (create && create !== 1) {
  11982. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  11983. }
  11984. expression = self.ensureSafeObject(self.computedMember(left, right));
  11985. self.assign(intoId, expression);
  11986. if (nameId) {
  11987. nameId.computed = true;
  11988. nameId.name = right;
  11989. }
  11990. } else {
  11991. ensureSafeMemberName(ast.property.name);
  11992. if (create && create !== 1) {
  11993. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  11994. }
  11995. expression = self.nonComputedMember(left, ast.property.name);
  11996. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  11997. expression = self.ensureSafeObject(expression);
  11998. }
  11999. self.assign(intoId, expression);
  12000. if (nameId) {
  12001. nameId.computed = false;
  12002. nameId.name = ast.property.name;
  12003. }
  12004. }
  12005. }, function() {
  12006. self.assign(intoId, 'undefined');
  12007. });
  12008. recursionFn(intoId);
  12009. }, !!create);
  12010. break;
  12011. case AST.CallExpression:
  12012. intoId = intoId || this.nextId();
  12013. if (ast.filter) {
  12014. right = self.filter(ast.callee.name);
  12015. args = [];
  12016. forEach(ast.arguments, function(expr) {
  12017. var argument = self.nextId();
  12018. self.recurse(expr, argument);
  12019. args.push(argument);
  12020. });
  12021. expression = right + '(' + args.join(',') + ')';
  12022. self.assign(intoId, expression);
  12023. recursionFn(intoId);
  12024. } else {
  12025. right = self.nextId();
  12026. left = {};
  12027. args = [];
  12028. self.recurse(ast.callee, right, left, function() {
  12029. self.if_(self.notNull(right), function() {
  12030. self.addEnsureSafeFunction(right);
  12031. forEach(ast.arguments, function(expr) {
  12032. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12033. args.push(self.ensureSafeObject(argument));
  12034. });
  12035. });
  12036. if (left.name) {
  12037. if (!self.state.expensiveChecks) {
  12038. self.addEnsureSafeObject(left.context);
  12039. }
  12040. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12041. } else {
  12042. expression = right + '(' + args.join(',') + ')';
  12043. }
  12044. expression = self.ensureSafeObject(expression);
  12045. self.assign(intoId, expression);
  12046. }, function() {
  12047. self.assign(intoId, 'undefined');
  12048. });
  12049. recursionFn(intoId);
  12050. });
  12051. }
  12052. break;
  12053. case AST.AssignmentExpression:
  12054. right = this.nextId();
  12055. left = {};
  12056. if (!isAssignable(ast.left)) {
  12057. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12058. }
  12059. this.recurse(ast.left, undefined, left, function() {
  12060. self.if_(self.notNull(left.context), function() {
  12061. self.recurse(ast.right, right);
  12062. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12063. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12064. self.assign(intoId, expression);
  12065. recursionFn(intoId || expression);
  12066. });
  12067. }, 1);
  12068. break;
  12069. case AST.ArrayExpression:
  12070. args = [];
  12071. forEach(ast.elements, function(expr) {
  12072. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12073. args.push(argument);
  12074. });
  12075. });
  12076. expression = '[' + args.join(',') + ']';
  12077. this.assign(intoId, expression);
  12078. recursionFn(expression);
  12079. break;
  12080. case AST.ObjectExpression:
  12081. args = [];
  12082. forEach(ast.properties, function(property) {
  12083. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12084. args.push(self.escape(
  12085. property.key.type === AST.Identifier ? property.key.name :
  12086. ('' + property.key.value)) +
  12087. ':' + expr);
  12088. });
  12089. });
  12090. expression = '{' + args.join(',') + '}';
  12091. this.assign(intoId, expression);
  12092. recursionFn(expression);
  12093. break;
  12094. case AST.ThisExpression:
  12095. this.assign(intoId, 's');
  12096. recursionFn('s');
  12097. break;
  12098. case AST.NGValueParameter:
  12099. this.assign(intoId, 'v');
  12100. recursionFn('v');
  12101. break;
  12102. }
  12103. },
  12104. getHasOwnProperty: function(element, property) {
  12105. var key = element + '.' + property;
  12106. var own = this.current().own;
  12107. if (!own.hasOwnProperty(key)) {
  12108. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12109. }
  12110. return own[key];
  12111. },
  12112. assign: function(id, value) {
  12113. if (!id) return;
  12114. this.current().body.push(id, '=', value, ';');
  12115. return id;
  12116. },
  12117. filter: function(filterName) {
  12118. if (!this.state.filters.hasOwnProperty(filterName)) {
  12119. this.state.filters[filterName] = this.nextId(true);
  12120. }
  12121. return this.state.filters[filterName];
  12122. },
  12123. ifDefined: function(id, defaultValue) {
  12124. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12125. },
  12126. plus: function(left, right) {
  12127. return 'plus(' + left + ',' + right + ')';
  12128. },
  12129. return_: function(id) {
  12130. this.current().body.push('return ', id, ';');
  12131. },
  12132. if_: function(test, alternate, consequent) {
  12133. if (test === true) {
  12134. alternate();
  12135. } else {
  12136. var body = this.current().body;
  12137. body.push('if(', test, '){');
  12138. alternate();
  12139. body.push('}');
  12140. if (consequent) {
  12141. body.push('else{');
  12142. consequent();
  12143. body.push('}');
  12144. }
  12145. }
  12146. },
  12147. not: function(expression) {
  12148. return '!(' + expression + ')';
  12149. },
  12150. notNull: function(expression) {
  12151. return expression + '!=null';
  12152. },
  12153. nonComputedMember: function(left, right) {
  12154. return left + '.' + right;
  12155. },
  12156. computedMember: function(left, right) {
  12157. return left + '[' + right + ']';
  12158. },
  12159. member: function(left, right, computed) {
  12160. if (computed) return this.computedMember(left, right);
  12161. return this.nonComputedMember(left, right);
  12162. },
  12163. addEnsureSafeObject: function(item) {
  12164. this.current().body.push(this.ensureSafeObject(item), ';');
  12165. },
  12166. addEnsureSafeMemberName: function(item) {
  12167. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12168. },
  12169. addEnsureSafeFunction: function(item) {
  12170. this.current().body.push(this.ensureSafeFunction(item), ';');
  12171. },
  12172. ensureSafeObject: function(item) {
  12173. return 'ensureSafeObject(' + item + ',text)';
  12174. },
  12175. ensureSafeMemberName: function(item) {
  12176. return 'ensureSafeMemberName(' + item + ',text)';
  12177. },
  12178. ensureSafeFunction: function(item) {
  12179. return 'ensureSafeFunction(' + item + ',text)';
  12180. },
  12181. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12182. var self = this;
  12183. return function() {
  12184. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12185. };
  12186. },
  12187. lazyAssign: function(id, value) {
  12188. var self = this;
  12189. return function() {
  12190. self.assign(id, value);
  12191. };
  12192. },
  12193. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12194. stringEscapeFn: function(c) {
  12195. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12196. },
  12197. escape: function(value) {
  12198. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12199. if (isNumber(value)) return value.toString();
  12200. if (value === true) return 'true';
  12201. if (value === false) return 'false';
  12202. if (value === null) return 'null';
  12203. if (typeof value === 'undefined') return 'undefined';
  12204. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12205. },
  12206. nextId: function(skip, init) {
  12207. var id = 'v' + (this.state.nextId++);
  12208. if (!skip) {
  12209. this.current().vars.push(id + (init ? '=' + init : ''));
  12210. }
  12211. return id;
  12212. },
  12213. current: function() {
  12214. return this.state[this.state.computing];
  12215. }
  12216. };
  12217. function ASTInterpreter(astBuilder, $filter) {
  12218. this.astBuilder = astBuilder;
  12219. this.$filter = $filter;
  12220. }
  12221. ASTInterpreter.prototype = {
  12222. compile: function(expression, expensiveChecks) {
  12223. var self = this;
  12224. var ast = this.astBuilder.ast(expression);
  12225. this.expression = expression;
  12226. this.expensiveChecks = expensiveChecks;
  12227. findConstantAndWatchExpressions(ast, self.$filter);
  12228. var assignable;
  12229. var assign;
  12230. if ((assignable = assignableAST(ast))) {
  12231. assign = this.recurse(assignable);
  12232. }
  12233. var toWatch = getInputs(ast.body);
  12234. var inputs;
  12235. if (toWatch) {
  12236. inputs = [];
  12237. forEach(toWatch, function(watch, key) {
  12238. var input = self.recurse(watch);
  12239. watch.input = input;
  12240. inputs.push(input);
  12241. watch.watchId = key;
  12242. });
  12243. }
  12244. var expressions = [];
  12245. forEach(ast.body, function(expression) {
  12246. expressions.push(self.recurse(expression.expression));
  12247. });
  12248. var fn = ast.body.length === 0 ? function() {} :
  12249. ast.body.length === 1 ? expressions[0] :
  12250. function(scope, locals) {
  12251. var lastValue;
  12252. forEach(expressions, function(exp) {
  12253. lastValue = exp(scope, locals);
  12254. });
  12255. return lastValue;
  12256. };
  12257. if (assign) {
  12258. fn.assign = function(scope, value, locals) {
  12259. return assign(scope, locals, value);
  12260. };
  12261. }
  12262. if (inputs) {
  12263. fn.inputs = inputs;
  12264. }
  12265. fn.literal = isLiteral(ast);
  12266. fn.constant = isConstant(ast);
  12267. return fn;
  12268. },
  12269. recurse: function(ast, context, create) {
  12270. var left, right, self = this, args, expression;
  12271. if (ast.input) {
  12272. return this.inputs(ast.input, ast.watchId);
  12273. }
  12274. switch (ast.type) {
  12275. case AST.Literal:
  12276. return this.value(ast.value, context);
  12277. case AST.UnaryExpression:
  12278. right = this.recurse(ast.argument);
  12279. return this['unary' + ast.operator](right, context);
  12280. case AST.BinaryExpression:
  12281. left = this.recurse(ast.left);
  12282. right = this.recurse(ast.right);
  12283. return this['binary' + ast.operator](left, right, context);
  12284. case AST.LogicalExpression:
  12285. left = this.recurse(ast.left);
  12286. right = this.recurse(ast.right);
  12287. return this['binary' + ast.operator](left, right, context);
  12288. case AST.ConditionalExpression:
  12289. return this['ternary?:'](
  12290. this.recurse(ast.test),
  12291. this.recurse(ast.alternate),
  12292. this.recurse(ast.consequent),
  12293. context
  12294. );
  12295. case AST.Identifier:
  12296. ensureSafeMemberName(ast.name, self.expression);
  12297. return self.identifier(ast.name,
  12298. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12299. context, create, self.expression);
  12300. case AST.MemberExpression:
  12301. left = this.recurse(ast.object, false, !!create);
  12302. if (!ast.computed) {
  12303. ensureSafeMemberName(ast.property.name, self.expression);
  12304. right = ast.property.name;
  12305. }
  12306. if (ast.computed) right = this.recurse(ast.property);
  12307. return ast.computed ?
  12308. this.computedMember(left, right, context, create, self.expression) :
  12309. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12310. case AST.CallExpression:
  12311. args = [];
  12312. forEach(ast.arguments, function(expr) {
  12313. args.push(self.recurse(expr));
  12314. });
  12315. if (ast.filter) right = this.$filter(ast.callee.name);
  12316. if (!ast.filter) right = this.recurse(ast.callee, true);
  12317. return ast.filter ?
  12318. function(scope, locals, assign, inputs) {
  12319. var values = [];
  12320. for (var i = 0; i < args.length; ++i) {
  12321. values.push(args[i](scope, locals, assign, inputs));
  12322. }
  12323. var value = right.apply(undefined, values, inputs);
  12324. return context ? {context: undefined, name: undefined, value: value} : value;
  12325. } :
  12326. function(scope, locals, assign, inputs) {
  12327. var rhs = right(scope, locals, assign, inputs);
  12328. var value;
  12329. if (rhs.value != null) {
  12330. ensureSafeObject(rhs.context, self.expression);
  12331. ensureSafeFunction(rhs.value, self.expression);
  12332. var values = [];
  12333. for (var i = 0; i < args.length; ++i) {
  12334. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12335. }
  12336. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12337. }
  12338. return context ? {value: value} : value;
  12339. };
  12340. case AST.AssignmentExpression:
  12341. left = this.recurse(ast.left, true, 1);
  12342. right = this.recurse(ast.right);
  12343. return function(scope, locals, assign, inputs) {
  12344. var lhs = left(scope, locals, assign, inputs);
  12345. var rhs = right(scope, locals, assign, inputs);
  12346. ensureSafeObject(lhs.value, self.expression);
  12347. lhs.context[lhs.name] = rhs;
  12348. return context ? {value: rhs} : rhs;
  12349. };
  12350. case AST.ArrayExpression:
  12351. args = [];
  12352. forEach(ast.elements, function(expr) {
  12353. args.push(self.recurse(expr));
  12354. });
  12355. return function(scope, locals, assign, inputs) {
  12356. var value = [];
  12357. for (var i = 0; i < args.length; ++i) {
  12358. value.push(args[i](scope, locals, assign, inputs));
  12359. }
  12360. return context ? {value: value} : value;
  12361. };
  12362. case AST.ObjectExpression:
  12363. args = [];
  12364. forEach(ast.properties, function(property) {
  12365. args.push({key: property.key.type === AST.Identifier ?
  12366. property.key.name :
  12367. ('' + property.key.value),
  12368. value: self.recurse(property.value)
  12369. });
  12370. });
  12371. return function(scope, locals, assign, inputs) {
  12372. var value = {};
  12373. for (var i = 0; i < args.length; ++i) {
  12374. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12375. }
  12376. return context ? {value: value} : value;
  12377. };
  12378. case AST.ThisExpression:
  12379. return function(scope) {
  12380. return context ? {value: scope} : scope;
  12381. };
  12382. case AST.NGValueParameter:
  12383. return function(scope, locals, assign, inputs) {
  12384. return context ? {value: assign} : assign;
  12385. };
  12386. }
  12387. },
  12388. 'unary+': function(argument, context) {
  12389. return function(scope, locals, assign, inputs) {
  12390. var arg = argument(scope, locals, assign, inputs);
  12391. if (isDefined(arg)) {
  12392. arg = +arg;
  12393. } else {
  12394. arg = 0;
  12395. }
  12396. return context ? {value: arg} : arg;
  12397. };
  12398. },
  12399. 'unary-': function(argument, context) {
  12400. return function(scope, locals, assign, inputs) {
  12401. var arg = argument(scope, locals, assign, inputs);
  12402. if (isDefined(arg)) {
  12403. arg = -arg;
  12404. } else {
  12405. arg = 0;
  12406. }
  12407. return context ? {value: arg} : arg;
  12408. };
  12409. },
  12410. 'unary!': function(argument, context) {
  12411. return function(scope, locals, assign, inputs) {
  12412. var arg = !argument(scope, locals, assign, inputs);
  12413. return context ? {value: arg} : arg;
  12414. };
  12415. },
  12416. 'binary+': function(left, right, context) {
  12417. return function(scope, locals, assign, inputs) {
  12418. var lhs = left(scope, locals, assign, inputs);
  12419. var rhs = right(scope, locals, assign, inputs);
  12420. var arg = plusFn(lhs, rhs);
  12421. return context ? {value: arg} : arg;
  12422. };
  12423. },
  12424. 'binary-': function(left, right, context) {
  12425. return function(scope, locals, assign, inputs) {
  12426. var lhs = left(scope, locals, assign, inputs);
  12427. var rhs = right(scope, locals, assign, inputs);
  12428. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12429. return context ? {value: arg} : arg;
  12430. };
  12431. },
  12432. 'binary*': function(left, right, context) {
  12433. return function(scope, locals, assign, inputs) {
  12434. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12435. return context ? {value: arg} : arg;
  12436. };
  12437. },
  12438. 'binary/': function(left, right, context) {
  12439. return function(scope, locals, assign, inputs) {
  12440. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12441. return context ? {value: arg} : arg;
  12442. };
  12443. },
  12444. 'binary%': function(left, right, context) {
  12445. return function(scope, locals, assign, inputs) {
  12446. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12447. return context ? {value: arg} : arg;
  12448. };
  12449. },
  12450. 'binary===': function(left, right, context) {
  12451. return function(scope, locals, assign, inputs) {
  12452. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12453. return context ? {value: arg} : arg;
  12454. };
  12455. },
  12456. 'binary!==': function(left, right, context) {
  12457. return function(scope, locals, assign, inputs) {
  12458. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12459. return context ? {value: arg} : arg;
  12460. };
  12461. },
  12462. 'binary==': function(left, right, context) {
  12463. return function(scope, locals, assign, inputs) {
  12464. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12465. return context ? {value: arg} : arg;
  12466. };
  12467. },
  12468. 'binary!=': function(left, right, context) {
  12469. return function(scope, locals, assign, inputs) {
  12470. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12471. return context ? {value: arg} : arg;
  12472. };
  12473. },
  12474. 'binary<': function(left, right, context) {
  12475. return function(scope, locals, assign, inputs) {
  12476. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12477. return context ? {value: arg} : arg;
  12478. };
  12479. },
  12480. 'binary>': function(left, right, context) {
  12481. return function(scope, locals, assign, inputs) {
  12482. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12483. return context ? {value: arg} : arg;
  12484. };
  12485. },
  12486. 'binary<=': function(left, right, context) {
  12487. return function(scope, locals, assign, inputs) {
  12488. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12489. return context ? {value: arg} : arg;
  12490. };
  12491. },
  12492. 'binary>=': function(left, right, context) {
  12493. return function(scope, locals, assign, inputs) {
  12494. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12495. return context ? {value: arg} : arg;
  12496. };
  12497. },
  12498. 'binary&&': function(left, right, context) {
  12499. return function(scope, locals, assign, inputs) {
  12500. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12501. return context ? {value: arg} : arg;
  12502. };
  12503. },
  12504. 'binary||': function(left, right, context) {
  12505. return function(scope, locals, assign, inputs) {
  12506. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12507. return context ? {value: arg} : arg;
  12508. };
  12509. },
  12510. 'ternary?:': function(test, alternate, consequent, context) {
  12511. return function(scope, locals, assign, inputs) {
  12512. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12513. return context ? {value: arg} : arg;
  12514. };
  12515. },
  12516. value: function(value, context) {
  12517. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12518. },
  12519. identifier: function(name, expensiveChecks, context, create, expression) {
  12520. return function(scope, locals, assign, inputs) {
  12521. var base = locals && (name in locals) ? locals : scope;
  12522. if (create && create !== 1 && base && !(base[name])) {
  12523. base[name] = {};
  12524. }
  12525. var value = base ? base[name] : undefined;
  12526. if (expensiveChecks) {
  12527. ensureSafeObject(value, expression);
  12528. }
  12529. if (context) {
  12530. return {context: base, name: name, value: value};
  12531. } else {
  12532. return value;
  12533. }
  12534. };
  12535. },
  12536. computedMember: function(left, right, context, create, expression) {
  12537. return function(scope, locals, assign, inputs) {
  12538. var lhs = left(scope, locals, assign, inputs);
  12539. var rhs;
  12540. var value;
  12541. if (lhs != null) {
  12542. rhs = right(scope, locals, assign, inputs);
  12543. ensureSafeMemberName(rhs, expression);
  12544. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12545. lhs[rhs] = {};
  12546. }
  12547. value = lhs[rhs];
  12548. ensureSafeObject(value, expression);
  12549. }
  12550. if (context) {
  12551. return {context: lhs, name: rhs, value: value};
  12552. } else {
  12553. return value;
  12554. }
  12555. };
  12556. },
  12557. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12558. return function(scope, locals, assign, inputs) {
  12559. var lhs = left(scope, locals, assign, inputs);
  12560. if (create && create !== 1 && lhs && !(lhs[right])) {
  12561. lhs[right] = {};
  12562. }
  12563. var value = lhs != null ? lhs[right] : undefined;
  12564. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12565. ensureSafeObject(value, expression);
  12566. }
  12567. if (context) {
  12568. return {context: lhs, name: right, value: value};
  12569. } else {
  12570. return value;
  12571. }
  12572. };
  12573. },
  12574. inputs: function(input, watchId) {
  12575. return function(scope, value, locals, inputs) {
  12576. if (inputs) return inputs[watchId];
  12577. return input(scope, value, locals);
  12578. };
  12579. }
  12580. };
  12581. /**
  12582. * @constructor
  12583. */
  12584. var Parser = function(lexer, $filter, options) {
  12585. this.lexer = lexer;
  12586. this.$filter = $filter;
  12587. this.options = options;
  12588. this.ast = new AST(this.lexer);
  12589. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12590. new ASTCompiler(this.ast, $filter);
  12591. };
  12592. Parser.prototype = {
  12593. constructor: Parser,
  12594. parse: function(text) {
  12595. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12596. }
  12597. };
  12598. //////////////////////////////////////////////////
  12599. // Parser helper functions
  12600. //////////////////////////////////////////////////
  12601. function setter(obj, path, setValue, fullExp) {
  12602. ensureSafeObject(obj, fullExp);
  12603. var element = path.split('.'), key;
  12604. for (var i = 0; element.length > 1; i++) {
  12605. key = ensureSafeMemberName(element.shift(), fullExp);
  12606. var propertyObj = ensureSafeObject(obj[key], fullExp);
  12607. if (!propertyObj) {
  12608. propertyObj = {};
  12609. obj[key] = propertyObj;
  12610. }
  12611. obj = propertyObj;
  12612. }
  12613. key = ensureSafeMemberName(element.shift(), fullExp);
  12614. ensureSafeObject(obj[key], fullExp);
  12615. obj[key] = setValue;
  12616. return setValue;
  12617. }
  12618. var getterFnCacheDefault = createMap();
  12619. var getterFnCacheExpensive = createMap();
  12620. function isPossiblyDangerousMemberName(name) {
  12621. return name == 'constructor';
  12622. }
  12623. var objectValueOf = Object.prototype.valueOf;
  12624. function getValueOf(value) {
  12625. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12626. }
  12627. ///////////////////////////////////
  12628. /**
  12629. * @ngdoc service
  12630. * @name $parse
  12631. * @kind function
  12632. *
  12633. * @description
  12634. *
  12635. * Converts Angular {@link guide/expression expression} into a function.
  12636. *
  12637. * ```js
  12638. * var getter = $parse('user.name');
  12639. * var setter = getter.assign;
  12640. * var context = {user:{name:'angular'}};
  12641. * var locals = {user:{name:'local'}};
  12642. *
  12643. * expect(getter(context)).toEqual('angular');
  12644. * setter(context, 'newValue');
  12645. * expect(context.user.name).toEqual('newValue');
  12646. * expect(getter(context, locals)).toEqual('local');
  12647. * ```
  12648. *
  12649. *
  12650. * @param {string} expression String expression to compile.
  12651. * @returns {function(context, locals)} a function which represents the compiled expression:
  12652. *
  12653. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12654. * are evaluated against (typically a scope object).
  12655. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12656. * `context`.
  12657. *
  12658. * The returned function also has the following properties:
  12659. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12660. * literal.
  12661. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12662. * constant literals.
  12663. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12664. * set to a function to change its value on the given context.
  12665. *
  12666. */
  12667. /**
  12668. * @ngdoc provider
  12669. * @name $parseProvider
  12670. *
  12671. * @description
  12672. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12673. * service.
  12674. */
  12675. function $ParseProvider() {
  12676. var cacheDefault = createMap();
  12677. var cacheExpensive = createMap();
  12678. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  12679. var $parseOptions = {
  12680. csp: $sniffer.csp,
  12681. expensiveChecks: false
  12682. },
  12683. $parseOptionsExpensive = {
  12684. csp: $sniffer.csp,
  12685. expensiveChecks: true
  12686. };
  12687. return function $parse(exp, interceptorFn, expensiveChecks) {
  12688. var parsedExpression, oneTime, cacheKey;
  12689. switch (typeof exp) {
  12690. case 'string':
  12691. exp = exp.trim();
  12692. cacheKey = exp;
  12693. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12694. parsedExpression = cache[cacheKey];
  12695. if (!parsedExpression) {
  12696. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12697. oneTime = true;
  12698. exp = exp.substring(2);
  12699. }
  12700. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12701. var lexer = new Lexer(parseOptions);
  12702. var parser = new Parser(lexer, $filter, parseOptions);
  12703. parsedExpression = parser.parse(exp);
  12704. if (parsedExpression.constant) {
  12705. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12706. } else if (oneTime) {
  12707. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12708. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12709. } else if (parsedExpression.inputs) {
  12710. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12711. }
  12712. cache[cacheKey] = parsedExpression;
  12713. }
  12714. return addInterceptor(parsedExpression, interceptorFn);
  12715. case 'function':
  12716. return addInterceptor(exp, interceptorFn);
  12717. default:
  12718. return noop;
  12719. }
  12720. };
  12721. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12722. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12723. return newValue === oldValueOfValue;
  12724. }
  12725. if (typeof newValue === 'object') {
  12726. // attempt to convert the value to a primitive type
  12727. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12728. // be cheaply dirty-checked
  12729. newValue = getValueOf(newValue);
  12730. if (typeof newValue === 'object') {
  12731. // objects/arrays are not supported - deep-watching them would be too expensive
  12732. return false;
  12733. }
  12734. // fall-through to the primitive equality check
  12735. }
  12736. //Primitive or NaN
  12737. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12738. }
  12739. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12740. var inputExpressions = parsedExpression.inputs;
  12741. var lastResult;
  12742. if (inputExpressions.length === 1) {
  12743. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12744. inputExpressions = inputExpressions[0];
  12745. return scope.$watch(function expressionInputWatch(scope) {
  12746. var newInputValue = inputExpressions(scope);
  12747. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12748. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12749. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12750. }
  12751. return lastResult;
  12752. }, listener, objectEquality, prettyPrintExpression);
  12753. }
  12754. var oldInputValueOfValues = [];
  12755. var oldInputValues = [];
  12756. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12757. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12758. oldInputValues[i] = null;
  12759. }
  12760. return scope.$watch(function expressionInputsWatch(scope) {
  12761. var changed = false;
  12762. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12763. var newInputValue = inputExpressions[i](scope);
  12764. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12765. oldInputValues[i] = newInputValue;
  12766. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12767. }
  12768. }
  12769. if (changed) {
  12770. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12771. }
  12772. return lastResult;
  12773. }, listener, objectEquality, prettyPrintExpression);
  12774. }
  12775. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12776. var unwatch, lastValue;
  12777. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12778. return parsedExpression(scope);
  12779. }, function oneTimeListener(value, old, scope) {
  12780. lastValue = value;
  12781. if (isFunction(listener)) {
  12782. listener.apply(this, arguments);
  12783. }
  12784. if (isDefined(value)) {
  12785. scope.$$postDigest(function() {
  12786. if (isDefined(lastValue)) {
  12787. unwatch();
  12788. }
  12789. });
  12790. }
  12791. }, objectEquality);
  12792. }
  12793. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12794. var unwatch, lastValue;
  12795. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12796. return parsedExpression(scope);
  12797. }, function oneTimeListener(value, old, scope) {
  12798. lastValue = value;
  12799. if (isFunction(listener)) {
  12800. listener.call(this, value, old, scope);
  12801. }
  12802. if (isAllDefined(value)) {
  12803. scope.$$postDigest(function() {
  12804. if (isAllDefined(lastValue)) unwatch();
  12805. });
  12806. }
  12807. }, objectEquality);
  12808. function isAllDefined(value) {
  12809. var allDefined = true;
  12810. forEach(value, function(val) {
  12811. if (!isDefined(val)) allDefined = false;
  12812. });
  12813. return allDefined;
  12814. }
  12815. }
  12816. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12817. var unwatch;
  12818. return unwatch = scope.$watch(function constantWatch(scope) {
  12819. return parsedExpression(scope);
  12820. }, function constantListener(value, old, scope) {
  12821. if (isFunction(listener)) {
  12822. listener.apply(this, arguments);
  12823. }
  12824. unwatch();
  12825. }, objectEquality);
  12826. }
  12827. function addInterceptor(parsedExpression, interceptorFn) {
  12828. if (!interceptorFn) return parsedExpression;
  12829. var watchDelegate = parsedExpression.$$watchDelegate;
  12830. var regularWatch =
  12831. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12832. watchDelegate !== oneTimeWatchDelegate;
  12833. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12834. var value = parsedExpression(scope, locals, assign, inputs);
  12835. return interceptorFn(value, scope, locals);
  12836. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12837. var value = parsedExpression(scope, locals, assign, inputs);
  12838. var result = interceptorFn(value, scope, locals);
  12839. // we only return the interceptor's result if the
  12840. // initial value is defined (for bind-once)
  12841. return isDefined(value) ? result : value;
  12842. };
  12843. // Propagate $$watchDelegates other then inputsWatchDelegate
  12844. if (parsedExpression.$$watchDelegate &&
  12845. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12846. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12847. } else if (!interceptorFn.$stateful) {
  12848. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12849. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12850. fn.$$watchDelegate = inputsWatchDelegate;
  12851. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12852. }
  12853. return fn;
  12854. }
  12855. }];
  12856. }
  12857. /**
  12858. * @ngdoc service
  12859. * @name $q
  12860. * @requires $rootScope
  12861. *
  12862. * @description
  12863. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12864. * when they are done processing.
  12865. *
  12866. * This is an implementation of promises/deferred objects inspired by
  12867. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12868. *
  12869. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12870. * implementations, and the other which resembles ES6 promises to some degree.
  12871. *
  12872. * # $q constructor
  12873. *
  12874. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12875. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12876. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12877. *
  12878. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12879. * available yet.
  12880. *
  12881. * It can be used like so:
  12882. *
  12883. * ```js
  12884. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12885. * // are available in the current lexical scope (they could have been injected or passed in).
  12886. *
  12887. * function asyncGreet(name) {
  12888. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  12889. * return $q(function(resolve, reject) {
  12890. * setTimeout(function() {
  12891. * if (okToGreet(name)) {
  12892. * resolve('Hello, ' + name + '!');
  12893. * } else {
  12894. * reject('Greeting ' + name + ' is not allowed.');
  12895. * }
  12896. * }, 1000);
  12897. * });
  12898. * }
  12899. *
  12900. * var promise = asyncGreet('Robin Hood');
  12901. * promise.then(function(greeting) {
  12902. * alert('Success: ' + greeting);
  12903. * }, function(reason) {
  12904. * alert('Failed: ' + reason);
  12905. * });
  12906. * ```
  12907. *
  12908. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  12909. *
  12910. * However, the more traditional CommonJS-style usage is still available, and documented below.
  12911. *
  12912. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  12913. * interface for interacting with an object that represents the result of an action that is
  12914. * performed asynchronously, and may or may not be finished at any given point in time.
  12915. *
  12916. * From the perspective of dealing with error handling, deferred and promise APIs are to
  12917. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  12918. *
  12919. * ```js
  12920. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12921. * // are available in the current lexical scope (they could have been injected or passed in).
  12922. *
  12923. * function asyncGreet(name) {
  12924. * var deferred = $q.defer();
  12925. *
  12926. * setTimeout(function() {
  12927. * deferred.notify('About to greet ' + name + '.');
  12928. *
  12929. * if (okToGreet(name)) {
  12930. * deferred.resolve('Hello, ' + name + '!');
  12931. * } else {
  12932. * deferred.reject('Greeting ' + name + ' is not allowed.');
  12933. * }
  12934. * }, 1000);
  12935. *
  12936. * return deferred.promise;
  12937. * }
  12938. *
  12939. * var promise = asyncGreet('Robin Hood');
  12940. * promise.then(function(greeting) {
  12941. * alert('Success: ' + greeting);
  12942. * }, function(reason) {
  12943. * alert('Failed: ' + reason);
  12944. * }, function(update) {
  12945. * alert('Got notification: ' + update);
  12946. * });
  12947. * ```
  12948. *
  12949. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  12950. * comes in the way of guarantees that promise and deferred APIs make, see
  12951. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  12952. *
  12953. * Additionally the promise api allows for composition that is very hard to do with the
  12954. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  12955. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  12956. * section on serial or parallel joining of promises.
  12957. *
  12958. * # The Deferred API
  12959. *
  12960. * A new instance of deferred is constructed by calling `$q.defer()`.
  12961. *
  12962. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  12963. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  12964. * of the task.
  12965. *
  12966. * **Methods**
  12967. *
  12968. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  12969. * constructed via `$q.reject`, the promise will be rejected instead.
  12970. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  12971. * resolving it with a rejection constructed via `$q.reject`.
  12972. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  12973. * multiple times before the promise is either resolved or rejected.
  12974. *
  12975. * **Properties**
  12976. *
  12977. * - promise – `{Promise}` – promise object associated with this deferred.
  12978. *
  12979. *
  12980. * # The Promise API
  12981. *
  12982. * A new promise instance is created when a deferred instance is created and can be retrieved by
  12983. * calling `deferred.promise`.
  12984. *
  12985. * The purpose of the promise object is to allow for interested parties to get access to the result
  12986. * of the deferred task when it completes.
  12987. *
  12988. * **Methods**
  12989. *
  12990. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  12991. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  12992. * as soon as the result is available. The callbacks are called with a single argument: the result
  12993. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  12994. * provide a progress indication, before the promise is resolved or rejected.
  12995. *
  12996. * This method *returns a new promise* which is resolved or rejected via the return value of the
  12997. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  12998. * with the value which is resolved in that promise using
  12999. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13000. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13001. * resolved or rejected from the notifyCallback method.
  13002. *
  13003. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13004. *
  13005. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13006. * but to do so without modifying the final value. This is useful to release resources or do some
  13007. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13008. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13009. * more information.
  13010. *
  13011. * # Chaining promises
  13012. *
  13013. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13014. * possible to create a chain of promises:
  13015. *
  13016. * ```js
  13017. * promiseB = promiseA.then(function(result) {
  13018. * return result + 1;
  13019. * });
  13020. *
  13021. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13022. * // will be the result of promiseA incremented by 1
  13023. * ```
  13024. *
  13025. * It is possible to create chains of any length and since a promise can be resolved with another
  13026. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13027. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13028. * $http's response interceptors.
  13029. *
  13030. *
  13031. * # Differences between Kris Kowal's Q and $q
  13032. *
  13033. * There are two main differences:
  13034. *
  13035. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13036. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13037. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13038. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13039. * all the important functionality needed for common async tasks.
  13040. *
  13041. * # Testing
  13042. *
  13043. * ```js
  13044. * it('should simulate promise', inject(function($q, $rootScope) {
  13045. * var deferred = $q.defer();
  13046. * var promise = deferred.promise;
  13047. * var resolvedValue;
  13048. *
  13049. * promise.then(function(value) { resolvedValue = value; });
  13050. * expect(resolvedValue).toBeUndefined();
  13051. *
  13052. * // Simulate resolving of promise
  13053. * deferred.resolve(123);
  13054. * // Note that the 'then' function does not get called synchronously.
  13055. * // This is because we want the promise API to always be async, whether or not
  13056. * // it got called synchronously or asynchronously.
  13057. * expect(resolvedValue).toBeUndefined();
  13058. *
  13059. * // Propagate promise resolution to 'then' functions using $apply().
  13060. * $rootScope.$apply();
  13061. * expect(resolvedValue).toEqual(123);
  13062. * }));
  13063. * ```
  13064. *
  13065. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13066. * rejecting the newly created promise. The first parameter is a function which resolves the
  13067. * promise, the second parameter is a function which rejects the promise.
  13068. *
  13069. * @returns {Promise} The newly created promise.
  13070. */
  13071. function $QProvider() {
  13072. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13073. return qFactory(function(callback) {
  13074. $rootScope.$evalAsync(callback);
  13075. }, $exceptionHandler);
  13076. }];
  13077. }
  13078. function $$QProvider() {
  13079. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13080. return qFactory(function(callback) {
  13081. $browser.defer(callback);
  13082. }, $exceptionHandler);
  13083. }];
  13084. }
  13085. /**
  13086. * Constructs a promise manager.
  13087. *
  13088. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13089. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13090. * debugging purposes.
  13091. * @returns {object} Promise manager.
  13092. */
  13093. function qFactory(nextTick, exceptionHandler) {
  13094. var $qMinErr = minErr('$q', TypeError);
  13095. function callOnce(self, resolveFn, rejectFn) {
  13096. var called = false;
  13097. function wrap(fn) {
  13098. return function(value) {
  13099. if (called) return;
  13100. called = true;
  13101. fn.call(self, value);
  13102. };
  13103. }
  13104. return [wrap(resolveFn), wrap(rejectFn)];
  13105. }
  13106. /**
  13107. * @ngdoc method
  13108. * @name ng.$q#defer
  13109. * @kind function
  13110. *
  13111. * @description
  13112. * Creates a `Deferred` object which represents a task which will finish in the future.
  13113. *
  13114. * @returns {Deferred} Returns a new instance of deferred.
  13115. */
  13116. var defer = function() {
  13117. return new Deferred();
  13118. };
  13119. function Promise() {
  13120. this.$$state = { status: 0 };
  13121. }
  13122. Promise.prototype = {
  13123. then: function(onFulfilled, onRejected, progressBack) {
  13124. var result = new Deferred();
  13125. this.$$state.pending = this.$$state.pending || [];
  13126. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13127. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13128. return result.promise;
  13129. },
  13130. "catch": function(callback) {
  13131. return this.then(null, callback);
  13132. },
  13133. "finally": function(callback, progressBack) {
  13134. return this.then(function(value) {
  13135. return handleCallback(value, true, callback);
  13136. }, function(error) {
  13137. return handleCallback(error, false, callback);
  13138. }, progressBack);
  13139. }
  13140. };
  13141. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13142. function simpleBind(context, fn) {
  13143. return function(value) {
  13144. fn.call(context, value);
  13145. };
  13146. }
  13147. function processQueue(state) {
  13148. var fn, deferred, pending;
  13149. pending = state.pending;
  13150. state.processScheduled = false;
  13151. state.pending = undefined;
  13152. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13153. deferred = pending[i][0];
  13154. fn = pending[i][state.status];
  13155. try {
  13156. if (isFunction(fn)) {
  13157. deferred.resolve(fn(state.value));
  13158. } else if (state.status === 1) {
  13159. deferred.resolve(state.value);
  13160. } else {
  13161. deferred.reject(state.value);
  13162. }
  13163. } catch (e) {
  13164. deferred.reject(e);
  13165. exceptionHandler(e);
  13166. }
  13167. }
  13168. }
  13169. function scheduleProcessQueue(state) {
  13170. if (state.processScheduled || !state.pending) return;
  13171. state.processScheduled = true;
  13172. nextTick(function() { processQueue(state); });
  13173. }
  13174. function Deferred() {
  13175. this.promise = new Promise();
  13176. //Necessary to support unbound execution :/
  13177. this.resolve = simpleBind(this, this.resolve);
  13178. this.reject = simpleBind(this, this.reject);
  13179. this.notify = simpleBind(this, this.notify);
  13180. }
  13181. Deferred.prototype = {
  13182. resolve: function(val) {
  13183. if (this.promise.$$state.status) return;
  13184. if (val === this.promise) {
  13185. this.$$reject($qMinErr(
  13186. 'qcycle',
  13187. "Expected promise to be resolved with value other than itself '{0}'",
  13188. val));
  13189. } else {
  13190. this.$$resolve(val);
  13191. }
  13192. },
  13193. $$resolve: function(val) {
  13194. var then, fns;
  13195. fns = callOnce(this, this.$$resolve, this.$$reject);
  13196. try {
  13197. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13198. if (isFunction(then)) {
  13199. this.promise.$$state.status = -1;
  13200. then.call(val, fns[0], fns[1], this.notify);
  13201. } else {
  13202. this.promise.$$state.value = val;
  13203. this.promise.$$state.status = 1;
  13204. scheduleProcessQueue(this.promise.$$state);
  13205. }
  13206. } catch (e) {
  13207. fns[1](e);
  13208. exceptionHandler(e);
  13209. }
  13210. },
  13211. reject: function(reason) {
  13212. if (this.promise.$$state.status) return;
  13213. this.$$reject(reason);
  13214. },
  13215. $$reject: function(reason) {
  13216. this.promise.$$state.value = reason;
  13217. this.promise.$$state.status = 2;
  13218. scheduleProcessQueue(this.promise.$$state);
  13219. },
  13220. notify: function(progress) {
  13221. var callbacks = this.promise.$$state.pending;
  13222. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13223. nextTick(function() {
  13224. var callback, result;
  13225. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13226. result = callbacks[i][0];
  13227. callback = callbacks[i][3];
  13228. try {
  13229. result.notify(isFunction(callback) ? callback(progress) : progress);
  13230. } catch (e) {
  13231. exceptionHandler(e);
  13232. }
  13233. }
  13234. });
  13235. }
  13236. }
  13237. };
  13238. /**
  13239. * @ngdoc method
  13240. * @name $q#reject
  13241. * @kind function
  13242. *
  13243. * @description
  13244. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13245. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13246. * a promise chain, you don't need to worry about it.
  13247. *
  13248. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13249. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13250. * a promise error callback and you want to forward the error to the promise derived from the
  13251. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13252. * `reject`.
  13253. *
  13254. * ```js
  13255. * promiseB = promiseA.then(function(result) {
  13256. * // success: do something and resolve promiseB
  13257. * // with the old or a new result
  13258. * return result;
  13259. * }, function(reason) {
  13260. * // error: handle the error if possible and
  13261. * // resolve promiseB with newPromiseOrValue,
  13262. * // otherwise forward the rejection to promiseB
  13263. * if (canHandle(reason)) {
  13264. * // handle the error and recover
  13265. * return newPromiseOrValue;
  13266. * }
  13267. * return $q.reject(reason);
  13268. * });
  13269. * ```
  13270. *
  13271. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13272. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13273. */
  13274. var reject = function(reason) {
  13275. var result = new Deferred();
  13276. result.reject(reason);
  13277. return result.promise;
  13278. };
  13279. var makePromise = function makePromise(value, resolved) {
  13280. var result = new Deferred();
  13281. if (resolved) {
  13282. result.resolve(value);
  13283. } else {
  13284. result.reject(value);
  13285. }
  13286. return result.promise;
  13287. };
  13288. var handleCallback = function handleCallback(value, isResolved, callback) {
  13289. var callbackOutput = null;
  13290. try {
  13291. if (isFunction(callback)) callbackOutput = callback();
  13292. } catch (e) {
  13293. return makePromise(e, false);
  13294. }
  13295. if (isPromiseLike(callbackOutput)) {
  13296. return callbackOutput.then(function() {
  13297. return makePromise(value, isResolved);
  13298. }, function(error) {
  13299. return makePromise(error, false);
  13300. });
  13301. } else {
  13302. return makePromise(value, isResolved);
  13303. }
  13304. };
  13305. /**
  13306. * @ngdoc method
  13307. * @name $q#when
  13308. * @kind function
  13309. *
  13310. * @description
  13311. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13312. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13313. * the promise comes from a source that can't be trusted.
  13314. *
  13315. * @param {*} value Value or a promise
  13316. * @returns {Promise} Returns a promise of the passed value or promise
  13317. */
  13318. var when = function(value, callback, errback, progressBack) {
  13319. var result = new Deferred();
  13320. result.resolve(value);
  13321. return result.promise.then(callback, errback, progressBack);
  13322. };
  13323. /**
  13324. * @ngdoc method
  13325. * @name $q#resolve
  13326. * @kind function
  13327. *
  13328. * @description
  13329. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13330. *
  13331. * @param {*} value Value or a promise
  13332. * @returns {Promise} Returns a promise of the passed value or promise
  13333. */
  13334. var resolve = when;
  13335. /**
  13336. * @ngdoc method
  13337. * @name $q#all
  13338. * @kind function
  13339. *
  13340. * @description
  13341. * Combines multiple promises into a single promise that is resolved when all of the input
  13342. * promises are resolved.
  13343. *
  13344. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13345. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13346. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13347. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13348. * with the same rejection value.
  13349. */
  13350. function all(promises) {
  13351. var deferred = new Deferred(),
  13352. counter = 0,
  13353. results = isArray(promises) ? [] : {};
  13354. forEach(promises, function(promise, key) {
  13355. counter++;
  13356. when(promise).then(function(value) {
  13357. if (results.hasOwnProperty(key)) return;
  13358. results[key] = value;
  13359. if (!(--counter)) deferred.resolve(results);
  13360. }, function(reason) {
  13361. if (results.hasOwnProperty(key)) return;
  13362. deferred.reject(reason);
  13363. });
  13364. });
  13365. if (counter === 0) {
  13366. deferred.resolve(results);
  13367. }
  13368. return deferred.promise;
  13369. }
  13370. var $Q = function Q(resolver) {
  13371. if (!isFunction(resolver)) {
  13372. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13373. }
  13374. if (!(this instanceof Q)) {
  13375. // More useful when $Q is the Promise itself.
  13376. return new Q(resolver);
  13377. }
  13378. var deferred = new Deferred();
  13379. function resolveFn(value) {
  13380. deferred.resolve(value);
  13381. }
  13382. function rejectFn(reason) {
  13383. deferred.reject(reason);
  13384. }
  13385. resolver(resolveFn, rejectFn);
  13386. return deferred.promise;
  13387. };
  13388. $Q.defer = defer;
  13389. $Q.reject = reject;
  13390. $Q.when = when;
  13391. $Q.resolve = resolve;
  13392. $Q.all = all;
  13393. return $Q;
  13394. }
  13395. function $$RAFProvider() { //rAF
  13396. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13397. var requestAnimationFrame = $window.requestAnimationFrame ||
  13398. $window.webkitRequestAnimationFrame;
  13399. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13400. $window.webkitCancelAnimationFrame ||
  13401. $window.webkitCancelRequestAnimationFrame;
  13402. var rafSupported = !!requestAnimationFrame;
  13403. var rafFn = rafSupported
  13404. ? function(fn) {
  13405. var id = requestAnimationFrame(fn);
  13406. return function() {
  13407. cancelAnimationFrame(id);
  13408. };
  13409. }
  13410. : function(fn) {
  13411. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13412. return function() {
  13413. $timeout.cancel(timer);
  13414. };
  13415. };
  13416. queueFn.supported = rafSupported;
  13417. var cancelLastRAF;
  13418. var taskCount = 0;
  13419. var taskQueue = [];
  13420. return queueFn;
  13421. function flush() {
  13422. for (var i = 0; i < taskQueue.length; i++) {
  13423. var task = taskQueue[i];
  13424. if (task) {
  13425. taskQueue[i] = null;
  13426. task();
  13427. }
  13428. }
  13429. taskCount = taskQueue.length = 0;
  13430. }
  13431. function queueFn(asyncFn) {
  13432. var index = taskQueue.length;
  13433. taskCount++;
  13434. taskQueue.push(asyncFn);
  13435. if (index === 0) {
  13436. cancelLastRAF = rafFn(flush);
  13437. }
  13438. return function cancelQueueFn() {
  13439. if (index >= 0) {
  13440. taskQueue[index] = null;
  13441. index = null;
  13442. if (--taskCount === 0 && cancelLastRAF) {
  13443. cancelLastRAF();
  13444. cancelLastRAF = null;
  13445. taskQueue.length = 0;
  13446. }
  13447. }
  13448. };
  13449. }
  13450. }];
  13451. }
  13452. /**
  13453. * DESIGN NOTES
  13454. *
  13455. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13456. *
  13457. * The typical use of scope is to watch the expressions, which most of the time return the same
  13458. * value as last time so we optimize the operation.
  13459. *
  13460. * Closures construction is expensive in terms of speed as well as memory:
  13461. * - No closures, instead use prototypical inheritance for API
  13462. * - Internal state needs to be stored on scope directly, which means that private state is
  13463. * exposed as $$____ properties
  13464. *
  13465. * Loop operations are optimized by using while(count--) { ... }
  13466. * - this means that in order to keep the same order of execution as addition we have to add
  13467. * items to the array at the beginning (unshift) instead of at the end (push)
  13468. *
  13469. * Child scopes are created and removed often
  13470. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13471. *
  13472. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13473. * implemented in the same way as watch. Watch requires return of initialization function which
  13474. * are expensive to construct.
  13475. */
  13476. /**
  13477. * @ngdoc provider
  13478. * @name $rootScopeProvider
  13479. * @description
  13480. *
  13481. * Provider for the $rootScope service.
  13482. */
  13483. /**
  13484. * @ngdoc method
  13485. * @name $rootScopeProvider#digestTtl
  13486. * @description
  13487. *
  13488. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13489. * assuming that the model is unstable.
  13490. *
  13491. * The current default is 10 iterations.
  13492. *
  13493. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13494. * several digest iterations. However if an application needs more than the default 10 digest
  13495. * iterations for its model to stabilize then you should investigate what is causing the model to
  13496. * continuously change during the digest.
  13497. *
  13498. * Increasing the TTL could have performance implications, so you should not change it without
  13499. * proper justification.
  13500. *
  13501. * @param {number} limit The number of digest iterations.
  13502. */
  13503. /**
  13504. * @ngdoc service
  13505. * @name $rootScope
  13506. * @description
  13507. *
  13508. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13509. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13510. * between the model and the view, via a mechanism for watching the model for changes.
  13511. * They also provide an event emission/broadcast and subscription facility. See the
  13512. * {@link guide/scope developer guide on scopes}.
  13513. */
  13514. function $RootScopeProvider() {
  13515. var TTL = 10;
  13516. var $rootScopeMinErr = minErr('$rootScope');
  13517. var lastDirtyWatch = null;
  13518. var applyAsyncId = null;
  13519. this.digestTtl = function(value) {
  13520. if (arguments.length) {
  13521. TTL = value;
  13522. }
  13523. return TTL;
  13524. };
  13525. function createChildScopeClass(parent) {
  13526. function ChildScope() {
  13527. this.$$watchers = this.$$nextSibling =
  13528. this.$$childHead = this.$$childTail = null;
  13529. this.$$listeners = {};
  13530. this.$$listenerCount = {};
  13531. this.$$watchersCount = 0;
  13532. this.$id = nextUid();
  13533. this.$$ChildScope = null;
  13534. }
  13535. ChildScope.prototype = parent;
  13536. return ChildScope;
  13537. }
  13538. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13539. function($injector, $exceptionHandler, $parse, $browser) {
  13540. function destroyChildScope($event) {
  13541. $event.currentScope.$$destroyed = true;
  13542. }
  13543. /**
  13544. * @ngdoc type
  13545. * @name $rootScope.Scope
  13546. *
  13547. * @description
  13548. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13549. * {@link auto.$injector $injector}. Child scopes are created using the
  13550. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13551. * compiled HTML template is executed.)
  13552. *
  13553. * Here is a simple scope snippet to show how you can interact with the scope.
  13554. * ```html
  13555. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  13556. * ```
  13557. *
  13558. * # Inheritance
  13559. * A scope can inherit from a parent scope, as in this example:
  13560. * ```js
  13561. var parent = $rootScope;
  13562. var child = parent.$new();
  13563. parent.salutation = "Hello";
  13564. expect(child.salutation).toEqual('Hello');
  13565. child.salutation = "Welcome";
  13566. expect(child.salutation).toEqual('Welcome');
  13567. expect(parent.salutation).toEqual('Hello');
  13568. * ```
  13569. *
  13570. * When interacting with `Scope` in tests, additional helper methods are available on the
  13571. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13572. * details.
  13573. *
  13574. *
  13575. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13576. * provided for the current scope. Defaults to {@link ng}.
  13577. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13578. * append/override services provided by `providers`. This is handy
  13579. * when unit-testing and having the need to override a default
  13580. * service.
  13581. * @returns {Object} Newly created scope.
  13582. *
  13583. */
  13584. function Scope() {
  13585. this.$id = nextUid();
  13586. this.$$phase = this.$parent = this.$$watchers =
  13587. this.$$nextSibling = this.$$prevSibling =
  13588. this.$$childHead = this.$$childTail = null;
  13589. this.$root = this;
  13590. this.$$destroyed = false;
  13591. this.$$listeners = {};
  13592. this.$$listenerCount = {};
  13593. this.$$watchersCount = 0;
  13594. this.$$isolateBindings = null;
  13595. }
  13596. /**
  13597. * @ngdoc property
  13598. * @name $rootScope.Scope#$id
  13599. *
  13600. * @description
  13601. * Unique scope ID (monotonically increasing) useful for debugging.
  13602. */
  13603. /**
  13604. * @ngdoc property
  13605. * @name $rootScope.Scope#$parent
  13606. *
  13607. * @description
  13608. * Reference to the parent scope.
  13609. */
  13610. /**
  13611. * @ngdoc property
  13612. * @name $rootScope.Scope#$root
  13613. *
  13614. * @description
  13615. * Reference to the root scope.
  13616. */
  13617. Scope.prototype = {
  13618. constructor: Scope,
  13619. /**
  13620. * @ngdoc method
  13621. * @name $rootScope.Scope#$new
  13622. * @kind function
  13623. *
  13624. * @description
  13625. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13626. *
  13627. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13628. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13629. *
  13630. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13631. * desired for the scope and its child scopes to be permanently detached from the parent and
  13632. * thus stop participating in model change detection and listener notification by invoking.
  13633. *
  13634. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13635. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13636. * When creating widgets, it is useful for the widget to not accidentally read parent
  13637. * state.
  13638. *
  13639. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13640. * of the newly created scope. Defaults to `this` scope if not provided.
  13641. * This is used when creating a transclude scope to correctly place it
  13642. * in the scope hierarchy while maintaining the correct prototypical
  13643. * inheritance.
  13644. *
  13645. * @returns {Object} The newly created child scope.
  13646. *
  13647. */
  13648. $new: function(isolate, parent) {
  13649. var child;
  13650. parent = parent || this;
  13651. if (isolate) {
  13652. child = new Scope();
  13653. child.$root = this.$root;
  13654. } else {
  13655. // Only create a child scope class if somebody asks for one,
  13656. // but cache it to allow the VM to optimize lookups.
  13657. if (!this.$$ChildScope) {
  13658. this.$$ChildScope = createChildScopeClass(this);
  13659. }
  13660. child = new this.$$ChildScope();
  13661. }
  13662. child.$parent = parent;
  13663. child.$$prevSibling = parent.$$childTail;
  13664. if (parent.$$childHead) {
  13665. parent.$$childTail.$$nextSibling = child;
  13666. parent.$$childTail = child;
  13667. } else {
  13668. parent.$$childHead = parent.$$childTail = child;
  13669. }
  13670. // When the new scope is not isolated or we inherit from `this`, and
  13671. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13672. // prototypically. In all other cases, this property needs to be set
  13673. // when the parent scope is destroyed.
  13674. // The listener needs to be added after the parent is set
  13675. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13676. return child;
  13677. },
  13678. /**
  13679. * @ngdoc method
  13680. * @name $rootScope.Scope#$watch
  13681. * @kind function
  13682. *
  13683. * @description
  13684. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13685. *
  13686. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13687. * $digest()} and should return the value that will be watched. (Since
  13688. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  13689. * `watchExpression` can execute multiple times per
  13690. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  13691. * - The `listener` is called only when the value from the current `watchExpression` and the
  13692. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13693. * see below). Inequality is determined according to reference inequality,
  13694. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13695. * via the `!==` Javascript operator, unless `objectEquality == true`
  13696. * (see next point)
  13697. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13698. * according to the {@link angular.equals} function. To save the value of the object for
  13699. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13700. * watching complex objects will have adverse memory and performance implications.
  13701. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13702. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13703. * iteration limit is 10 to prevent an infinite loop deadlock.
  13704. *
  13705. *
  13706. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13707. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  13708. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  13709. * change is detected, be prepared for multiple calls to your listener.)
  13710. *
  13711. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13712. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13713. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13714. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13715. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13716. * listener was called due to initialization.
  13717. *
  13718. *
  13719. *
  13720. * # Example
  13721. * ```js
  13722. // let's assume that scope was dependency injected as the $rootScope
  13723. var scope = $rootScope;
  13724. scope.name = 'misko';
  13725. scope.counter = 0;
  13726. expect(scope.counter).toEqual(0);
  13727. scope.$watch('name', function(newValue, oldValue) {
  13728. scope.counter = scope.counter + 1;
  13729. });
  13730. expect(scope.counter).toEqual(0);
  13731. scope.$digest();
  13732. // the listener is always called during the first $digest loop after it was registered
  13733. expect(scope.counter).toEqual(1);
  13734. scope.$digest();
  13735. // but now it will not be called unless the value changes
  13736. expect(scope.counter).toEqual(1);
  13737. scope.name = 'adam';
  13738. scope.$digest();
  13739. expect(scope.counter).toEqual(2);
  13740. // Using a function as a watchExpression
  13741. var food;
  13742. scope.foodCounter = 0;
  13743. expect(scope.foodCounter).toEqual(0);
  13744. scope.$watch(
  13745. // This function returns the value being watched. It is called for each turn of the $digest loop
  13746. function() { return food; },
  13747. // This is the change listener, called when the value returned from the above function changes
  13748. function(newValue, oldValue) {
  13749. if ( newValue !== oldValue ) {
  13750. // Only increment the counter if the value changed
  13751. scope.foodCounter = scope.foodCounter + 1;
  13752. }
  13753. }
  13754. );
  13755. // No digest has been run so the counter will be zero
  13756. expect(scope.foodCounter).toEqual(0);
  13757. // Run the digest but since food has not changed count will still be zero
  13758. scope.$digest();
  13759. expect(scope.foodCounter).toEqual(0);
  13760. // Update food and run digest. Now the counter will increment
  13761. food = 'cheeseburger';
  13762. scope.$digest();
  13763. expect(scope.foodCounter).toEqual(1);
  13764. * ```
  13765. *
  13766. *
  13767. *
  13768. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13769. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13770. * a call to the `listener`.
  13771. *
  13772. * - `string`: Evaluated as {@link guide/expression expression}
  13773. * - `function(scope)`: called with current `scope` as a parameter.
  13774. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13775. * of `watchExpression` changes.
  13776. *
  13777. * - `newVal` contains the current value of the `watchExpression`
  13778. * - `oldVal` contains the previous value of the `watchExpression`
  13779. * - `scope` refers to the current scope
  13780. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13781. * comparing for reference equality.
  13782. * @returns {function()} Returns a deregistration function for this listener.
  13783. */
  13784. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13785. var get = $parse(watchExp);
  13786. if (get.$$watchDelegate) {
  13787. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13788. }
  13789. var scope = this,
  13790. array = scope.$$watchers,
  13791. watcher = {
  13792. fn: listener,
  13793. last: initWatchVal,
  13794. get: get,
  13795. exp: prettyPrintExpression || watchExp,
  13796. eq: !!objectEquality
  13797. };
  13798. lastDirtyWatch = null;
  13799. if (!isFunction(listener)) {
  13800. watcher.fn = noop;
  13801. }
  13802. if (!array) {
  13803. array = scope.$$watchers = [];
  13804. }
  13805. // we use unshift since we use a while loop in $digest for speed.
  13806. // the while loop reads in reverse order.
  13807. array.unshift(watcher);
  13808. incrementWatchersCount(this, 1);
  13809. return function deregisterWatch() {
  13810. if (arrayRemove(array, watcher) >= 0) {
  13811. incrementWatchersCount(scope, -1);
  13812. }
  13813. lastDirtyWatch = null;
  13814. };
  13815. },
  13816. /**
  13817. * @ngdoc method
  13818. * @name $rootScope.Scope#$watchGroup
  13819. * @kind function
  13820. *
  13821. * @description
  13822. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13823. * If any one expression in the collection changes the `listener` is executed.
  13824. *
  13825. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13826. * call to $digest() to see if any items changes.
  13827. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13828. *
  13829. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13830. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13831. *
  13832. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13833. * expression in `watchExpressions` changes
  13834. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13835. * those of `watchExpression`
  13836. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13837. * those of `watchExpression`
  13838. * The `scope` refers to the current scope.
  13839. * @returns {function()} Returns a de-registration function for all listeners.
  13840. */
  13841. $watchGroup: function(watchExpressions, listener) {
  13842. var oldValues = new Array(watchExpressions.length);
  13843. var newValues = new Array(watchExpressions.length);
  13844. var deregisterFns = [];
  13845. var self = this;
  13846. var changeReactionScheduled = false;
  13847. var firstRun = true;
  13848. if (!watchExpressions.length) {
  13849. // No expressions means we call the listener ASAP
  13850. var shouldCall = true;
  13851. self.$evalAsync(function() {
  13852. if (shouldCall) listener(newValues, newValues, self);
  13853. });
  13854. return function deregisterWatchGroup() {
  13855. shouldCall = false;
  13856. };
  13857. }
  13858. if (watchExpressions.length === 1) {
  13859. // Special case size of one
  13860. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13861. newValues[0] = value;
  13862. oldValues[0] = oldValue;
  13863. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13864. });
  13865. }
  13866. forEach(watchExpressions, function(expr, i) {
  13867. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13868. newValues[i] = value;
  13869. oldValues[i] = oldValue;
  13870. if (!changeReactionScheduled) {
  13871. changeReactionScheduled = true;
  13872. self.$evalAsync(watchGroupAction);
  13873. }
  13874. });
  13875. deregisterFns.push(unwatchFn);
  13876. });
  13877. function watchGroupAction() {
  13878. changeReactionScheduled = false;
  13879. if (firstRun) {
  13880. firstRun = false;
  13881. listener(newValues, newValues, self);
  13882. } else {
  13883. listener(newValues, oldValues, self);
  13884. }
  13885. }
  13886. return function deregisterWatchGroup() {
  13887. while (deregisterFns.length) {
  13888. deregisterFns.shift()();
  13889. }
  13890. };
  13891. },
  13892. /**
  13893. * @ngdoc method
  13894. * @name $rootScope.Scope#$watchCollection
  13895. * @kind function
  13896. *
  13897. * @description
  13898. * Shallow watches the properties of an object and fires whenever any of the properties change
  13899. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13900. * the properties). If a change is detected, the `listener` callback is fired.
  13901. *
  13902. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13903. * call to $digest() to see if any items have been added, removed, or moved.
  13904. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13905. * adding, removing, and moving items belonging to an object or array.
  13906. *
  13907. *
  13908. * # Example
  13909. * ```js
  13910. $scope.names = ['igor', 'matias', 'misko', 'james'];
  13911. $scope.dataCount = 4;
  13912. $scope.$watchCollection('names', function(newNames, oldNames) {
  13913. $scope.dataCount = newNames.length;
  13914. });
  13915. expect($scope.dataCount).toEqual(4);
  13916. $scope.$digest();
  13917. //still at 4 ... no changes
  13918. expect($scope.dataCount).toEqual(4);
  13919. $scope.names.pop();
  13920. $scope.$digest();
  13921. //now there's been a change
  13922. expect($scope.dataCount).toEqual(3);
  13923. * ```
  13924. *
  13925. *
  13926. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  13927. * expression value should evaluate to an object or an array which is observed on each
  13928. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  13929. * collection will trigger a call to the `listener`.
  13930. *
  13931. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  13932. * when a change is detected.
  13933. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  13934. * - The `oldCollection` object is a copy of the former collection data.
  13935. * Due to performance considerations, the`oldCollection` value is computed only if the
  13936. * `listener` function declares two or more arguments.
  13937. * - The `scope` argument refers to the current scope.
  13938. *
  13939. * @returns {function()} Returns a de-registration function for this listener. When the
  13940. * de-registration function is executed, the internal watch operation is terminated.
  13941. */
  13942. $watchCollection: function(obj, listener) {
  13943. $watchCollectionInterceptor.$stateful = true;
  13944. var self = this;
  13945. // the current value, updated on each dirty-check run
  13946. var newValue;
  13947. // a shallow copy of the newValue from the last dirty-check run,
  13948. // updated to match newValue during dirty-check run
  13949. var oldValue;
  13950. // a shallow copy of the newValue from when the last change happened
  13951. var veryOldValue;
  13952. // only track veryOldValue if the listener is asking for it
  13953. var trackVeryOldValue = (listener.length > 1);
  13954. var changeDetected = 0;
  13955. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  13956. var internalArray = [];
  13957. var internalObject = {};
  13958. var initRun = true;
  13959. var oldLength = 0;
  13960. function $watchCollectionInterceptor(_value) {
  13961. newValue = _value;
  13962. var newLength, key, bothNaN, newItem, oldItem;
  13963. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  13964. if (isUndefined(newValue)) return;
  13965. if (!isObject(newValue)) { // if primitive
  13966. if (oldValue !== newValue) {
  13967. oldValue = newValue;
  13968. changeDetected++;
  13969. }
  13970. } else if (isArrayLike(newValue)) {
  13971. if (oldValue !== internalArray) {
  13972. // we are transitioning from something which was not an array into array.
  13973. oldValue = internalArray;
  13974. oldLength = oldValue.length = 0;
  13975. changeDetected++;
  13976. }
  13977. newLength = newValue.length;
  13978. if (oldLength !== newLength) {
  13979. // if lengths do not match we need to trigger change notification
  13980. changeDetected++;
  13981. oldValue.length = oldLength = newLength;
  13982. }
  13983. // copy the items to oldValue and look for changes.
  13984. for (var i = 0; i < newLength; i++) {
  13985. oldItem = oldValue[i];
  13986. newItem = newValue[i];
  13987. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  13988. if (!bothNaN && (oldItem !== newItem)) {
  13989. changeDetected++;
  13990. oldValue[i] = newItem;
  13991. }
  13992. }
  13993. } else {
  13994. if (oldValue !== internalObject) {
  13995. // we are transitioning from something which was not an object into object.
  13996. oldValue = internalObject = {};
  13997. oldLength = 0;
  13998. changeDetected++;
  13999. }
  14000. // copy the items to oldValue and look for changes.
  14001. newLength = 0;
  14002. for (key in newValue) {
  14003. if (newValue.hasOwnProperty(key)) {
  14004. newLength++;
  14005. newItem = newValue[key];
  14006. oldItem = oldValue[key];
  14007. if (key in oldValue) {
  14008. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14009. if (!bothNaN && (oldItem !== newItem)) {
  14010. changeDetected++;
  14011. oldValue[key] = newItem;
  14012. }
  14013. } else {
  14014. oldLength++;
  14015. oldValue[key] = newItem;
  14016. changeDetected++;
  14017. }
  14018. }
  14019. }
  14020. if (oldLength > newLength) {
  14021. // we used to have more keys, need to find them and destroy them.
  14022. changeDetected++;
  14023. for (key in oldValue) {
  14024. if (!newValue.hasOwnProperty(key)) {
  14025. oldLength--;
  14026. delete oldValue[key];
  14027. }
  14028. }
  14029. }
  14030. }
  14031. return changeDetected;
  14032. }
  14033. function $watchCollectionAction() {
  14034. if (initRun) {
  14035. initRun = false;
  14036. listener(newValue, newValue, self);
  14037. } else {
  14038. listener(newValue, veryOldValue, self);
  14039. }
  14040. // make a copy for the next time a collection is changed
  14041. if (trackVeryOldValue) {
  14042. if (!isObject(newValue)) {
  14043. //primitive
  14044. veryOldValue = newValue;
  14045. } else if (isArrayLike(newValue)) {
  14046. veryOldValue = new Array(newValue.length);
  14047. for (var i = 0; i < newValue.length; i++) {
  14048. veryOldValue[i] = newValue[i];
  14049. }
  14050. } else { // if object
  14051. veryOldValue = {};
  14052. for (var key in newValue) {
  14053. if (hasOwnProperty.call(newValue, key)) {
  14054. veryOldValue[key] = newValue[key];
  14055. }
  14056. }
  14057. }
  14058. }
  14059. }
  14060. return this.$watch(changeDetector, $watchCollectionAction);
  14061. },
  14062. /**
  14063. * @ngdoc method
  14064. * @name $rootScope.Scope#$digest
  14065. * @kind function
  14066. *
  14067. * @description
  14068. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14069. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14070. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14071. * until no more listeners are firing. This means that it is possible to get into an infinite
  14072. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14073. * iterations exceeds 10.
  14074. *
  14075. * Usually, you don't call `$digest()` directly in
  14076. * {@link ng.directive:ngController controllers} or in
  14077. * {@link ng.$compileProvider#directive directives}.
  14078. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14079. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14080. *
  14081. * If you want to be notified whenever `$digest()` is called,
  14082. * you can register a `watchExpression` function with
  14083. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14084. *
  14085. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14086. *
  14087. * # Example
  14088. * ```js
  14089. var scope = ...;
  14090. scope.name = 'misko';
  14091. scope.counter = 0;
  14092. expect(scope.counter).toEqual(0);
  14093. scope.$watch('name', function(newValue, oldValue) {
  14094. scope.counter = scope.counter + 1;
  14095. });
  14096. expect(scope.counter).toEqual(0);
  14097. scope.$digest();
  14098. // the listener is always called during the first $digest loop after it was registered
  14099. expect(scope.counter).toEqual(1);
  14100. scope.$digest();
  14101. // but now it will not be called unless the value changes
  14102. expect(scope.counter).toEqual(1);
  14103. scope.name = 'adam';
  14104. scope.$digest();
  14105. expect(scope.counter).toEqual(2);
  14106. * ```
  14107. *
  14108. */
  14109. $digest: function() {
  14110. var watch, value, last,
  14111. watchers,
  14112. length,
  14113. dirty, ttl = TTL,
  14114. next, current, target = this,
  14115. watchLog = [],
  14116. logIdx, logMsg, asyncTask;
  14117. beginPhase('$digest');
  14118. // Check for changes to browser url that happened in sync before the call to $digest
  14119. $browser.$$checkUrlChange();
  14120. if (this === $rootScope && applyAsyncId !== null) {
  14121. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14122. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14123. $browser.defer.cancel(applyAsyncId);
  14124. flushApplyAsync();
  14125. }
  14126. lastDirtyWatch = null;
  14127. do { // "while dirty" loop
  14128. dirty = false;
  14129. current = target;
  14130. while (asyncQueue.length) {
  14131. try {
  14132. asyncTask = asyncQueue.shift();
  14133. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14134. } catch (e) {
  14135. $exceptionHandler(e);
  14136. }
  14137. lastDirtyWatch = null;
  14138. }
  14139. traverseScopesLoop:
  14140. do { // "traverse the scopes" loop
  14141. if ((watchers = current.$$watchers)) {
  14142. // process our watches
  14143. length = watchers.length;
  14144. while (length--) {
  14145. try {
  14146. watch = watchers[length];
  14147. // Most common watches are on primitives, in which case we can short
  14148. // circuit it with === operator, only when === fails do we use .equals
  14149. if (watch) {
  14150. if ((value = watch.get(current)) !== (last = watch.last) &&
  14151. !(watch.eq
  14152. ? equals(value, last)
  14153. : (typeof value === 'number' && typeof last === 'number'
  14154. && isNaN(value) && isNaN(last)))) {
  14155. dirty = true;
  14156. lastDirtyWatch = watch;
  14157. watch.last = watch.eq ? copy(value, null) : value;
  14158. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14159. if (ttl < 5) {
  14160. logIdx = 4 - ttl;
  14161. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14162. watchLog[logIdx].push({
  14163. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14164. newVal: value,
  14165. oldVal: last
  14166. });
  14167. }
  14168. } else if (watch === lastDirtyWatch) {
  14169. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14170. // have already been tested.
  14171. dirty = false;
  14172. break traverseScopesLoop;
  14173. }
  14174. }
  14175. } catch (e) {
  14176. $exceptionHandler(e);
  14177. }
  14178. }
  14179. }
  14180. // Insanity Warning: scope depth-first traversal
  14181. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14182. // this piece should be kept in sync with the traversal in $broadcast
  14183. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14184. (current !== target && current.$$nextSibling)))) {
  14185. while (current !== target && !(next = current.$$nextSibling)) {
  14186. current = current.$parent;
  14187. }
  14188. }
  14189. } while ((current = next));
  14190. // `break traverseScopesLoop;` takes us to here
  14191. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14192. clearPhase();
  14193. throw $rootScopeMinErr('infdig',
  14194. '{0} $digest() iterations reached. Aborting!\n' +
  14195. 'Watchers fired in the last 5 iterations: {1}',
  14196. TTL, watchLog);
  14197. }
  14198. } while (dirty || asyncQueue.length);
  14199. clearPhase();
  14200. while (postDigestQueue.length) {
  14201. try {
  14202. postDigestQueue.shift()();
  14203. } catch (e) {
  14204. $exceptionHandler(e);
  14205. }
  14206. }
  14207. },
  14208. /**
  14209. * @ngdoc event
  14210. * @name $rootScope.Scope#$destroy
  14211. * @eventType broadcast on scope being destroyed
  14212. *
  14213. * @description
  14214. * Broadcasted when a scope and its children are being destroyed.
  14215. *
  14216. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14217. * clean up DOM bindings before an element is removed from the DOM.
  14218. */
  14219. /**
  14220. * @ngdoc method
  14221. * @name $rootScope.Scope#$destroy
  14222. * @kind function
  14223. *
  14224. * @description
  14225. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14226. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14227. * propagate to the current scope and its children. Removal also implies that the current
  14228. * scope is eligible for garbage collection.
  14229. *
  14230. * The `$destroy()` is usually used by directives such as
  14231. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14232. * unrolling of the loop.
  14233. *
  14234. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14235. * Application code can register a `$destroy` event handler that will give it a chance to
  14236. * perform any necessary cleanup.
  14237. *
  14238. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14239. * clean up DOM bindings before an element is removed from the DOM.
  14240. */
  14241. $destroy: function() {
  14242. // We can't destroy a scope that has been already destroyed.
  14243. if (this.$$destroyed) return;
  14244. var parent = this.$parent;
  14245. this.$broadcast('$destroy');
  14246. this.$$destroyed = true;
  14247. if (this === $rootScope) {
  14248. //Remove handlers attached to window when $rootScope is removed
  14249. $browser.$$applicationDestroyed();
  14250. }
  14251. incrementWatchersCount(this, -this.$$watchersCount);
  14252. for (var eventName in this.$$listenerCount) {
  14253. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14254. }
  14255. // sever all the references to parent scopes (after this cleanup, the current scope should
  14256. // not be retained by any of our references and should be eligible for garbage collection)
  14257. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14258. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14259. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14260. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14261. // Disable listeners, watchers and apply/digest methods
  14262. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14263. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14264. this.$$listeners = {};
  14265. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14266. // and inline caches.
  14267. //
  14268. // see:
  14269. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14270. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14271. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14272. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14273. this.$$childTail = this.$root = this.$$watchers = null;
  14274. },
  14275. /**
  14276. * @ngdoc method
  14277. * @name $rootScope.Scope#$eval
  14278. * @kind function
  14279. *
  14280. * @description
  14281. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14282. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14283. * expressions.
  14284. *
  14285. * # Example
  14286. * ```js
  14287. var scope = ng.$rootScope.Scope();
  14288. scope.a = 1;
  14289. scope.b = 2;
  14290. expect(scope.$eval('a+b')).toEqual(3);
  14291. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14292. * ```
  14293. *
  14294. * @param {(string|function())=} expression An angular expression to be executed.
  14295. *
  14296. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14297. * - `function(scope)`: execute the function with the current `scope` parameter.
  14298. *
  14299. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14300. * @returns {*} The result of evaluating the expression.
  14301. */
  14302. $eval: function(expr, locals) {
  14303. return $parse(expr)(this, locals);
  14304. },
  14305. /**
  14306. * @ngdoc method
  14307. * @name $rootScope.Scope#$evalAsync
  14308. * @kind function
  14309. *
  14310. * @description
  14311. * Executes the expression on the current scope at a later point in time.
  14312. *
  14313. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14314. * that:
  14315. *
  14316. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14317. * rendering).
  14318. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14319. * `expression` execution.
  14320. *
  14321. * Any exceptions from the execution of the expression are forwarded to the
  14322. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14323. *
  14324. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14325. * will be scheduled. However, it is encouraged to always call code that changes the model
  14326. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14327. *
  14328. * @param {(string|function())=} expression An angular expression to be executed.
  14329. *
  14330. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14331. * - `function(scope)`: execute the function with the current `scope` parameter.
  14332. *
  14333. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14334. */
  14335. $evalAsync: function(expr, locals) {
  14336. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14337. // task also schedule async auto-flush
  14338. if (!$rootScope.$$phase && !asyncQueue.length) {
  14339. $browser.defer(function() {
  14340. if (asyncQueue.length) {
  14341. $rootScope.$digest();
  14342. }
  14343. });
  14344. }
  14345. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14346. },
  14347. $$postDigest: function(fn) {
  14348. postDigestQueue.push(fn);
  14349. },
  14350. /**
  14351. * @ngdoc method
  14352. * @name $rootScope.Scope#$apply
  14353. * @kind function
  14354. *
  14355. * @description
  14356. * `$apply()` is used to execute an expression in angular from outside of the angular
  14357. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14358. * Because we are calling into the angular framework we need to perform proper scope life
  14359. * cycle of {@link ng.$exceptionHandler exception handling},
  14360. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14361. *
  14362. * ## Life cycle
  14363. *
  14364. * # Pseudo-Code of `$apply()`
  14365. * ```js
  14366. function $apply(expr) {
  14367. try {
  14368. return $eval(expr);
  14369. } catch (e) {
  14370. $exceptionHandler(e);
  14371. } finally {
  14372. $root.$digest();
  14373. }
  14374. }
  14375. * ```
  14376. *
  14377. *
  14378. * Scope's `$apply()` method transitions through the following stages:
  14379. *
  14380. * 1. The {@link guide/expression expression} is executed using the
  14381. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14382. * 2. Any exceptions from the execution of the expression are forwarded to the
  14383. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14384. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14385. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14386. *
  14387. *
  14388. * @param {(string|function())=} exp An angular expression to be executed.
  14389. *
  14390. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14391. * - `function(scope)`: execute the function with current `scope` parameter.
  14392. *
  14393. * @returns {*} The result of evaluating the expression.
  14394. */
  14395. $apply: function(expr) {
  14396. try {
  14397. beginPhase('$apply');
  14398. return this.$eval(expr);
  14399. } catch (e) {
  14400. $exceptionHandler(e);
  14401. } finally {
  14402. clearPhase();
  14403. try {
  14404. $rootScope.$digest();
  14405. } catch (e) {
  14406. $exceptionHandler(e);
  14407. throw e;
  14408. }
  14409. }
  14410. },
  14411. /**
  14412. * @ngdoc method
  14413. * @name $rootScope.Scope#$applyAsync
  14414. * @kind function
  14415. *
  14416. * @description
  14417. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14418. * varies across browsers, but is typically around ~10 milliseconds.
  14419. *
  14420. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14421. * digest.
  14422. *
  14423. * @param {(string|function())=} exp An angular expression to be executed.
  14424. *
  14425. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14426. * - `function(scope)`: execute the function with current `scope` parameter.
  14427. */
  14428. $applyAsync: function(expr) {
  14429. var scope = this;
  14430. expr && applyAsyncQueue.push($applyAsyncExpression);
  14431. scheduleApplyAsync();
  14432. function $applyAsyncExpression() {
  14433. scope.$eval(expr);
  14434. }
  14435. },
  14436. /**
  14437. * @ngdoc method
  14438. * @name $rootScope.Scope#$on
  14439. * @kind function
  14440. *
  14441. * @description
  14442. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14443. * discussion of event life cycle.
  14444. *
  14445. * The event listener function format is: `function(event, args...)`. The `event` object
  14446. * passed into the listener has the following attributes:
  14447. *
  14448. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14449. * `$broadcast`-ed.
  14450. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14451. * event propagates through the scope hierarchy, this property is set to null.
  14452. * - `name` - `{string}`: name of the event.
  14453. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14454. * further event propagation (available only for events that were `$emit`-ed).
  14455. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14456. * to true.
  14457. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14458. *
  14459. * @param {string} name Event name to listen on.
  14460. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14461. * @returns {function()} Returns a deregistration function for this listener.
  14462. */
  14463. $on: function(name, listener) {
  14464. var namedListeners = this.$$listeners[name];
  14465. if (!namedListeners) {
  14466. this.$$listeners[name] = namedListeners = [];
  14467. }
  14468. namedListeners.push(listener);
  14469. var current = this;
  14470. do {
  14471. if (!current.$$listenerCount[name]) {
  14472. current.$$listenerCount[name] = 0;
  14473. }
  14474. current.$$listenerCount[name]++;
  14475. } while ((current = current.$parent));
  14476. var self = this;
  14477. return function() {
  14478. var indexOfListener = namedListeners.indexOf(listener);
  14479. if (indexOfListener !== -1) {
  14480. namedListeners[indexOfListener] = null;
  14481. decrementListenerCount(self, 1, name);
  14482. }
  14483. };
  14484. },
  14485. /**
  14486. * @ngdoc method
  14487. * @name $rootScope.Scope#$emit
  14488. * @kind function
  14489. *
  14490. * @description
  14491. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14492. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14493. *
  14494. * The event life cycle starts at the scope on which `$emit` was called. All
  14495. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14496. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14497. * registered listeners along the way. The event will stop propagating if one of the listeners
  14498. * cancels it.
  14499. *
  14500. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14501. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14502. *
  14503. * @param {string} name Event name to emit.
  14504. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14505. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14506. */
  14507. $emit: function(name, args) {
  14508. var empty = [],
  14509. namedListeners,
  14510. scope = this,
  14511. stopPropagation = false,
  14512. event = {
  14513. name: name,
  14514. targetScope: scope,
  14515. stopPropagation: function() {stopPropagation = true;},
  14516. preventDefault: function() {
  14517. event.defaultPrevented = true;
  14518. },
  14519. defaultPrevented: false
  14520. },
  14521. listenerArgs = concat([event], arguments, 1),
  14522. i, length;
  14523. do {
  14524. namedListeners = scope.$$listeners[name] || empty;
  14525. event.currentScope = scope;
  14526. for (i = 0, length = namedListeners.length; i < length; i++) {
  14527. // if listeners were deregistered, defragment the array
  14528. if (!namedListeners[i]) {
  14529. namedListeners.splice(i, 1);
  14530. i--;
  14531. length--;
  14532. continue;
  14533. }
  14534. try {
  14535. //allow all listeners attached to the current scope to run
  14536. namedListeners[i].apply(null, listenerArgs);
  14537. } catch (e) {
  14538. $exceptionHandler(e);
  14539. }
  14540. }
  14541. //if any listener on the current scope stops propagation, prevent bubbling
  14542. if (stopPropagation) {
  14543. event.currentScope = null;
  14544. return event;
  14545. }
  14546. //traverse upwards
  14547. scope = scope.$parent;
  14548. } while (scope);
  14549. event.currentScope = null;
  14550. return event;
  14551. },
  14552. /**
  14553. * @ngdoc method
  14554. * @name $rootScope.Scope#$broadcast
  14555. * @kind function
  14556. *
  14557. * @description
  14558. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14559. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14560. *
  14561. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14562. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14563. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14564. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14565. *
  14566. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14567. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14568. *
  14569. * @param {string} name Event name to broadcast.
  14570. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14571. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14572. */
  14573. $broadcast: function(name, args) {
  14574. var target = this,
  14575. current = target,
  14576. next = target,
  14577. event = {
  14578. name: name,
  14579. targetScope: target,
  14580. preventDefault: function() {
  14581. event.defaultPrevented = true;
  14582. },
  14583. defaultPrevented: false
  14584. };
  14585. if (!target.$$listenerCount[name]) return event;
  14586. var listenerArgs = concat([event], arguments, 1),
  14587. listeners, i, length;
  14588. //down while you can, then up and next sibling or up and next sibling until back at root
  14589. while ((current = next)) {
  14590. event.currentScope = current;
  14591. listeners = current.$$listeners[name] || [];
  14592. for (i = 0, length = listeners.length; i < length; i++) {
  14593. // if listeners were deregistered, defragment the array
  14594. if (!listeners[i]) {
  14595. listeners.splice(i, 1);
  14596. i--;
  14597. length--;
  14598. continue;
  14599. }
  14600. try {
  14601. listeners[i].apply(null, listenerArgs);
  14602. } catch (e) {
  14603. $exceptionHandler(e);
  14604. }
  14605. }
  14606. // Insanity Warning: scope depth-first traversal
  14607. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14608. // this piece should be kept in sync with the traversal in $digest
  14609. // (though it differs due to having the extra check for $$listenerCount)
  14610. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14611. (current !== target && current.$$nextSibling)))) {
  14612. while (current !== target && !(next = current.$$nextSibling)) {
  14613. current = current.$parent;
  14614. }
  14615. }
  14616. }
  14617. event.currentScope = null;
  14618. return event;
  14619. }
  14620. };
  14621. var $rootScope = new Scope();
  14622. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14623. var asyncQueue = $rootScope.$$asyncQueue = [];
  14624. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14625. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14626. return $rootScope;
  14627. function beginPhase(phase) {
  14628. if ($rootScope.$$phase) {
  14629. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14630. }
  14631. $rootScope.$$phase = phase;
  14632. }
  14633. function clearPhase() {
  14634. $rootScope.$$phase = null;
  14635. }
  14636. function incrementWatchersCount(current, count) {
  14637. do {
  14638. current.$$watchersCount += count;
  14639. } while ((current = current.$parent));
  14640. }
  14641. function decrementListenerCount(current, count, name) {
  14642. do {
  14643. current.$$listenerCount[name] -= count;
  14644. if (current.$$listenerCount[name] === 0) {
  14645. delete current.$$listenerCount[name];
  14646. }
  14647. } while ((current = current.$parent));
  14648. }
  14649. /**
  14650. * function used as an initial value for watchers.
  14651. * because it's unique we can easily tell it apart from other values
  14652. */
  14653. function initWatchVal() {}
  14654. function flushApplyAsync() {
  14655. while (applyAsyncQueue.length) {
  14656. try {
  14657. applyAsyncQueue.shift()();
  14658. } catch (e) {
  14659. $exceptionHandler(e);
  14660. }
  14661. }
  14662. applyAsyncId = null;
  14663. }
  14664. function scheduleApplyAsync() {
  14665. if (applyAsyncId === null) {
  14666. applyAsyncId = $browser.defer(function() {
  14667. $rootScope.$apply(flushApplyAsync);
  14668. });
  14669. }
  14670. }
  14671. }];
  14672. }
  14673. /**
  14674. * @description
  14675. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14676. */
  14677. function $$SanitizeUriProvider() {
  14678. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14679. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14680. /**
  14681. * @description
  14682. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14683. * urls during a[href] sanitization.
  14684. *
  14685. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14686. *
  14687. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14688. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14689. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14690. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14691. *
  14692. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14693. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14694. * chaining otherwise.
  14695. */
  14696. this.aHrefSanitizationWhitelist = function(regexp) {
  14697. if (isDefined(regexp)) {
  14698. aHrefSanitizationWhitelist = regexp;
  14699. return this;
  14700. }
  14701. return aHrefSanitizationWhitelist;
  14702. };
  14703. /**
  14704. * @description
  14705. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14706. * urls during img[src] sanitization.
  14707. *
  14708. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14709. *
  14710. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14711. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14712. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14713. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14714. *
  14715. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14716. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14717. * chaining otherwise.
  14718. */
  14719. this.imgSrcSanitizationWhitelist = function(regexp) {
  14720. if (isDefined(regexp)) {
  14721. imgSrcSanitizationWhitelist = regexp;
  14722. return this;
  14723. }
  14724. return imgSrcSanitizationWhitelist;
  14725. };
  14726. this.$get = function() {
  14727. return function sanitizeUri(uri, isImage) {
  14728. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14729. var normalizedVal;
  14730. normalizedVal = urlResolve(uri).href;
  14731. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14732. return 'unsafe:' + normalizedVal;
  14733. }
  14734. return uri;
  14735. };
  14736. };
  14737. }
  14738. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14739. * Any commits to this file should be reviewed with security in mind. *
  14740. * Changes to this file can potentially create security vulnerabilities. *
  14741. * An approval from 2 Core members with history of modifying *
  14742. * this file is required. *
  14743. * *
  14744. * Does the change somehow allow for arbitrary javascript to be executed? *
  14745. * Or allows for someone to change the prototype of built-in objects? *
  14746. * Or gives undesired access to variables likes document or window? *
  14747. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14748. var $sceMinErr = minErr('$sce');
  14749. var SCE_CONTEXTS = {
  14750. HTML: 'html',
  14751. CSS: 'css',
  14752. URL: 'url',
  14753. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14754. // url. (e.g. ng-include, script src, templateUrl)
  14755. RESOURCE_URL: 'resourceUrl',
  14756. JS: 'js'
  14757. };
  14758. // Helper functions follow.
  14759. function adjustMatcher(matcher) {
  14760. if (matcher === 'self') {
  14761. return matcher;
  14762. } else if (isString(matcher)) {
  14763. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14764. // '*' matches any character except those from the set ':/.?&'.
  14765. // '**' matches any character (like .* in a RegExp).
  14766. // More than 2 *'s raises an error as it's ill defined.
  14767. if (matcher.indexOf('***') > -1) {
  14768. throw $sceMinErr('iwcard',
  14769. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14770. }
  14771. matcher = escapeForRegexp(matcher).
  14772. replace('\\*\\*', '.*').
  14773. replace('\\*', '[^:/.?&;]*');
  14774. return new RegExp('^' + matcher + '$');
  14775. } else if (isRegExp(matcher)) {
  14776. // The only other type of matcher allowed is a Regexp.
  14777. // Match entire URL / disallow partial matches.
  14778. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14779. return new RegExp('^' + matcher.source + '$');
  14780. } else {
  14781. throw $sceMinErr('imatcher',
  14782. 'Matchers may only be "self", string patterns or RegExp objects');
  14783. }
  14784. }
  14785. function adjustMatchers(matchers) {
  14786. var adjustedMatchers = [];
  14787. if (isDefined(matchers)) {
  14788. forEach(matchers, function(matcher) {
  14789. adjustedMatchers.push(adjustMatcher(matcher));
  14790. });
  14791. }
  14792. return adjustedMatchers;
  14793. }
  14794. /**
  14795. * @ngdoc service
  14796. * @name $sceDelegate
  14797. * @kind function
  14798. *
  14799. * @description
  14800. *
  14801. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14802. * Contextual Escaping (SCE)} services to AngularJS.
  14803. *
  14804. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14805. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14806. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14807. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14808. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14809. *
  14810. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14811. *
  14812. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14813. * can override it completely to change the behavior of `$sce`, the common case would
  14814. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14815. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14816. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14817. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14818. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14819. */
  14820. /**
  14821. * @ngdoc provider
  14822. * @name $sceDelegateProvider
  14823. * @description
  14824. *
  14825. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14826. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14827. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14828. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14829. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14830. *
  14831. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14832. * Strict Contextual Escaping (SCE)}.
  14833. *
  14834. * **Example**: Consider the following case. <a name="example"></a>
  14835. *
  14836. * - your app is hosted at url `http://myapp.example.com/`
  14837. * - but some of your templates are hosted on other domains you control such as
  14838. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14839. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14840. *
  14841. * Here is what a secure configuration for this scenario might look like:
  14842. *
  14843. * ```
  14844. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14845. * $sceDelegateProvider.resourceUrlWhitelist([
  14846. * // Allow same origin resource loads.
  14847. * 'self',
  14848. * // Allow loading from our assets domain. Notice the difference between * and **.
  14849. * 'http://srv*.assets.example.com/**'
  14850. * ]);
  14851. *
  14852. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14853. * $sceDelegateProvider.resourceUrlBlacklist([
  14854. * 'http://myapp.example.com/clickThru**'
  14855. * ]);
  14856. * });
  14857. * ```
  14858. */
  14859. function $SceDelegateProvider() {
  14860. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14861. // Resource URLs can also be trusted by policy.
  14862. var resourceUrlWhitelist = ['self'],
  14863. resourceUrlBlacklist = [];
  14864. /**
  14865. * @ngdoc method
  14866. * @name $sceDelegateProvider#resourceUrlWhitelist
  14867. * @kind function
  14868. *
  14869. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14870. * provided. This must be an array or null. A snapshot of this array is used so further
  14871. * changes to the array are ignored.
  14872. *
  14873. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14874. * allowed in this array.
  14875. *
  14876. * Note: **an empty whitelist array will block all URLs**!
  14877. *
  14878. * @return {Array} the currently set whitelist array.
  14879. *
  14880. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14881. * same origin resource requests.
  14882. *
  14883. * @description
  14884. * Sets/Gets the whitelist of trusted resource URLs.
  14885. */
  14886. this.resourceUrlWhitelist = function(value) {
  14887. if (arguments.length) {
  14888. resourceUrlWhitelist = adjustMatchers(value);
  14889. }
  14890. return resourceUrlWhitelist;
  14891. };
  14892. /**
  14893. * @ngdoc method
  14894. * @name $sceDelegateProvider#resourceUrlBlacklist
  14895. * @kind function
  14896. *
  14897. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14898. * provided. This must be an array or null. A snapshot of this array is used so further
  14899. * changes to the array are ignored.
  14900. *
  14901. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14902. * allowed in this array.
  14903. *
  14904. * The typical usage for the blacklist is to **block
  14905. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14906. * these would otherwise be trusted but actually return content from the redirected domain.
  14907. *
  14908. * Finally, **the blacklist overrides the whitelist** and has the final say.
  14909. *
  14910. * @return {Array} the currently set blacklist array.
  14911. *
  14912. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  14913. * is no blacklist.)
  14914. *
  14915. * @description
  14916. * Sets/Gets the blacklist of trusted resource URLs.
  14917. */
  14918. this.resourceUrlBlacklist = function(value) {
  14919. if (arguments.length) {
  14920. resourceUrlBlacklist = adjustMatchers(value);
  14921. }
  14922. return resourceUrlBlacklist;
  14923. };
  14924. this.$get = ['$injector', function($injector) {
  14925. var htmlSanitizer = function htmlSanitizer(html) {
  14926. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  14927. };
  14928. if ($injector.has('$sanitize')) {
  14929. htmlSanitizer = $injector.get('$sanitize');
  14930. }
  14931. function matchUrl(matcher, parsedUrl) {
  14932. if (matcher === 'self') {
  14933. return urlIsSameOrigin(parsedUrl);
  14934. } else {
  14935. // definitely a regex. See adjustMatchers()
  14936. return !!matcher.exec(parsedUrl.href);
  14937. }
  14938. }
  14939. function isResourceUrlAllowedByPolicy(url) {
  14940. var parsedUrl = urlResolve(url.toString());
  14941. var i, n, allowed = false;
  14942. // Ensure that at least one item from the whitelist allows this url.
  14943. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  14944. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  14945. allowed = true;
  14946. break;
  14947. }
  14948. }
  14949. if (allowed) {
  14950. // Ensure that no item from the blacklist blocked this url.
  14951. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  14952. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  14953. allowed = false;
  14954. break;
  14955. }
  14956. }
  14957. }
  14958. return allowed;
  14959. }
  14960. function generateHolderType(Base) {
  14961. var holderType = function TrustedValueHolderType(trustedValue) {
  14962. this.$$unwrapTrustedValue = function() {
  14963. return trustedValue;
  14964. };
  14965. };
  14966. if (Base) {
  14967. holderType.prototype = new Base();
  14968. }
  14969. holderType.prototype.valueOf = function sceValueOf() {
  14970. return this.$$unwrapTrustedValue();
  14971. };
  14972. holderType.prototype.toString = function sceToString() {
  14973. return this.$$unwrapTrustedValue().toString();
  14974. };
  14975. return holderType;
  14976. }
  14977. var trustedValueHolderBase = generateHolderType(),
  14978. byType = {};
  14979. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  14980. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  14981. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  14982. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  14983. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  14984. /**
  14985. * @ngdoc method
  14986. * @name $sceDelegate#trustAs
  14987. *
  14988. * @description
  14989. * Returns an object that is trusted by angular for use in specified strict
  14990. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  14991. * attribute interpolation, any dom event binding attribute interpolation
  14992. * such as for onclick, etc.) that uses the provided value.
  14993. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  14994. *
  14995. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14996. * resourceUrl, html, js and css.
  14997. * @param {*} value The value that that should be considered trusted/safe.
  14998. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14999. * where Angular expects a $sce.trustAs() return value.
  15000. */
  15001. function trustAs(type, trustedValue) {
  15002. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15003. if (!Constructor) {
  15004. throw $sceMinErr('icontext',
  15005. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15006. type, trustedValue);
  15007. }
  15008. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  15009. return trustedValue;
  15010. }
  15011. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15012. // mutable objects, we ensure here that the value passed in is actually a string.
  15013. if (typeof trustedValue !== 'string') {
  15014. throw $sceMinErr('itype',
  15015. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15016. type);
  15017. }
  15018. return new Constructor(trustedValue);
  15019. }
  15020. /**
  15021. * @ngdoc method
  15022. * @name $sceDelegate#valueOf
  15023. *
  15024. * @description
  15025. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15026. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15027. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15028. *
  15029. * If the passed parameter is not a value that had been returned by {@link
  15030. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15031. *
  15032. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15033. * call or anything else.
  15034. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15035. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15036. * `value` unchanged.
  15037. */
  15038. function valueOf(maybeTrusted) {
  15039. if (maybeTrusted instanceof trustedValueHolderBase) {
  15040. return maybeTrusted.$$unwrapTrustedValue();
  15041. } else {
  15042. return maybeTrusted;
  15043. }
  15044. }
  15045. /**
  15046. * @ngdoc method
  15047. * @name $sceDelegate#getTrusted
  15048. *
  15049. * @description
  15050. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15051. * returns the originally supplied value if the queried context type is a supertype of the
  15052. * created type. If this condition isn't satisfied, throws an exception.
  15053. *
  15054. * @param {string} type The kind of context in which this value is to be used.
  15055. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15056. * `$sceDelegate.trustAs`} call.
  15057. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15058. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15059. */
  15060. function getTrusted(type, maybeTrusted) {
  15061. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  15062. return maybeTrusted;
  15063. }
  15064. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15065. if (constructor && maybeTrusted instanceof constructor) {
  15066. return maybeTrusted.$$unwrapTrustedValue();
  15067. }
  15068. // If we get here, then we may only take one of two actions.
  15069. // 1. sanitize the value for the requested type, or
  15070. // 2. throw an exception.
  15071. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15072. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15073. return maybeTrusted;
  15074. } else {
  15075. throw $sceMinErr('insecurl',
  15076. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15077. maybeTrusted.toString());
  15078. }
  15079. } else if (type === SCE_CONTEXTS.HTML) {
  15080. return htmlSanitizer(maybeTrusted);
  15081. }
  15082. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15083. }
  15084. return { trustAs: trustAs,
  15085. getTrusted: getTrusted,
  15086. valueOf: valueOf };
  15087. }];
  15088. }
  15089. /**
  15090. * @ngdoc provider
  15091. * @name $sceProvider
  15092. * @description
  15093. *
  15094. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15095. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15096. * - override the default implementation with a custom delegate
  15097. *
  15098. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15099. */
  15100. /* jshint maxlen: false*/
  15101. /**
  15102. * @ngdoc service
  15103. * @name $sce
  15104. * @kind function
  15105. *
  15106. * @description
  15107. *
  15108. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15109. *
  15110. * # Strict Contextual Escaping
  15111. *
  15112. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15113. * contexts to result in a value that is marked as safe to use for that context. One example of
  15114. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15115. * to these contexts as privileged or SCE contexts.
  15116. *
  15117. * As of version 1.2, Angular ships with SCE enabled by default.
  15118. *
  15119. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15120. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15121. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15122. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15123. * to the top of your HTML document.
  15124. *
  15125. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15126. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15127. *
  15128. * Here's an example of a binding in a privileged context:
  15129. *
  15130. * ```
  15131. * <input ng-model="userHtml" aria-label="User input">
  15132. * <div ng-bind-html="userHtml"></div>
  15133. * ```
  15134. *
  15135. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15136. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15137. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15138. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15139. * security vulnerabilities.)
  15140. *
  15141. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15142. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15143. *
  15144. * How would you ensure that every place that used these types of bindings was bound to a value that
  15145. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15146. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15147. * properties/fields and forgot to update the binding to the sanitized value?
  15148. *
  15149. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15150. * determine that something explicitly says it's safe to use a value for binding in that
  15151. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15152. * for those values that you can easily tell are safe - because they were received from your server,
  15153. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15154. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15155. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15156. *
  15157. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15158. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15159. * obtain values that will be accepted by SCE / privileged contexts.
  15160. *
  15161. *
  15162. * ## How does it work?
  15163. *
  15164. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15165. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15166. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15167. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15168. *
  15169. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15170. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15171. * simplified):
  15172. *
  15173. * ```
  15174. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15175. * return function(scope, element, attr) {
  15176. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15177. * element.html(value || '');
  15178. * });
  15179. * };
  15180. * }];
  15181. * ```
  15182. *
  15183. * ## Impact on loading templates
  15184. *
  15185. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15186. * `templateUrl`'s specified by {@link guide/directive directives}.
  15187. *
  15188. * By default, Angular only loads templates from the same domain and protocol as the application
  15189. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15190. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15191. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15192. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15193. *
  15194. * *Please note*:
  15195. * The browser's
  15196. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15197. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15198. * policy apply in addition to this and may further restrict whether the template is successfully
  15199. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15200. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15201. * browsers.
  15202. *
  15203. * ## This feels like too much overhead
  15204. *
  15205. * It's important to remember that SCE only applies to interpolation expressions.
  15206. *
  15207. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15208. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15209. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15210. *
  15211. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15212. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15213. *
  15214. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15215. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15216. * It blocks loading templates from other domains or loading templates over http from an https
  15217. * served document. You can change these by setting your own custom {@link
  15218. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15219. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15220. *
  15221. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15222. * application that's secure and can be audited to verify that with much more ease than bolting
  15223. * security onto an application later.
  15224. *
  15225. * <a name="contexts"></a>
  15226. * ## What trusted context types are supported?
  15227. *
  15228. * | Context | Notes |
  15229. * |---------------------|----------------|
  15230. * | `$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. |
  15231. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15232. * | `$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. |
  15233. * | `$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. |
  15234. * | `$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. |
  15235. *
  15236. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15237. *
  15238. * Each element in these arrays must be one of the following:
  15239. *
  15240. * - **'self'**
  15241. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15242. * domain** as the application document using the **same protocol**.
  15243. * - **String** (except the special value `'self'`)
  15244. * - The string is matched against the full *normalized / absolute URL* of the resource
  15245. * being tested (substring matches are not good enough.)
  15246. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15247. * match themselves.
  15248. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15249. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  15250. * in a whitelist.
  15251. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15252. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  15253. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15254. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15255. * http://foo.example.com/templates/**).
  15256. * - **RegExp** (*see caveat below*)
  15257. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15258. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15259. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15260. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  15261. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15262. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15263. * is highly recommended to use the string patterns and only fall back to regular expressions
  15264. * if they as a last resort.
  15265. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15266. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15267. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15268. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15269. * - If you are generating your JavaScript from some other templating engine (not
  15270. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15271. * remember to escape your regular expression (and be aware that you might need more than
  15272. * one level of escaping depending on your templating engine and the way you interpolated
  15273. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15274. * enough before coding your own. e.g. Ruby has
  15275. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15276. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15277. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15278. * Closure library's [goog.string.regExpEscape(s)](
  15279. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15280. *
  15281. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15282. *
  15283. * ## Show me an example using SCE.
  15284. *
  15285. * <example module="mySceApp" deps="angular-sanitize.js">
  15286. * <file name="index.html">
  15287. * <div ng-controller="AppController as myCtrl">
  15288. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15289. * <b>User comments</b><br>
  15290. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15291. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15292. * exploit.
  15293. * <div class="well">
  15294. * <div ng-repeat="userComment in myCtrl.userComments">
  15295. * <b>{{userComment.name}}</b>:
  15296. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15297. * <br>
  15298. * </div>
  15299. * </div>
  15300. * </div>
  15301. * </file>
  15302. *
  15303. * <file name="script.js">
  15304. * angular.module('mySceApp', ['ngSanitize'])
  15305. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15306. * function($http, $templateCache, $sce) {
  15307. * var self = this;
  15308. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15309. * self.userComments = userComments;
  15310. * });
  15311. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15312. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15313. * 'sanitization.&quot;">Hover over this text.</span>');
  15314. * }]);
  15315. * </file>
  15316. *
  15317. * <file name="test_data.json">
  15318. * [
  15319. * { "name": "Alice",
  15320. * "htmlComment":
  15321. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15322. * },
  15323. * { "name": "Bob",
  15324. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15325. * }
  15326. * ]
  15327. * </file>
  15328. *
  15329. * <file name="protractor.js" type="protractor">
  15330. * describe('SCE doc demo', function() {
  15331. * it('should sanitize untrusted values', function() {
  15332. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15333. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15334. * });
  15335. *
  15336. * it('should NOT sanitize explicitly trusted values', function() {
  15337. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15338. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15339. * 'sanitization.&quot;">Hover over this text.</span>');
  15340. * });
  15341. * });
  15342. * </file>
  15343. * </example>
  15344. *
  15345. *
  15346. *
  15347. * ## Can I disable SCE completely?
  15348. *
  15349. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15350. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15351. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15352. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15353. * you're migrating them a module at a time.
  15354. *
  15355. * That said, here's how you can completely disable SCE:
  15356. *
  15357. * ```
  15358. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15359. * // Completely disable SCE. For demonstration purposes only!
  15360. * // Do not use in new projects.
  15361. * $sceProvider.enabled(false);
  15362. * });
  15363. * ```
  15364. *
  15365. */
  15366. /* jshint maxlen: 100 */
  15367. function $SceProvider() {
  15368. var enabled = true;
  15369. /**
  15370. * @ngdoc method
  15371. * @name $sceProvider#enabled
  15372. * @kind function
  15373. *
  15374. * @param {boolean=} value If provided, then enables/disables SCE.
  15375. * @return {boolean} true if SCE is enabled, false otherwise.
  15376. *
  15377. * @description
  15378. * Enables/disables SCE and returns the current value.
  15379. */
  15380. this.enabled = function(value) {
  15381. if (arguments.length) {
  15382. enabled = !!value;
  15383. }
  15384. return enabled;
  15385. };
  15386. /* Design notes on the default implementation for SCE.
  15387. *
  15388. * The API contract for the SCE delegate
  15389. * -------------------------------------
  15390. * The SCE delegate object must provide the following 3 methods:
  15391. *
  15392. * - trustAs(contextEnum, value)
  15393. * This method is used to tell the SCE service that the provided value is OK to use in the
  15394. * contexts specified by contextEnum. It must return an object that will be accepted by
  15395. * getTrusted() for a compatible contextEnum and return this value.
  15396. *
  15397. * - valueOf(value)
  15398. * For values that were not produced by trustAs(), return them as is. For values that were
  15399. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15400. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15401. * such a value.
  15402. *
  15403. * - getTrusted(contextEnum, value)
  15404. * This function should return the a value that is safe to use in the context specified by
  15405. * contextEnum or throw and exception otherwise.
  15406. *
  15407. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15408. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15409. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15410. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15411. * return the same object passed in if it was found in the registry under a compatible context or
  15412. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15413. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15414. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15415. *
  15416. *
  15417. * A note on the inheritance model for SCE contexts
  15418. * ------------------------------------------------
  15419. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15420. * is purely an implementation details.
  15421. *
  15422. * The contract is simply this:
  15423. *
  15424. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15425. * will also succeed.
  15426. *
  15427. * Inheritance happens to capture this in a natural way. In some future, we
  15428. * may not use inheritance anymore. That is OK because no code outside of
  15429. * sce.js and sceSpecs.js would need to be aware of this detail.
  15430. */
  15431. this.$get = ['$parse', '$sceDelegate', function(
  15432. $parse, $sceDelegate) {
  15433. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15434. // the "expression(javascript expression)" syntax which is insecure.
  15435. if (enabled && msie < 8) {
  15436. throw $sceMinErr('iequirks',
  15437. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15438. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15439. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15440. }
  15441. var sce = shallowCopy(SCE_CONTEXTS);
  15442. /**
  15443. * @ngdoc method
  15444. * @name $sce#isEnabled
  15445. * @kind function
  15446. *
  15447. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15448. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15449. *
  15450. * @description
  15451. * Returns a boolean indicating if SCE is enabled.
  15452. */
  15453. sce.isEnabled = function() {
  15454. return enabled;
  15455. };
  15456. sce.trustAs = $sceDelegate.trustAs;
  15457. sce.getTrusted = $sceDelegate.getTrusted;
  15458. sce.valueOf = $sceDelegate.valueOf;
  15459. if (!enabled) {
  15460. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15461. sce.valueOf = identity;
  15462. }
  15463. /**
  15464. * @ngdoc method
  15465. * @name $sce#parseAs
  15466. *
  15467. * @description
  15468. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15469. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15470. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15471. * *result*)}
  15472. *
  15473. * @param {string} type The kind of SCE context in which this result will be used.
  15474. * @param {string} expression String expression to compile.
  15475. * @returns {function(context, locals)} a function which represents the compiled expression:
  15476. *
  15477. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15478. * are evaluated against (typically a scope object).
  15479. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15480. * `context`.
  15481. */
  15482. sce.parseAs = function sceParseAs(type, expr) {
  15483. var parsed = $parse(expr);
  15484. if (parsed.literal && parsed.constant) {
  15485. return parsed;
  15486. } else {
  15487. return $parse(expr, function(value) {
  15488. return sce.getTrusted(type, value);
  15489. });
  15490. }
  15491. };
  15492. /**
  15493. * @ngdoc method
  15494. * @name $sce#trustAs
  15495. *
  15496. * @description
  15497. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15498. * returns an object that is trusted by angular for use in specified strict contextual
  15499. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15500. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15501. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15502. * escaping.
  15503. *
  15504. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15505. * resourceUrl, html, js and css.
  15506. * @param {*} value The value that that should be considered trusted/safe.
  15507. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15508. * where Angular expects a $sce.trustAs() return value.
  15509. */
  15510. /**
  15511. * @ngdoc method
  15512. * @name $sce#trustAsHtml
  15513. *
  15514. * @description
  15515. * Shorthand method. `$sce.trustAsHtml(value)` →
  15516. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15517. *
  15518. * @param {*} value The value to trustAs.
  15519. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15520. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15521. * only accept expressions that are either literal constants or are the
  15522. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15523. */
  15524. /**
  15525. * @ngdoc method
  15526. * @name $sce#trustAsUrl
  15527. *
  15528. * @description
  15529. * Shorthand method. `$sce.trustAsUrl(value)` →
  15530. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15531. *
  15532. * @param {*} value The value to trustAs.
  15533. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15534. * $sce.getTrustedUrl(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#trustAsResourceUrl
  15541. *
  15542. * @description
  15543. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15544. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15545. *
  15546. * @param {*} value The value to trustAs.
  15547. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15548. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15549. * only accept expressions that are either literal constants or are the return
  15550. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15551. */
  15552. /**
  15553. * @ngdoc method
  15554. * @name $sce#trustAsJs
  15555. *
  15556. * @description
  15557. * Shorthand method. `$sce.trustAsJs(value)` →
  15558. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15559. *
  15560. * @param {*} value The value to trustAs.
  15561. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15562. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15563. * only accept expressions that are either literal constants or are the
  15564. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15565. */
  15566. /**
  15567. * @ngdoc method
  15568. * @name $sce#getTrusted
  15569. *
  15570. * @description
  15571. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15572. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15573. * originally supplied value if the queried context type is a supertype of the created type.
  15574. * If this condition isn't satisfied, throws an exception.
  15575. *
  15576. * @param {string} type The kind of context in which this value is to be used.
  15577. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15578. * call.
  15579. * @returns {*} The value the was originally provided to
  15580. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15581. * Otherwise, throws an exception.
  15582. */
  15583. /**
  15584. * @ngdoc method
  15585. * @name $sce#getTrustedHtml
  15586. *
  15587. * @description
  15588. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15589. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15590. *
  15591. * @param {*} value The value to pass to `$sce.getTrusted`.
  15592. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15593. */
  15594. /**
  15595. * @ngdoc method
  15596. * @name $sce#getTrustedCss
  15597. *
  15598. * @description
  15599. * Shorthand method. `$sce.getTrustedCss(value)` →
  15600. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15601. *
  15602. * @param {*} value The value to pass to `$sce.getTrusted`.
  15603. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15604. */
  15605. /**
  15606. * @ngdoc method
  15607. * @name $sce#getTrustedUrl
  15608. *
  15609. * @description
  15610. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15611. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15612. *
  15613. * @param {*} value The value to pass to `$sce.getTrusted`.
  15614. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15615. */
  15616. /**
  15617. * @ngdoc method
  15618. * @name $sce#getTrustedResourceUrl
  15619. *
  15620. * @description
  15621. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15622. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15623. *
  15624. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15625. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15626. */
  15627. /**
  15628. * @ngdoc method
  15629. * @name $sce#getTrustedJs
  15630. *
  15631. * @description
  15632. * Shorthand method. `$sce.getTrustedJs(value)` →
  15633. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15634. *
  15635. * @param {*} value The value to pass to `$sce.getTrusted`.
  15636. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15637. */
  15638. /**
  15639. * @ngdoc method
  15640. * @name $sce#parseAsHtml
  15641. *
  15642. * @description
  15643. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15644. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15645. *
  15646. * @param {string} expression String expression to compile.
  15647. * @returns {function(context, locals)} a function which represents the compiled expression:
  15648. *
  15649. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15650. * are evaluated against (typically a scope object).
  15651. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15652. * `context`.
  15653. */
  15654. /**
  15655. * @ngdoc method
  15656. * @name $sce#parseAsCss
  15657. *
  15658. * @description
  15659. * Shorthand method. `$sce.parseAsCss(value)` →
  15660. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15661. *
  15662. * @param {string} expression String expression to compile.
  15663. * @returns {function(context, locals)} a function which represents the compiled expression:
  15664. *
  15665. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15666. * are evaluated against (typically a scope object).
  15667. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15668. * `context`.
  15669. */
  15670. /**
  15671. * @ngdoc method
  15672. * @name $sce#parseAsUrl
  15673. *
  15674. * @description
  15675. * Shorthand method. `$sce.parseAsUrl(value)` →
  15676. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15677. *
  15678. * @param {string} expression String expression to compile.
  15679. * @returns {function(context, locals)} a function which represents the compiled expression:
  15680. *
  15681. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15682. * are evaluated against (typically a scope object).
  15683. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15684. * `context`.
  15685. */
  15686. /**
  15687. * @ngdoc method
  15688. * @name $sce#parseAsResourceUrl
  15689. *
  15690. * @description
  15691. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15692. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15693. *
  15694. * @param {string} expression String expression to compile.
  15695. * @returns {function(context, locals)} a function which represents the compiled expression:
  15696. *
  15697. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15698. * are evaluated against (typically a scope object).
  15699. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15700. * `context`.
  15701. */
  15702. /**
  15703. * @ngdoc method
  15704. * @name $sce#parseAsJs
  15705. *
  15706. * @description
  15707. * Shorthand method. `$sce.parseAsJs(value)` →
  15708. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15709. *
  15710. * @param {string} expression String expression to compile.
  15711. * @returns {function(context, locals)} a function which represents the compiled expression:
  15712. *
  15713. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15714. * are evaluated against (typically a scope object).
  15715. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15716. * `context`.
  15717. */
  15718. // Shorthand delegations.
  15719. var parse = sce.parseAs,
  15720. getTrusted = sce.getTrusted,
  15721. trustAs = sce.trustAs;
  15722. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15723. var lName = lowercase(name);
  15724. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15725. return parse(enumValue, expr);
  15726. };
  15727. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15728. return getTrusted(enumValue, value);
  15729. };
  15730. sce[camelCase("trust_as_" + lName)] = function(value) {
  15731. return trustAs(enumValue, value);
  15732. };
  15733. });
  15734. return sce;
  15735. }];
  15736. }
  15737. /**
  15738. * !!! This is an undocumented "private" service !!!
  15739. *
  15740. * @name $sniffer
  15741. * @requires $window
  15742. * @requires $document
  15743. *
  15744. * @property {boolean} history Does the browser support html5 history api ?
  15745. * @property {boolean} transitions Does the browser support CSS transition events ?
  15746. * @property {boolean} animations Does the browser support CSS animation events ?
  15747. *
  15748. * @description
  15749. * This is very simple implementation of testing browser's features.
  15750. */
  15751. function $SnifferProvider() {
  15752. this.$get = ['$window', '$document', function($window, $document) {
  15753. var eventSupport = {},
  15754. android =
  15755. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15756. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15757. document = $document[0] || {},
  15758. vendorPrefix,
  15759. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15760. bodyStyle = document.body && document.body.style,
  15761. transitions = false,
  15762. animations = false,
  15763. match;
  15764. if (bodyStyle) {
  15765. for (var prop in bodyStyle) {
  15766. if (match = vendorRegex.exec(prop)) {
  15767. vendorPrefix = match[0];
  15768. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15769. break;
  15770. }
  15771. }
  15772. if (!vendorPrefix) {
  15773. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15774. }
  15775. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15776. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15777. if (android && (!transitions || !animations)) {
  15778. transitions = isString(bodyStyle.webkitTransition);
  15779. animations = isString(bodyStyle.webkitAnimation);
  15780. }
  15781. }
  15782. return {
  15783. // Android has history.pushState, but it does not update location correctly
  15784. // so let's not use the history API at all.
  15785. // http://code.google.com/p/android/issues/detail?id=17471
  15786. // https://github.com/angular/angular.js/issues/904
  15787. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15788. // so let's not use the history API also
  15789. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15790. // jshint -W018
  15791. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15792. // jshint +W018
  15793. hasEvent: function(event) {
  15794. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15795. // it. In particular the event is not fired when backspace or delete key are pressed or
  15796. // when cut operation is performed.
  15797. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15798. // e.g. when placeholder changes, or a form is focused.
  15799. if (event === 'input' && msie <= 11) return false;
  15800. if (isUndefined(eventSupport[event])) {
  15801. var divElm = document.createElement('div');
  15802. eventSupport[event] = 'on' + event in divElm;
  15803. }
  15804. return eventSupport[event];
  15805. },
  15806. csp: csp(),
  15807. vendorPrefix: vendorPrefix,
  15808. transitions: transitions,
  15809. animations: animations,
  15810. android: android
  15811. };
  15812. }];
  15813. }
  15814. var $compileMinErr = minErr('$compile');
  15815. /**
  15816. * @ngdoc service
  15817. * @name $templateRequest
  15818. *
  15819. * @description
  15820. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  15821. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  15822. * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
  15823. * by setting the 2nd parameter of the function to true).
  15824. *
  15825. * @param {string} tpl The HTTP request template URL
  15826. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15827. *
  15828. * @return {Promise} a promise for the HTTP response data of the given URL.
  15829. *
  15830. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15831. */
  15832. function $TemplateRequestProvider() {
  15833. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  15834. function handleRequestFn(tpl, ignoreRequestError) {
  15835. handleRequestFn.totalPendingRequests++;
  15836. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15837. if (isArray(transformResponse)) {
  15838. transformResponse = transformResponse.filter(function(transformer) {
  15839. return transformer !== defaultHttpResponseTransform;
  15840. });
  15841. } else if (transformResponse === defaultHttpResponseTransform) {
  15842. transformResponse = null;
  15843. }
  15844. var httpOptions = {
  15845. cache: $templateCache,
  15846. transformResponse: transformResponse
  15847. };
  15848. return $http.get(tpl, httpOptions)
  15849. ['finally'](function() {
  15850. handleRequestFn.totalPendingRequests--;
  15851. })
  15852. .then(function(response) {
  15853. $templateCache.put(tpl, response.data);
  15854. return response.data;
  15855. }, handleError);
  15856. function handleError(resp) {
  15857. if (!ignoreRequestError) {
  15858. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15859. tpl, resp.status, resp.statusText);
  15860. }
  15861. return $q.reject(resp);
  15862. }
  15863. }
  15864. handleRequestFn.totalPendingRequests = 0;
  15865. return handleRequestFn;
  15866. }];
  15867. }
  15868. function $$TestabilityProvider() {
  15869. this.$get = ['$rootScope', '$browser', '$location',
  15870. function($rootScope, $browser, $location) {
  15871. /**
  15872. * @name $testability
  15873. *
  15874. * @description
  15875. * The private $$testability service provides a collection of methods for use when debugging
  15876. * or by automated test and debugging tools.
  15877. */
  15878. var testability = {};
  15879. /**
  15880. * @name $$testability#findBindings
  15881. *
  15882. * @description
  15883. * Returns an array of elements that are bound (via ng-bind or {{}})
  15884. * to expressions matching the input.
  15885. *
  15886. * @param {Element} element The element root to search from.
  15887. * @param {string} expression The binding expression to match.
  15888. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15889. * for the expression. Filters and whitespace are ignored.
  15890. */
  15891. testability.findBindings = function(element, expression, opt_exactMatch) {
  15892. var bindings = element.getElementsByClassName('ng-binding');
  15893. var matches = [];
  15894. forEach(bindings, function(binding) {
  15895. var dataBinding = angular.element(binding).data('$binding');
  15896. if (dataBinding) {
  15897. forEach(dataBinding, function(bindingName) {
  15898. if (opt_exactMatch) {
  15899. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  15900. if (matcher.test(bindingName)) {
  15901. matches.push(binding);
  15902. }
  15903. } else {
  15904. if (bindingName.indexOf(expression) != -1) {
  15905. matches.push(binding);
  15906. }
  15907. }
  15908. });
  15909. }
  15910. });
  15911. return matches;
  15912. };
  15913. /**
  15914. * @name $$testability#findModels
  15915. *
  15916. * @description
  15917. * Returns an array of elements that are two-way found via ng-model to
  15918. * expressions matching the input.
  15919. *
  15920. * @param {Element} element The element root to search from.
  15921. * @param {string} expression The model expression to match.
  15922. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15923. * for the expression.
  15924. */
  15925. testability.findModels = function(element, expression, opt_exactMatch) {
  15926. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  15927. for (var p = 0; p < prefixes.length; ++p) {
  15928. var attributeEquals = opt_exactMatch ? '=' : '*=';
  15929. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  15930. var elements = element.querySelectorAll(selector);
  15931. if (elements.length) {
  15932. return elements;
  15933. }
  15934. }
  15935. };
  15936. /**
  15937. * @name $$testability#getLocation
  15938. *
  15939. * @description
  15940. * Shortcut for getting the location in a browser agnostic way. Returns
  15941. * the path, search, and hash. (e.g. /path?a=b#hash)
  15942. */
  15943. testability.getLocation = function() {
  15944. return $location.url();
  15945. };
  15946. /**
  15947. * @name $$testability#setLocation
  15948. *
  15949. * @description
  15950. * Shortcut for navigating to a location without doing a full page reload.
  15951. *
  15952. * @param {string} url The location url (path, search and hash,
  15953. * e.g. /path?a=b#hash) to go to.
  15954. */
  15955. testability.setLocation = function(url) {
  15956. if (url !== $location.url()) {
  15957. $location.url(url);
  15958. $rootScope.$digest();
  15959. }
  15960. };
  15961. /**
  15962. * @name $$testability#whenStable
  15963. *
  15964. * @description
  15965. * Calls the callback when $timeout and $http requests are completed.
  15966. *
  15967. * @param {function} callback
  15968. */
  15969. testability.whenStable = function(callback) {
  15970. $browser.notifyWhenNoOutstandingRequests(callback);
  15971. };
  15972. return testability;
  15973. }];
  15974. }
  15975. function $TimeoutProvider() {
  15976. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  15977. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  15978. var deferreds = {};
  15979. /**
  15980. * @ngdoc service
  15981. * @name $timeout
  15982. *
  15983. * @description
  15984. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  15985. * block and delegates any exceptions to
  15986. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15987. *
  15988. * The return value of calling `$timeout` is a promise, which will be resolved when
  15989. * the delay has passed and the timeout function, if provided, is executed.
  15990. *
  15991. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  15992. *
  15993. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  15994. * synchronously flush the queue of deferred functions.
  15995. *
  15996. * If you only want a promise that will be resolved after some specified delay
  15997. * then you can call `$timeout` without the `fn` function.
  15998. *
  15999. * @param {function()=} fn A function, whose execution should be delayed.
  16000. * @param {number=} [delay=0] Delay in milliseconds.
  16001. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16002. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16003. * @param {...*=} Pass additional parameters to the executed function.
  16004. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16005. * promise will be resolved with is the return value of the `fn` function.
  16006. *
  16007. */
  16008. function timeout(fn, delay, invokeApply) {
  16009. if (!isFunction(fn)) {
  16010. invokeApply = delay;
  16011. delay = fn;
  16012. fn = noop;
  16013. }
  16014. var args = sliceArgs(arguments, 3),
  16015. skipApply = (isDefined(invokeApply) && !invokeApply),
  16016. deferred = (skipApply ? $$q : $q).defer(),
  16017. promise = deferred.promise,
  16018. timeoutId;
  16019. timeoutId = $browser.defer(function() {
  16020. try {
  16021. deferred.resolve(fn.apply(null, args));
  16022. } catch (e) {
  16023. deferred.reject(e);
  16024. $exceptionHandler(e);
  16025. }
  16026. finally {
  16027. delete deferreds[promise.$$timeoutId];
  16028. }
  16029. if (!skipApply) $rootScope.$apply();
  16030. }, delay);
  16031. promise.$$timeoutId = timeoutId;
  16032. deferreds[timeoutId] = deferred;
  16033. return promise;
  16034. }
  16035. /**
  16036. * @ngdoc method
  16037. * @name $timeout#cancel
  16038. *
  16039. * @description
  16040. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16041. * resolved with a rejection.
  16042. *
  16043. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16044. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16045. * canceled.
  16046. */
  16047. timeout.cancel = function(promise) {
  16048. if (promise && promise.$$timeoutId in deferreds) {
  16049. deferreds[promise.$$timeoutId].reject('canceled');
  16050. delete deferreds[promise.$$timeoutId];
  16051. return $browser.defer.cancel(promise.$$timeoutId);
  16052. }
  16053. return false;
  16054. };
  16055. return timeout;
  16056. }];
  16057. }
  16058. // NOTE: The usage of window and document instead of $window and $document here is
  16059. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16060. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16061. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16062. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16063. // exactly the behavior needed here. There is little value is mocking these out for this
  16064. // service.
  16065. var urlParsingNode = document.createElement("a");
  16066. var originUrl = urlResolve(window.location.href);
  16067. /**
  16068. *
  16069. * Implementation Notes for non-IE browsers
  16070. * ----------------------------------------
  16071. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16072. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16073. * URL will be resolved into an absolute URL in the context of the application document.
  16074. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16075. * properties are all populated to reflect the normalized URL. This approach has wide
  16076. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16077. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16078. *
  16079. * Implementation Notes for IE
  16080. * ---------------------------
  16081. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16082. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16083. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16084. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16085. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16086. * properties such as protocol, hostname, port, etc.
  16087. *
  16088. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  16089. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  16090. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  16091. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  16092. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  16093. * method and IE < 8 is unsupported.
  16094. *
  16095. * References:
  16096. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16097. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16098. * http://url.spec.whatwg.org/#urlutils
  16099. * https://github.com/angular/angular.js/pull/2902
  16100. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16101. *
  16102. * @kind function
  16103. * @param {string} url The URL to be parsed.
  16104. * @description Normalizes and parses a URL.
  16105. * @returns {object} Returns the normalized URL as a dictionary.
  16106. *
  16107. * | member name | Description |
  16108. * |---------------|----------------|
  16109. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16110. * | protocol | The protocol including the trailing colon |
  16111. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16112. * | search | The search params, minus the question mark |
  16113. * | hash | The hash string, minus the hash symbol
  16114. * | hostname | The hostname
  16115. * | port | The port, without ":"
  16116. * | pathname | The pathname, beginning with "/"
  16117. *
  16118. */
  16119. function urlResolve(url) {
  16120. var href = url;
  16121. if (msie) {
  16122. // Normalize before parse. Refer Implementation Notes on why this is
  16123. // done in two steps on IE.
  16124. urlParsingNode.setAttribute("href", href);
  16125. href = urlParsingNode.href;
  16126. }
  16127. urlParsingNode.setAttribute('href', href);
  16128. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16129. return {
  16130. href: urlParsingNode.href,
  16131. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16132. host: urlParsingNode.host,
  16133. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16134. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16135. hostname: urlParsingNode.hostname,
  16136. port: urlParsingNode.port,
  16137. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16138. ? urlParsingNode.pathname
  16139. : '/' + urlParsingNode.pathname
  16140. };
  16141. }
  16142. /**
  16143. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16144. *
  16145. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16146. * or a parsed URL object.
  16147. * @returns {boolean} Whether the request is for the same origin as the application document.
  16148. */
  16149. function urlIsSameOrigin(requestUrl) {
  16150. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16151. return (parsed.protocol === originUrl.protocol &&
  16152. parsed.host === originUrl.host);
  16153. }
  16154. /**
  16155. * @ngdoc service
  16156. * @name $window
  16157. *
  16158. * @description
  16159. * A reference to the browser's `window` object. While `window`
  16160. * is globally available in JavaScript, it causes testability problems, because
  16161. * it is a global variable. In angular we always refer to it through the
  16162. * `$window` service, so it may be overridden, removed or mocked for testing.
  16163. *
  16164. * Expressions, like the one defined for the `ngClick` directive in the example
  16165. * below, are evaluated with respect to the current scope. Therefore, there is
  16166. * no risk of inadvertently coding in a dependency on a global value in such an
  16167. * expression.
  16168. *
  16169. * @example
  16170. <example module="windowExample">
  16171. <file name="index.html">
  16172. <script>
  16173. angular.module('windowExample', [])
  16174. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16175. $scope.greeting = 'Hello, World!';
  16176. $scope.doGreeting = function(greeting) {
  16177. $window.alert(greeting);
  16178. };
  16179. }]);
  16180. </script>
  16181. <div ng-controller="ExampleController">
  16182. <input type="text" ng-model="greeting" aria-label="greeting" />
  16183. <button ng-click="doGreeting(greeting)">ALERT</button>
  16184. </div>
  16185. </file>
  16186. <file name="protractor.js" type="protractor">
  16187. it('should display the greeting in the input box', function() {
  16188. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16189. // If we click the button it will block the test runner
  16190. // element(':button').click();
  16191. });
  16192. </file>
  16193. </example>
  16194. */
  16195. function $WindowProvider() {
  16196. this.$get = valueFn(window);
  16197. }
  16198. /**
  16199. * @name $$cookieReader
  16200. * @requires $document
  16201. *
  16202. * @description
  16203. * This is a private service for reading cookies used by $http and ngCookies
  16204. *
  16205. * @return {Object} a key/value map of the current cookies
  16206. */
  16207. function $$CookieReader($document) {
  16208. var rawDocument = $document[0] || {};
  16209. var lastCookies = {};
  16210. var lastCookieString = '';
  16211. function safeDecodeURIComponent(str) {
  16212. try {
  16213. return decodeURIComponent(str);
  16214. } catch (e) {
  16215. return str;
  16216. }
  16217. }
  16218. return function() {
  16219. var cookieArray, cookie, i, index, name;
  16220. var currentCookieString = rawDocument.cookie || '';
  16221. if (currentCookieString !== lastCookieString) {
  16222. lastCookieString = currentCookieString;
  16223. cookieArray = lastCookieString.split('; ');
  16224. lastCookies = {};
  16225. for (i = 0; i < cookieArray.length; i++) {
  16226. cookie = cookieArray[i];
  16227. index = cookie.indexOf('=');
  16228. if (index > 0) { //ignore nameless cookies
  16229. name = safeDecodeURIComponent(cookie.substring(0, index));
  16230. // the first value that is seen for a cookie is the most
  16231. // specific one. values for the same cookie name that
  16232. // follow are for less specific paths.
  16233. if (lastCookies[name] === undefined) {
  16234. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16235. }
  16236. }
  16237. }
  16238. }
  16239. return lastCookies;
  16240. };
  16241. }
  16242. $$CookieReader.$inject = ['$document'];
  16243. function $$CookieReaderProvider() {
  16244. this.$get = $$CookieReader;
  16245. }
  16246. /* global currencyFilter: true,
  16247. dateFilter: true,
  16248. filterFilter: true,
  16249. jsonFilter: true,
  16250. limitToFilter: true,
  16251. lowercaseFilter: true,
  16252. numberFilter: true,
  16253. orderByFilter: true,
  16254. uppercaseFilter: true,
  16255. */
  16256. /**
  16257. * @ngdoc provider
  16258. * @name $filterProvider
  16259. * @description
  16260. *
  16261. * Filters are just functions which transform input to an output. However filters need to be
  16262. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16263. * annotated with dependencies and is responsible for creating a filter function.
  16264. *
  16265. * <div class="alert alert-warning">
  16266. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16267. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16268. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16269. * (`myapp_subsection_filterx`).
  16270. * </div>
  16271. *
  16272. * ```js
  16273. * // Filter registration
  16274. * function MyModule($provide, $filterProvider) {
  16275. * // create a service to demonstrate injection (not always needed)
  16276. * $provide.value('greet', function(name){
  16277. * return 'Hello ' + name + '!';
  16278. * });
  16279. *
  16280. * // register a filter factory which uses the
  16281. * // greet service to demonstrate DI.
  16282. * $filterProvider.register('greet', function(greet){
  16283. * // return the filter function which uses the greet service
  16284. * // to generate salutation
  16285. * return function(text) {
  16286. * // filters need to be forgiving so check input validity
  16287. * return text && greet(text) || text;
  16288. * };
  16289. * });
  16290. * }
  16291. * ```
  16292. *
  16293. * The filter function is registered with the `$injector` under the filter name suffix with
  16294. * `Filter`.
  16295. *
  16296. * ```js
  16297. * it('should be the same instance', inject(
  16298. * function($filterProvider) {
  16299. * $filterProvider.register('reverse', function(){
  16300. * return ...;
  16301. * });
  16302. * },
  16303. * function($filter, reverseFilter) {
  16304. * expect($filter('reverse')).toBe(reverseFilter);
  16305. * });
  16306. * ```
  16307. *
  16308. *
  16309. * For more information about how angular filters work, and how to create your own filters, see
  16310. * {@link guide/filter Filters} in the Angular Developer Guide.
  16311. */
  16312. /**
  16313. * @ngdoc service
  16314. * @name $filter
  16315. * @kind function
  16316. * @description
  16317. * Filters are used for formatting data displayed to the user.
  16318. *
  16319. * The general syntax in templates is as follows:
  16320. *
  16321. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16322. *
  16323. * @param {String} name Name of the filter function to retrieve
  16324. * @return {Function} the filter function
  16325. * @example
  16326. <example name="$filter" module="filterExample">
  16327. <file name="index.html">
  16328. <div ng-controller="MainCtrl">
  16329. <h3>{{ originalText }}</h3>
  16330. <h3>{{ filteredText }}</h3>
  16331. </div>
  16332. </file>
  16333. <file name="script.js">
  16334. angular.module('filterExample', [])
  16335. .controller('MainCtrl', function($scope, $filter) {
  16336. $scope.originalText = 'hello';
  16337. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16338. });
  16339. </file>
  16340. </example>
  16341. */
  16342. $FilterProvider.$inject = ['$provide'];
  16343. function $FilterProvider($provide) {
  16344. var suffix = 'Filter';
  16345. /**
  16346. * @ngdoc method
  16347. * @name $filterProvider#register
  16348. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16349. * the keys are the filter names and the values are the filter factories.
  16350. *
  16351. * <div class="alert alert-warning">
  16352. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16353. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16354. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16355. * (`myapp_subsection_filterx`).
  16356. * </div>
  16357. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16358. * of the registered filter instances.
  16359. */
  16360. function register(name, factory) {
  16361. if (isObject(name)) {
  16362. var filters = {};
  16363. forEach(name, function(filter, key) {
  16364. filters[key] = register(key, filter);
  16365. });
  16366. return filters;
  16367. } else {
  16368. return $provide.factory(name + suffix, factory);
  16369. }
  16370. }
  16371. this.register = register;
  16372. this.$get = ['$injector', function($injector) {
  16373. return function(name) {
  16374. return $injector.get(name + suffix);
  16375. };
  16376. }];
  16377. ////////////////////////////////////////
  16378. /* global
  16379. currencyFilter: false,
  16380. dateFilter: false,
  16381. filterFilter: false,
  16382. jsonFilter: false,
  16383. limitToFilter: false,
  16384. lowercaseFilter: false,
  16385. numberFilter: false,
  16386. orderByFilter: false,
  16387. uppercaseFilter: false,
  16388. */
  16389. register('currency', currencyFilter);
  16390. register('date', dateFilter);
  16391. register('filter', filterFilter);
  16392. register('json', jsonFilter);
  16393. register('limitTo', limitToFilter);
  16394. register('lowercase', lowercaseFilter);
  16395. register('number', numberFilter);
  16396. register('orderBy', orderByFilter);
  16397. register('uppercase', uppercaseFilter);
  16398. }
  16399. /**
  16400. * @ngdoc filter
  16401. * @name filter
  16402. * @kind function
  16403. *
  16404. * @description
  16405. * Selects a subset of items from `array` and returns it as a new array.
  16406. *
  16407. * @param {Array} array The source array.
  16408. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16409. * `array`.
  16410. *
  16411. * Can be one of:
  16412. *
  16413. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16414. * objects with string properties in `array` that match this string will be returned. This also
  16415. * applies to nested object properties.
  16416. * The predicate can be negated by prefixing the string with `!`.
  16417. *
  16418. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16419. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16420. * which have property `name` containing "M" and property `phone` containing "1". A special
  16421. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16422. * property of the object or its nested object properties. That's equivalent to the simple
  16423. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16424. * the string with `!`.
  16425. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16426. * not containing "M".
  16427. *
  16428. * Note that a named property will match properties on the same level only, while the special
  16429. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16430. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16431. * **will** be matched by `{$: 'John'}`.
  16432. *
  16433. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16434. * The function is called for each element of the array, with the element, its index, and
  16435. * the entire array itself as arguments.
  16436. *
  16437. * The final result is an array of those elements that the predicate returned true for.
  16438. *
  16439. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16440. * determining if the expected value (from the filter expression) and actual value (from
  16441. * the object in the array) should be considered a match.
  16442. *
  16443. * Can be one of:
  16444. *
  16445. * - `function(actual, expected)`:
  16446. * The function will be given the object value and the predicate value to compare and
  16447. * should return true if both values should be considered equal.
  16448. *
  16449. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16450. * This is essentially strict comparison of expected and actual.
  16451. *
  16452. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16453. * insensitive way.
  16454. *
  16455. * Primitive values are converted to strings. Objects are not compared against primitives,
  16456. * unless they have a custom `toString` method (e.g. `Date` objects).
  16457. *
  16458. * @example
  16459. <example>
  16460. <file name="index.html">
  16461. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16462. {name:'Mary', phone:'800-BIG-MARY'},
  16463. {name:'Mike', phone:'555-4321'},
  16464. {name:'Adam', phone:'555-5678'},
  16465. {name:'Julie', phone:'555-8765'},
  16466. {name:'Juliette', phone:'555-5678'}]"></div>
  16467. <label>Search: <input ng-model="searchText"></label>
  16468. <table id="searchTextResults">
  16469. <tr><th>Name</th><th>Phone</th></tr>
  16470. <tr ng-repeat="friend in friends | filter:searchText">
  16471. <td>{{friend.name}}</td>
  16472. <td>{{friend.phone}}</td>
  16473. </tr>
  16474. </table>
  16475. <hr>
  16476. <label>Any: <input ng-model="search.$"></label> <br>
  16477. <label>Name only <input ng-model="search.name"></label><br>
  16478. <label>Phone only <input ng-model="search.phone"></label><br>
  16479. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16480. <table id="searchObjResults">
  16481. <tr><th>Name</th><th>Phone</th></tr>
  16482. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16483. <td>{{friendObj.name}}</td>
  16484. <td>{{friendObj.phone}}</td>
  16485. </tr>
  16486. </table>
  16487. </file>
  16488. <file name="protractor.js" type="protractor">
  16489. var expectFriendNames = function(expectedNames, key) {
  16490. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16491. arr.forEach(function(wd, i) {
  16492. expect(wd.getText()).toMatch(expectedNames[i]);
  16493. });
  16494. });
  16495. };
  16496. it('should search across all fields when filtering with a string', function() {
  16497. var searchText = element(by.model('searchText'));
  16498. searchText.clear();
  16499. searchText.sendKeys('m');
  16500. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16501. searchText.clear();
  16502. searchText.sendKeys('76');
  16503. expectFriendNames(['John', 'Julie'], 'friend');
  16504. });
  16505. it('should search in specific fields when filtering with a predicate object', function() {
  16506. var searchAny = element(by.model('search.$'));
  16507. searchAny.clear();
  16508. searchAny.sendKeys('i');
  16509. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16510. });
  16511. it('should use a equal comparison when comparator is true', function() {
  16512. var searchName = element(by.model('search.name'));
  16513. var strict = element(by.model('strict'));
  16514. searchName.clear();
  16515. searchName.sendKeys('Julie');
  16516. strict.click();
  16517. expectFriendNames(['Julie'], 'friendObj');
  16518. });
  16519. </file>
  16520. </example>
  16521. */
  16522. function filterFilter() {
  16523. return function(array, expression, comparator) {
  16524. if (!isArrayLike(array)) {
  16525. if (array == null) {
  16526. return array;
  16527. } else {
  16528. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16529. }
  16530. }
  16531. var expressionType = getTypeForFilter(expression);
  16532. var predicateFn;
  16533. var matchAgainstAnyProp;
  16534. switch (expressionType) {
  16535. case 'function':
  16536. predicateFn = expression;
  16537. break;
  16538. case 'boolean':
  16539. case 'null':
  16540. case 'number':
  16541. case 'string':
  16542. matchAgainstAnyProp = true;
  16543. //jshint -W086
  16544. case 'object':
  16545. //jshint +W086
  16546. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16547. break;
  16548. default:
  16549. return array;
  16550. }
  16551. return Array.prototype.filter.call(array, predicateFn);
  16552. };
  16553. }
  16554. function hasCustomToString(obj) {
  16555. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  16556. }
  16557. // Helper functions for `filterFilter`
  16558. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16559. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16560. var predicateFn;
  16561. if (comparator === true) {
  16562. comparator = equals;
  16563. } else if (!isFunction(comparator)) {
  16564. comparator = function(actual, expected) {
  16565. if (isUndefined(actual)) {
  16566. // No substring matching against `undefined`
  16567. return false;
  16568. }
  16569. if ((actual === null) || (expected === null)) {
  16570. // No substring matching against `null`; only match against `null`
  16571. return actual === expected;
  16572. }
  16573. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16574. // Should not compare primitives against objects, unless they have custom `toString` method
  16575. return false;
  16576. }
  16577. actual = lowercase('' + actual);
  16578. expected = lowercase('' + expected);
  16579. return actual.indexOf(expected) !== -1;
  16580. };
  16581. }
  16582. predicateFn = function(item) {
  16583. if (shouldMatchPrimitives && !isObject(item)) {
  16584. return deepCompare(item, expression.$, comparator, false);
  16585. }
  16586. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16587. };
  16588. return predicateFn;
  16589. }
  16590. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16591. var actualType = getTypeForFilter(actual);
  16592. var expectedType = getTypeForFilter(expected);
  16593. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16594. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16595. } else if (isArray(actual)) {
  16596. // In case `actual` is an array, consider it a match
  16597. // if ANY of it's items matches `expected`
  16598. return actual.some(function(item) {
  16599. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16600. });
  16601. }
  16602. switch (actualType) {
  16603. case 'object':
  16604. var key;
  16605. if (matchAgainstAnyProp) {
  16606. for (key in actual) {
  16607. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16608. return true;
  16609. }
  16610. }
  16611. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16612. } else if (expectedType === 'object') {
  16613. for (key in expected) {
  16614. var expectedVal = expected[key];
  16615. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16616. continue;
  16617. }
  16618. var matchAnyProperty = key === '$';
  16619. var actualVal = matchAnyProperty ? actual : actual[key];
  16620. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16621. return false;
  16622. }
  16623. }
  16624. return true;
  16625. } else {
  16626. return comparator(actual, expected);
  16627. }
  16628. break;
  16629. case 'function':
  16630. return false;
  16631. default:
  16632. return comparator(actual, expected);
  16633. }
  16634. }
  16635. // Used for easily differentiating between `null` and actual `object`
  16636. function getTypeForFilter(val) {
  16637. return (val === null) ? 'null' : typeof val;
  16638. }
  16639. /**
  16640. * @ngdoc filter
  16641. * @name currency
  16642. * @kind function
  16643. *
  16644. * @description
  16645. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16646. * symbol for current locale is used.
  16647. *
  16648. * @param {number} amount Input to filter.
  16649. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16650. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16651. * @returns {string} Formatted number.
  16652. *
  16653. *
  16654. * @example
  16655. <example module="currencyExample">
  16656. <file name="index.html">
  16657. <script>
  16658. angular.module('currencyExample', [])
  16659. .controller('ExampleController', ['$scope', function($scope) {
  16660. $scope.amount = 1234.56;
  16661. }]);
  16662. </script>
  16663. <div ng-controller="ExampleController">
  16664. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16665. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16666. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16667. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16668. </div>
  16669. </file>
  16670. <file name="protractor.js" type="protractor">
  16671. it('should init with 1234.56', function() {
  16672. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16673. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16674. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16675. });
  16676. it('should update', function() {
  16677. if (browser.params.browser == 'safari') {
  16678. // Safari does not understand the minus key. See
  16679. // https://github.com/angular/protractor/issues/481
  16680. return;
  16681. }
  16682. element(by.model('amount')).clear();
  16683. element(by.model('amount')).sendKeys('-1234');
  16684. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  16685. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  16686. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  16687. });
  16688. </file>
  16689. </example>
  16690. */
  16691. currencyFilter.$inject = ['$locale'];
  16692. function currencyFilter($locale) {
  16693. var formats = $locale.NUMBER_FORMATS;
  16694. return function(amount, currencySymbol, fractionSize) {
  16695. if (isUndefined(currencySymbol)) {
  16696. currencySymbol = formats.CURRENCY_SYM;
  16697. }
  16698. if (isUndefined(fractionSize)) {
  16699. fractionSize = formats.PATTERNS[1].maxFrac;
  16700. }
  16701. // if null or undefined pass it through
  16702. return (amount == null)
  16703. ? amount
  16704. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16705. replace(/\u00A4/g, currencySymbol);
  16706. };
  16707. }
  16708. /**
  16709. * @ngdoc filter
  16710. * @name number
  16711. * @kind function
  16712. *
  16713. * @description
  16714. * Formats a number as text.
  16715. *
  16716. * If the input is null or undefined, it will just be returned.
  16717. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16718. * If the input is not a number an empty string is returned.
  16719. *
  16720. *
  16721. * @param {number|string} number Number to format.
  16722. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16723. * If this is not provided then the fraction size is computed from the current locale's number
  16724. * formatting pattern. In the case of the default locale, it will be 3.
  16725. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16726. *
  16727. * @example
  16728. <example module="numberFilterExample">
  16729. <file name="index.html">
  16730. <script>
  16731. angular.module('numberFilterExample', [])
  16732. .controller('ExampleController', ['$scope', function($scope) {
  16733. $scope.val = 1234.56789;
  16734. }]);
  16735. </script>
  16736. <div ng-controller="ExampleController">
  16737. <label>Enter number: <input ng-model='val'></label><br>
  16738. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16739. No fractions: <span>{{val | number:0}}</span><br>
  16740. Negative number: <span>{{-val | number:4}}</span>
  16741. </div>
  16742. </file>
  16743. <file name="protractor.js" type="protractor">
  16744. it('should format numbers', function() {
  16745. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16746. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16747. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16748. });
  16749. it('should update', function() {
  16750. element(by.model('val')).clear();
  16751. element(by.model('val')).sendKeys('3374.333');
  16752. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16753. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16754. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16755. });
  16756. </file>
  16757. </example>
  16758. */
  16759. numberFilter.$inject = ['$locale'];
  16760. function numberFilter($locale) {
  16761. var formats = $locale.NUMBER_FORMATS;
  16762. return function(number, fractionSize) {
  16763. // if null or undefined pass it through
  16764. return (number == null)
  16765. ? number
  16766. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16767. fractionSize);
  16768. };
  16769. }
  16770. var DECIMAL_SEP = '.';
  16771. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16772. if (isObject(number)) return '';
  16773. var isNegative = number < 0;
  16774. number = Math.abs(number);
  16775. var isInfinity = number === Infinity;
  16776. if (!isInfinity && !isFinite(number)) return '';
  16777. var numStr = number + '',
  16778. formatedText = '',
  16779. hasExponent = false,
  16780. parts = [];
  16781. if (isInfinity) formatedText = '\u221e';
  16782. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16783. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16784. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16785. number = 0;
  16786. } else {
  16787. formatedText = numStr;
  16788. hasExponent = true;
  16789. }
  16790. }
  16791. if (!isInfinity && !hasExponent) {
  16792. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16793. // determine fractionSize if it is not specified
  16794. if (isUndefined(fractionSize)) {
  16795. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16796. }
  16797. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16798. // inspired by:
  16799. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16800. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16801. var fraction = ('' + number).split(DECIMAL_SEP);
  16802. var whole = fraction[0];
  16803. fraction = fraction[1] || '';
  16804. var i, pos = 0,
  16805. lgroup = pattern.lgSize,
  16806. group = pattern.gSize;
  16807. if (whole.length >= (lgroup + group)) {
  16808. pos = whole.length - lgroup;
  16809. for (i = 0; i < pos; i++) {
  16810. if ((pos - i) % group === 0 && i !== 0) {
  16811. formatedText += groupSep;
  16812. }
  16813. formatedText += whole.charAt(i);
  16814. }
  16815. }
  16816. for (i = pos; i < whole.length; i++) {
  16817. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16818. formatedText += groupSep;
  16819. }
  16820. formatedText += whole.charAt(i);
  16821. }
  16822. // format fraction part.
  16823. while (fraction.length < fractionSize) {
  16824. fraction += '0';
  16825. }
  16826. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16827. } else {
  16828. if (fractionSize > 0 && number < 1) {
  16829. formatedText = number.toFixed(fractionSize);
  16830. number = parseFloat(formatedText);
  16831. }
  16832. }
  16833. if (number === 0) {
  16834. isNegative = false;
  16835. }
  16836. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16837. formatedText,
  16838. isNegative ? pattern.negSuf : pattern.posSuf);
  16839. return parts.join('');
  16840. }
  16841. function padNumber(num, digits, trim) {
  16842. var neg = '';
  16843. if (num < 0) {
  16844. neg = '-';
  16845. num = -num;
  16846. }
  16847. num = '' + num;
  16848. while (num.length < digits) num = '0' + num;
  16849. if (trim) {
  16850. num = num.substr(num.length - digits);
  16851. }
  16852. return neg + num;
  16853. }
  16854. function dateGetter(name, size, offset, trim) {
  16855. offset = offset || 0;
  16856. return function(date) {
  16857. var value = date['get' + name]();
  16858. if (offset > 0 || value > -offset) {
  16859. value += offset;
  16860. }
  16861. if (value === 0 && offset == -12) value = 12;
  16862. return padNumber(value, size, trim);
  16863. };
  16864. }
  16865. function dateStrGetter(name, shortForm) {
  16866. return function(date, formats) {
  16867. var value = date['get' + name]();
  16868. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16869. return formats[get][value];
  16870. };
  16871. }
  16872. function timeZoneGetter(date, formats, offset) {
  16873. var zone = -1 * offset;
  16874. var paddedZone = (zone >= 0) ? "+" : "";
  16875. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16876. padNumber(Math.abs(zone % 60), 2);
  16877. return paddedZone;
  16878. }
  16879. function getFirstThursdayOfYear(year) {
  16880. // 0 = index of January
  16881. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16882. // 4 = index of Thursday (+1 to account for 1st = 5)
  16883. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16884. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16885. }
  16886. function getThursdayThisWeek(datetime) {
  16887. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16888. // 4 = index of Thursday
  16889. datetime.getDate() + (4 - datetime.getDay()));
  16890. }
  16891. function weekGetter(size) {
  16892. return function(date) {
  16893. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16894. thisThurs = getThursdayThisWeek(date);
  16895. var diff = +thisThurs - +firstThurs,
  16896. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16897. return padNumber(result, size);
  16898. };
  16899. }
  16900. function ampmGetter(date, formats) {
  16901. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16902. }
  16903. function eraGetter(date, formats) {
  16904. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16905. }
  16906. function longEraGetter(date, formats) {
  16907. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  16908. }
  16909. var DATE_FORMATS = {
  16910. yyyy: dateGetter('FullYear', 4),
  16911. yy: dateGetter('FullYear', 2, 0, true),
  16912. y: dateGetter('FullYear', 1),
  16913. MMMM: dateStrGetter('Month'),
  16914. MMM: dateStrGetter('Month', true),
  16915. MM: dateGetter('Month', 2, 1),
  16916. M: dateGetter('Month', 1, 1),
  16917. dd: dateGetter('Date', 2),
  16918. d: dateGetter('Date', 1),
  16919. HH: dateGetter('Hours', 2),
  16920. H: dateGetter('Hours', 1),
  16921. hh: dateGetter('Hours', 2, -12),
  16922. h: dateGetter('Hours', 1, -12),
  16923. mm: dateGetter('Minutes', 2),
  16924. m: dateGetter('Minutes', 1),
  16925. ss: dateGetter('Seconds', 2),
  16926. s: dateGetter('Seconds', 1),
  16927. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  16928. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  16929. sss: dateGetter('Milliseconds', 3),
  16930. EEEE: dateStrGetter('Day'),
  16931. EEE: dateStrGetter('Day', true),
  16932. a: ampmGetter,
  16933. Z: timeZoneGetter,
  16934. ww: weekGetter(2),
  16935. w: weekGetter(1),
  16936. G: eraGetter,
  16937. GG: eraGetter,
  16938. GGG: eraGetter,
  16939. GGGG: longEraGetter
  16940. };
  16941. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  16942. NUMBER_STRING = /^\-?\d+$/;
  16943. /**
  16944. * @ngdoc filter
  16945. * @name date
  16946. * @kind function
  16947. *
  16948. * @description
  16949. * Formats `date` to a string based on the requested `format`.
  16950. *
  16951. * `format` string can be composed of the following elements:
  16952. *
  16953. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  16954. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  16955. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  16956. * * `'MMMM'`: Month in year (January-December)
  16957. * * `'MMM'`: Month in year (Jan-Dec)
  16958. * * `'MM'`: Month in year, padded (01-12)
  16959. * * `'M'`: Month in year (1-12)
  16960. * * `'dd'`: Day in month, padded (01-31)
  16961. * * `'d'`: Day in month (1-31)
  16962. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  16963. * * `'EEE'`: Day in Week, (Sun-Sat)
  16964. * * `'HH'`: Hour in day, padded (00-23)
  16965. * * `'H'`: Hour in day (0-23)
  16966. * * `'hh'`: Hour in AM/PM, padded (01-12)
  16967. * * `'h'`: Hour in AM/PM, (1-12)
  16968. * * `'mm'`: Minute in hour, padded (00-59)
  16969. * * `'m'`: Minute in hour (0-59)
  16970. * * `'ss'`: Second in minute, padded (00-59)
  16971. * * `'s'`: Second in minute (0-59)
  16972. * * `'sss'`: Millisecond in second, padded (000-999)
  16973. * * `'a'`: AM/PM marker
  16974. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  16975. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  16976. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  16977. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  16978. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  16979. *
  16980. * `format` string can also be one of the following predefined
  16981. * {@link guide/i18n localizable formats}:
  16982. *
  16983. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  16984. * (e.g. Sep 3, 2010 12:05:08 PM)
  16985. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  16986. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  16987. * (e.g. Friday, September 3, 2010)
  16988. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  16989. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  16990. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  16991. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  16992. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  16993. *
  16994. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  16995. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  16996. * (e.g. `"h 'o''clock'"`).
  16997. *
  16998. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  16999. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17000. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17001. * specified in the string input, the time is considered to be in the local timezone.
  17002. * @param {string=} format Formatting rules (see Description). If not specified,
  17003. * `mediumDate` is used.
  17004. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17005. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17006. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17007. * If not specified, the timezone of the browser will be used.
  17008. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17009. *
  17010. * @example
  17011. <example>
  17012. <file name="index.html">
  17013. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17014. <span>{{1288323623006 | date:'medium'}}</span><br>
  17015. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17016. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17017. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17018. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17019. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17020. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17021. </file>
  17022. <file name="protractor.js" type="protractor">
  17023. it('should format date', function() {
  17024. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17025. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17026. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17027. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17028. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17029. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17030. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17031. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17032. });
  17033. </file>
  17034. </example>
  17035. */
  17036. dateFilter.$inject = ['$locale'];
  17037. function dateFilter($locale) {
  17038. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17039. // 1 2 3 4 5 6 7 8 9 10 11
  17040. function jsonStringToDate(string) {
  17041. var match;
  17042. if (match = string.match(R_ISO8601_STR)) {
  17043. var date = new Date(0),
  17044. tzHour = 0,
  17045. tzMin = 0,
  17046. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17047. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17048. if (match[9]) {
  17049. tzHour = toInt(match[9] + match[10]);
  17050. tzMin = toInt(match[9] + match[11]);
  17051. }
  17052. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17053. var h = toInt(match[4] || 0) - tzHour;
  17054. var m = toInt(match[5] || 0) - tzMin;
  17055. var s = toInt(match[6] || 0);
  17056. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17057. timeSetter.call(date, h, m, s, ms);
  17058. return date;
  17059. }
  17060. return string;
  17061. }
  17062. return function(date, format, timezone) {
  17063. var text = '',
  17064. parts = [],
  17065. fn, match;
  17066. format = format || 'mediumDate';
  17067. format = $locale.DATETIME_FORMATS[format] || format;
  17068. if (isString(date)) {
  17069. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17070. }
  17071. if (isNumber(date)) {
  17072. date = new Date(date);
  17073. }
  17074. if (!isDate(date) || !isFinite(date.getTime())) {
  17075. return date;
  17076. }
  17077. while (format) {
  17078. match = DATE_FORMATS_SPLIT.exec(format);
  17079. if (match) {
  17080. parts = concat(parts, match, 1);
  17081. format = parts.pop();
  17082. } else {
  17083. parts.push(format);
  17084. format = null;
  17085. }
  17086. }
  17087. var dateTimezoneOffset = date.getTimezoneOffset();
  17088. if (timezone) {
  17089. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17090. date = convertTimezoneToLocal(date, timezone, true);
  17091. }
  17092. forEach(parts, function(value) {
  17093. fn = DATE_FORMATS[value];
  17094. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17095. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17096. });
  17097. return text;
  17098. };
  17099. }
  17100. /**
  17101. * @ngdoc filter
  17102. * @name json
  17103. * @kind function
  17104. *
  17105. * @description
  17106. * Allows you to convert a JavaScript object into JSON string.
  17107. *
  17108. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17109. * the binding is automatically converted to JSON.
  17110. *
  17111. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17112. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17113. * @returns {string} JSON string.
  17114. *
  17115. *
  17116. * @example
  17117. <example>
  17118. <file name="index.html">
  17119. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17120. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17121. </file>
  17122. <file name="protractor.js" type="protractor">
  17123. it('should jsonify filtered objects', function() {
  17124. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17125. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17126. });
  17127. </file>
  17128. </example>
  17129. *
  17130. */
  17131. function jsonFilter() {
  17132. return function(object, spacing) {
  17133. if (isUndefined(spacing)) {
  17134. spacing = 2;
  17135. }
  17136. return toJson(object, spacing);
  17137. };
  17138. }
  17139. /**
  17140. * @ngdoc filter
  17141. * @name lowercase
  17142. * @kind function
  17143. * @description
  17144. * Converts string to lowercase.
  17145. * @see angular.lowercase
  17146. */
  17147. var lowercaseFilter = valueFn(lowercase);
  17148. /**
  17149. * @ngdoc filter
  17150. * @name uppercase
  17151. * @kind function
  17152. * @description
  17153. * Converts string to uppercase.
  17154. * @see angular.uppercase
  17155. */
  17156. var uppercaseFilter = valueFn(uppercase);
  17157. /**
  17158. * @ngdoc filter
  17159. * @name limitTo
  17160. * @kind function
  17161. *
  17162. * @description
  17163. * Creates a new array or string containing only a specified number of elements. The elements
  17164. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17165. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17166. * converted to a string.
  17167. *
  17168. * @param {Array|string|number} input Source array, string or number to be limited.
  17169. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17170. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17171. * If the number is negative, `limit` number of items from the end of the source array/string
  17172. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17173. * the input will be returned unchanged.
  17174. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17175. * indicates an offset from the end of `input`. Defaults to `0`.
  17176. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17177. * had less than `limit` elements.
  17178. *
  17179. * @example
  17180. <example module="limitToExample">
  17181. <file name="index.html">
  17182. <script>
  17183. angular.module('limitToExample', [])
  17184. .controller('ExampleController', ['$scope', function($scope) {
  17185. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17186. $scope.letters = "abcdefghi";
  17187. $scope.longNumber = 2345432342;
  17188. $scope.numLimit = 3;
  17189. $scope.letterLimit = 3;
  17190. $scope.longNumberLimit = 3;
  17191. }]);
  17192. </script>
  17193. <div ng-controller="ExampleController">
  17194. <label>
  17195. Limit {{numbers}} to:
  17196. <input type="number" step="1" ng-model="numLimit">
  17197. </label>
  17198. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17199. <label>
  17200. Limit {{letters}} to:
  17201. <input type="number" step="1" ng-model="letterLimit">
  17202. </label>
  17203. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17204. <label>
  17205. Limit {{longNumber}} to:
  17206. <input type="number" step="1" ng-model="longNumberLimit">
  17207. </label>
  17208. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17209. </div>
  17210. </file>
  17211. <file name="protractor.js" type="protractor">
  17212. var numLimitInput = element(by.model('numLimit'));
  17213. var letterLimitInput = element(by.model('letterLimit'));
  17214. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17215. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17216. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17217. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17218. it('should limit the number array to first three items', function() {
  17219. expect(numLimitInput.getAttribute('value')).toBe('3');
  17220. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17221. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17222. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17223. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17224. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17225. });
  17226. // There is a bug in safari and protractor that doesn't like the minus key
  17227. // it('should update the output when -3 is entered', function() {
  17228. // numLimitInput.clear();
  17229. // numLimitInput.sendKeys('-3');
  17230. // letterLimitInput.clear();
  17231. // letterLimitInput.sendKeys('-3');
  17232. // longNumberLimitInput.clear();
  17233. // longNumberLimitInput.sendKeys('-3');
  17234. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17235. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17236. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17237. // });
  17238. it('should not exceed the maximum size of input array', function() {
  17239. numLimitInput.clear();
  17240. numLimitInput.sendKeys('100');
  17241. letterLimitInput.clear();
  17242. letterLimitInput.sendKeys('100');
  17243. longNumberLimitInput.clear();
  17244. longNumberLimitInput.sendKeys('100');
  17245. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17246. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17247. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17248. });
  17249. </file>
  17250. </example>
  17251. */
  17252. function limitToFilter() {
  17253. return function(input, limit, begin) {
  17254. if (Math.abs(Number(limit)) === Infinity) {
  17255. limit = Number(limit);
  17256. } else {
  17257. limit = toInt(limit);
  17258. }
  17259. if (isNaN(limit)) return input;
  17260. if (isNumber(input)) input = input.toString();
  17261. if (!isArray(input) && !isString(input)) return input;
  17262. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17263. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17264. if (limit >= 0) {
  17265. return input.slice(begin, begin + limit);
  17266. } else {
  17267. if (begin === 0) {
  17268. return input.slice(limit, input.length);
  17269. } else {
  17270. return input.slice(Math.max(0, begin + limit), begin);
  17271. }
  17272. }
  17273. };
  17274. }
  17275. /**
  17276. * @ngdoc filter
  17277. * @name orderBy
  17278. * @kind function
  17279. *
  17280. * @description
  17281. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17282. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17283. * as expected, make sure they are actually being saved as numbers and not strings.
  17284. *
  17285. * @param {Array} array The array to sort.
  17286. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17287. * used by the comparator to determine the order of elements.
  17288. *
  17289. * Can be one of:
  17290. *
  17291. * - `function`: Getter function. The result of this function will be sorted using the
  17292. * `<`, `===`, `>` operator.
  17293. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17294. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17295. * 3 first characters of a property called `name`). The result of a constant expression
  17296. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17297. * to sort object by the value of their `special name` property). An expression can be
  17298. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17299. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17300. * element itself is used to compare where sorting.
  17301. * - `Array`: An array of function or string predicates. The first predicate in the array
  17302. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17303. *
  17304. * If the predicate is missing or empty then it defaults to `'+'`.
  17305. *
  17306. * @param {boolean=} reverse Reverse the order of the array.
  17307. * @returns {Array} Sorted copy of the source array.
  17308. *
  17309. *
  17310. * @example
  17311. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17312. * by age in descending order (predicate is set to `'-age'`).
  17313. * `reverse` is not set, which means it defaults to `false`.
  17314. <example module="orderByExample">
  17315. <file name="index.html">
  17316. <script>
  17317. angular.module('orderByExample', [])
  17318. .controller('ExampleController', ['$scope', function($scope) {
  17319. $scope.friends =
  17320. [{name:'John', phone:'555-1212', age:10},
  17321. {name:'Mary', phone:'555-9876', age:19},
  17322. {name:'Mike', phone:'555-4321', age:21},
  17323. {name:'Adam', phone:'555-5678', age:35},
  17324. {name:'Julie', phone:'555-8765', age:29}];
  17325. }]);
  17326. </script>
  17327. <div ng-controller="ExampleController">
  17328. <table class="friend">
  17329. <tr>
  17330. <th>Name</th>
  17331. <th>Phone Number</th>
  17332. <th>Age</th>
  17333. </tr>
  17334. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17335. <td>{{friend.name}}</td>
  17336. <td>{{friend.phone}}</td>
  17337. <td>{{friend.age}}</td>
  17338. </tr>
  17339. </table>
  17340. </div>
  17341. </file>
  17342. </example>
  17343. *
  17344. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17345. * as shown in the next example.
  17346. * @example
  17347. <example module="orderByExample">
  17348. <file name="index.html">
  17349. <script>
  17350. angular.module('orderByExample', [])
  17351. .controller('ExampleController', ['$scope', function($scope) {
  17352. $scope.friends =
  17353. [{name:'John', phone:'555-1212', age:10},
  17354. {name:'Mary', phone:'555-9876', age:19},
  17355. {name:'Mike', phone:'555-4321', age:21},
  17356. {name:'Adam', phone:'555-5678', age:35},
  17357. {name:'Julie', phone:'555-8765', age:29}];
  17358. $scope.predicate = 'age';
  17359. $scope.reverse = true;
  17360. $scope.order = function(predicate) {
  17361. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17362. $scope.predicate = predicate;
  17363. };
  17364. }]);
  17365. </script>
  17366. <style type="text/css">
  17367. .sortorder:after {
  17368. content: '\25b2';
  17369. }
  17370. .sortorder.reverse:after {
  17371. content: '\25bc';
  17372. }
  17373. </style>
  17374. <div ng-controller="ExampleController">
  17375. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17376. <hr/>
  17377. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17378. <table class="friend">
  17379. <tr>
  17380. <th>
  17381. <a href="" ng-click="order('name')">Name</a>
  17382. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17383. </th>
  17384. <th>
  17385. <a href="" ng-click="order('phone')">Phone Number</a>
  17386. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17387. </th>
  17388. <th>
  17389. <a href="" ng-click="order('age')">Age</a>
  17390. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17391. </th>
  17392. </tr>
  17393. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17394. <td>{{friend.name}}</td>
  17395. <td>{{friend.phone}}</td>
  17396. <td>{{friend.age}}</td>
  17397. </tr>
  17398. </table>
  17399. </div>
  17400. </file>
  17401. </example>
  17402. *
  17403. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17404. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17405. * desired parameters.
  17406. *
  17407. * Example:
  17408. *
  17409. * @example
  17410. <example module="orderByExample">
  17411. <file name="index.html">
  17412. <div ng-controller="ExampleController">
  17413. <table class="friend">
  17414. <tr>
  17415. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17416. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17417. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17418. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17419. </tr>
  17420. <tr ng-repeat="friend in friends">
  17421. <td>{{friend.name}}</td>
  17422. <td>{{friend.phone}}</td>
  17423. <td>{{friend.age}}</td>
  17424. </tr>
  17425. </table>
  17426. </div>
  17427. </file>
  17428. <file name="script.js">
  17429. angular.module('orderByExample', [])
  17430. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17431. var orderBy = $filter('orderBy');
  17432. $scope.friends = [
  17433. { name: 'John', phone: '555-1212', age: 10 },
  17434. { name: 'Mary', phone: '555-9876', age: 19 },
  17435. { name: 'Mike', phone: '555-4321', age: 21 },
  17436. { name: 'Adam', phone: '555-5678', age: 35 },
  17437. { name: 'Julie', phone: '555-8765', age: 29 }
  17438. ];
  17439. $scope.order = function(predicate, reverse) {
  17440. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17441. };
  17442. $scope.order('-age',false);
  17443. }]);
  17444. </file>
  17445. </example>
  17446. */
  17447. orderByFilter.$inject = ['$parse'];
  17448. function orderByFilter($parse) {
  17449. return function(array, sortPredicate, reverseOrder) {
  17450. if (!(isArrayLike(array))) return array;
  17451. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  17452. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17453. sortPredicate = sortPredicate.map(function(predicate) {
  17454. var descending = false, get = predicate || identity;
  17455. if (isString(predicate)) {
  17456. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17457. descending = predicate.charAt(0) == '-';
  17458. predicate = predicate.substring(1);
  17459. }
  17460. if (predicate === '') {
  17461. // Effectively no predicate was passed so we compare identity
  17462. return reverseComparator(compare, descending);
  17463. }
  17464. get = $parse(predicate);
  17465. if (get.constant) {
  17466. var key = get();
  17467. return reverseComparator(function(a, b) {
  17468. return compare(a[key], b[key]);
  17469. }, descending);
  17470. }
  17471. }
  17472. return reverseComparator(function(a, b) {
  17473. return compare(get(a),get(b));
  17474. }, descending);
  17475. });
  17476. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  17477. function comparator(o1, o2) {
  17478. for (var i = 0; i < sortPredicate.length; i++) {
  17479. var comp = sortPredicate[i](o1, o2);
  17480. if (comp !== 0) return comp;
  17481. }
  17482. return 0;
  17483. }
  17484. function reverseComparator(comp, descending) {
  17485. return descending
  17486. ? function(a, b) {return comp(b,a);}
  17487. : comp;
  17488. }
  17489. function isPrimitive(value) {
  17490. switch (typeof value) {
  17491. case 'number': /* falls through */
  17492. case 'boolean': /* falls through */
  17493. case 'string':
  17494. return true;
  17495. default:
  17496. return false;
  17497. }
  17498. }
  17499. function objectToString(value) {
  17500. if (value === null) return 'null';
  17501. if (typeof value.valueOf === 'function') {
  17502. value = value.valueOf();
  17503. if (isPrimitive(value)) return value;
  17504. }
  17505. if (typeof value.toString === 'function') {
  17506. value = value.toString();
  17507. if (isPrimitive(value)) return value;
  17508. }
  17509. return '';
  17510. }
  17511. function compare(v1, v2) {
  17512. var t1 = typeof v1;
  17513. var t2 = typeof v2;
  17514. if (t1 === t2 && t1 === "object") {
  17515. v1 = objectToString(v1);
  17516. v2 = objectToString(v2);
  17517. }
  17518. if (t1 === t2) {
  17519. if (t1 === "string") {
  17520. v1 = v1.toLowerCase();
  17521. v2 = v2.toLowerCase();
  17522. }
  17523. if (v1 === v2) return 0;
  17524. return v1 < v2 ? -1 : 1;
  17525. } else {
  17526. return t1 < t2 ? -1 : 1;
  17527. }
  17528. }
  17529. };
  17530. }
  17531. function ngDirective(directive) {
  17532. if (isFunction(directive)) {
  17533. directive = {
  17534. link: directive
  17535. };
  17536. }
  17537. directive.restrict = directive.restrict || 'AC';
  17538. return valueFn(directive);
  17539. }
  17540. /**
  17541. * @ngdoc directive
  17542. * @name a
  17543. * @restrict E
  17544. *
  17545. * @description
  17546. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17547. * the href attribute is empty.
  17548. *
  17549. * This change permits the easy creation of action links with the `ngClick` directive
  17550. * without changing the location or causing page reloads, e.g.:
  17551. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17552. */
  17553. var htmlAnchorDirective = valueFn({
  17554. restrict: 'E',
  17555. compile: function(element, attr) {
  17556. if (!attr.href && !attr.xlinkHref) {
  17557. return function(scope, element) {
  17558. // If the linked element is not an anchor tag anymore, do nothing
  17559. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17560. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17561. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17562. 'xlink:href' : 'href';
  17563. element.on('click', function(event) {
  17564. // if we have no href url, then don't navigate anywhere.
  17565. if (!element.attr(href)) {
  17566. event.preventDefault();
  17567. }
  17568. });
  17569. };
  17570. }
  17571. }
  17572. });
  17573. /**
  17574. * @ngdoc directive
  17575. * @name ngHref
  17576. * @restrict A
  17577. * @priority 99
  17578. *
  17579. * @description
  17580. * Using Angular markup like `{{hash}}` in an href attribute will
  17581. * make the link go to the wrong URL if the user clicks it before
  17582. * Angular has a chance to replace the `{{hash}}` markup with its
  17583. * value. Until Angular replaces the markup the link will be broken
  17584. * and will most likely return a 404 error. The `ngHref` directive
  17585. * solves this problem.
  17586. *
  17587. * The wrong way to write it:
  17588. * ```html
  17589. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17590. * ```
  17591. *
  17592. * The correct way to write it:
  17593. * ```html
  17594. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17595. * ```
  17596. *
  17597. * @element A
  17598. * @param {template} ngHref any string which can contain `{{}}` markup.
  17599. *
  17600. * @example
  17601. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17602. * in links and their different behaviors:
  17603. <example>
  17604. <file name="index.html">
  17605. <input ng-model="value" /><br />
  17606. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17607. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17608. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17609. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17610. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17611. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17612. </file>
  17613. <file name="protractor.js" type="protractor">
  17614. it('should execute ng-click but not reload when href without value', function() {
  17615. element(by.id('link-1')).click();
  17616. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17617. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17618. });
  17619. it('should execute ng-click but not reload when href empty string', function() {
  17620. element(by.id('link-2')).click();
  17621. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17622. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17623. });
  17624. it('should execute ng-click and change url when ng-href specified', function() {
  17625. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17626. element(by.id('link-3')).click();
  17627. // At this point, we navigate away from an Angular page, so we need
  17628. // to use browser.driver to get the base webdriver.
  17629. browser.wait(function() {
  17630. return browser.driver.getCurrentUrl().then(function(url) {
  17631. return url.match(/\/123$/);
  17632. });
  17633. }, 5000, 'page should navigate to /123');
  17634. });
  17635. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17636. element(by.id('link-4')).click();
  17637. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17638. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17639. });
  17640. it('should execute ng-click but not reload when no href but name specified', function() {
  17641. element(by.id('link-5')).click();
  17642. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17643. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17644. });
  17645. it('should only change url when only ng-href', function() {
  17646. element(by.model('value')).clear();
  17647. element(by.model('value')).sendKeys('6');
  17648. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17649. element(by.id('link-6')).click();
  17650. // At this point, we navigate away from an Angular page, so we need
  17651. // to use browser.driver to get the base webdriver.
  17652. browser.wait(function() {
  17653. return browser.driver.getCurrentUrl().then(function(url) {
  17654. return url.match(/\/6$/);
  17655. });
  17656. }, 5000, 'page should navigate to /6');
  17657. });
  17658. </file>
  17659. </example>
  17660. */
  17661. /**
  17662. * @ngdoc directive
  17663. * @name ngSrc
  17664. * @restrict A
  17665. * @priority 99
  17666. *
  17667. * @description
  17668. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17669. * work right: The browser will fetch from the URL with the literal
  17670. * text `{{hash}}` until Angular replaces the expression inside
  17671. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17672. *
  17673. * The buggy way to write it:
  17674. * ```html
  17675. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17676. * ```
  17677. *
  17678. * The correct way to write it:
  17679. * ```html
  17680. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17681. * ```
  17682. *
  17683. * @element IMG
  17684. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17685. */
  17686. /**
  17687. * @ngdoc directive
  17688. * @name ngSrcset
  17689. * @restrict A
  17690. * @priority 99
  17691. *
  17692. * @description
  17693. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17694. * work right: The browser will fetch from the URL with the literal
  17695. * text `{{hash}}` until Angular replaces the expression inside
  17696. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17697. *
  17698. * The buggy way to write it:
  17699. * ```html
  17700. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17701. * ```
  17702. *
  17703. * The correct way to write it:
  17704. * ```html
  17705. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17706. * ```
  17707. *
  17708. * @element IMG
  17709. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17710. */
  17711. /**
  17712. * @ngdoc directive
  17713. * @name ngDisabled
  17714. * @restrict A
  17715. * @priority 100
  17716. *
  17717. * @description
  17718. *
  17719. * This directive sets the `disabled` attribute on the element if the
  17720. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17721. *
  17722. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17723. * attribute. The following example would make the button enabled on Chrome/Firefox
  17724. * but not on older IEs:
  17725. *
  17726. * ```html
  17727. * <!-- See below for an example of ng-disabled being used correctly -->
  17728. * <div ng-init="isDisabled = false">
  17729. * <button disabled="{{isDisabled}}">Disabled</button>
  17730. * </div>
  17731. * ```
  17732. *
  17733. * This is because the HTML specification does not require browsers to preserve the values of
  17734. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17735. * If we put an Angular interpolation expression into such an attribute then the
  17736. * binding information would be lost when the browser removes the attribute.
  17737. *
  17738. * @example
  17739. <example>
  17740. <file name="index.html">
  17741. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17742. <button ng-model="button" ng-disabled="checked">Button</button>
  17743. </file>
  17744. <file name="protractor.js" type="protractor">
  17745. it('should toggle button', function() {
  17746. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17747. element(by.model('checked')).click();
  17748. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17749. });
  17750. </file>
  17751. </example>
  17752. *
  17753. * @element INPUT
  17754. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17755. * then the `disabled` attribute will be set on the element
  17756. */
  17757. /**
  17758. * @ngdoc directive
  17759. * @name ngChecked
  17760. * @restrict A
  17761. * @priority 100
  17762. *
  17763. * @description
  17764. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17765. * such as checked. (Their presence means true and their absence means false.)
  17766. * If we put an Angular interpolation expression into such an attribute then the
  17767. * binding information would be lost when the browser removes the attribute.
  17768. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17769. * This complementary directive is not removed by the browser and so provides
  17770. * a permanent reliable place to store the binding information.
  17771. * @example
  17772. <example>
  17773. <file name="index.html">
  17774. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17775. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17776. </file>
  17777. <file name="protractor.js" type="protractor">
  17778. it('should check both checkBoxes', function() {
  17779. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17780. element(by.model('master')).click();
  17781. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17782. });
  17783. </file>
  17784. </example>
  17785. *
  17786. * @element INPUT
  17787. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17788. * then special attribute "checked" will be set on the element
  17789. */
  17790. /**
  17791. * @ngdoc directive
  17792. * @name ngReadonly
  17793. * @restrict A
  17794. * @priority 100
  17795. *
  17796. * @description
  17797. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17798. * such as readonly. (Their presence means true and their absence means false.)
  17799. * If we put an Angular interpolation expression into such an attribute then the
  17800. * binding information would be lost when the browser removes the attribute.
  17801. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17802. * This complementary directive is not removed by the browser and so provides
  17803. * a permanent reliable place to store the binding information.
  17804. * @example
  17805. <example>
  17806. <file name="index.html">
  17807. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17808. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17809. </file>
  17810. <file name="protractor.js" type="protractor">
  17811. it('should toggle readonly attr', function() {
  17812. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17813. element(by.model('checked')).click();
  17814. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17815. });
  17816. </file>
  17817. </example>
  17818. *
  17819. * @element INPUT
  17820. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17821. * then special attribute "readonly" will be set on the element
  17822. */
  17823. /**
  17824. * @ngdoc directive
  17825. * @name ngSelected
  17826. * @restrict A
  17827. * @priority 100
  17828. *
  17829. * @description
  17830. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17831. * such as selected. (Their presence means true and their absence means false.)
  17832. * If we put an Angular interpolation expression into such an attribute then the
  17833. * binding information would be lost when the browser removes the attribute.
  17834. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17835. * This complementary directive is not removed by the browser and so provides
  17836. * a permanent reliable place to store the binding information.
  17837. *
  17838. * @example
  17839. <example>
  17840. <file name="index.html">
  17841. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17842. <select aria-label="ngSelected demo">
  17843. <option>Hello!</option>
  17844. <option id="greet" ng-selected="selected">Greetings!</option>
  17845. </select>
  17846. </file>
  17847. <file name="protractor.js" type="protractor">
  17848. it('should select Greetings!', function() {
  17849. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17850. element(by.model('selected')).click();
  17851. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17852. });
  17853. </file>
  17854. </example>
  17855. *
  17856. * @element OPTION
  17857. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17858. * then special attribute "selected" will be set on the element
  17859. */
  17860. /**
  17861. * @ngdoc directive
  17862. * @name ngOpen
  17863. * @restrict A
  17864. * @priority 100
  17865. *
  17866. * @description
  17867. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17868. * such as open. (Their presence means true and their absence means false.)
  17869. * If we put an Angular interpolation expression into such an attribute then the
  17870. * binding information would be lost when the browser removes the attribute.
  17871. * The `ngOpen` directive solves this problem for the `open` attribute.
  17872. * This complementary directive is not removed by the browser and so provides
  17873. * a permanent reliable place to store the binding information.
  17874. * @example
  17875. <example>
  17876. <file name="index.html">
  17877. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  17878. <details id="details" ng-open="open">
  17879. <summary>Show/Hide me</summary>
  17880. </details>
  17881. </file>
  17882. <file name="protractor.js" type="protractor">
  17883. it('should toggle open', function() {
  17884. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  17885. element(by.model('open')).click();
  17886. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  17887. });
  17888. </file>
  17889. </example>
  17890. *
  17891. * @element DETAILS
  17892. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  17893. * then special attribute "open" will be set on the element
  17894. */
  17895. var ngAttributeAliasDirectives = {};
  17896. // boolean attrs are evaluated
  17897. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  17898. // binding to multiple is not supported
  17899. if (propName == "multiple") return;
  17900. function defaultLinkFn(scope, element, attr) {
  17901. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  17902. attr.$set(attrName, !!value);
  17903. });
  17904. }
  17905. var normalized = directiveNormalize('ng-' + attrName);
  17906. var linkFn = defaultLinkFn;
  17907. if (propName === 'checked') {
  17908. linkFn = function(scope, element, attr) {
  17909. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  17910. if (attr.ngModel !== attr[normalized]) {
  17911. defaultLinkFn(scope, element, attr);
  17912. }
  17913. };
  17914. }
  17915. ngAttributeAliasDirectives[normalized] = function() {
  17916. return {
  17917. restrict: 'A',
  17918. priority: 100,
  17919. link: linkFn
  17920. };
  17921. };
  17922. });
  17923. // aliased input attrs are evaluated
  17924. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  17925. ngAttributeAliasDirectives[ngAttr] = function() {
  17926. return {
  17927. priority: 100,
  17928. link: function(scope, element, attr) {
  17929. //special case ngPattern when a literal regular expression value
  17930. //is used as the expression (this way we don't have to watch anything).
  17931. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  17932. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  17933. if (match) {
  17934. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  17935. return;
  17936. }
  17937. }
  17938. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  17939. attr.$set(ngAttr, value);
  17940. });
  17941. }
  17942. };
  17943. };
  17944. });
  17945. // ng-src, ng-srcset, ng-href are interpolated
  17946. forEach(['src', 'srcset', 'href'], function(attrName) {
  17947. var normalized = directiveNormalize('ng-' + attrName);
  17948. ngAttributeAliasDirectives[normalized] = function() {
  17949. return {
  17950. priority: 99, // it needs to run after the attributes are interpolated
  17951. link: function(scope, element, attr) {
  17952. var propName = attrName,
  17953. name = attrName;
  17954. if (attrName === 'href' &&
  17955. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  17956. name = 'xlinkHref';
  17957. attr.$attr[name] = 'xlink:href';
  17958. propName = null;
  17959. }
  17960. attr.$observe(normalized, function(value) {
  17961. if (!value) {
  17962. if (attrName === 'href') {
  17963. attr.$set(name, null);
  17964. }
  17965. return;
  17966. }
  17967. attr.$set(name, value);
  17968. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  17969. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  17970. // to set the property as well to achieve the desired effect.
  17971. // we use attr[attrName] value since $set can sanitize the url.
  17972. if (msie && propName) element.prop(propName, attr[name]);
  17973. });
  17974. }
  17975. };
  17976. };
  17977. });
  17978. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  17979. */
  17980. var nullFormCtrl = {
  17981. $addControl: noop,
  17982. $$renameControl: nullFormRenameControl,
  17983. $removeControl: noop,
  17984. $setValidity: noop,
  17985. $setDirty: noop,
  17986. $setPristine: noop,
  17987. $setSubmitted: noop
  17988. },
  17989. SUBMITTED_CLASS = 'ng-submitted';
  17990. function nullFormRenameControl(control, name) {
  17991. control.$name = name;
  17992. }
  17993. /**
  17994. * @ngdoc type
  17995. * @name form.FormController
  17996. *
  17997. * @property {boolean} $pristine True if user has not interacted with the form yet.
  17998. * @property {boolean} $dirty True if user has already interacted with the form.
  17999. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18000. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18001. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18002. *
  18003. * @property {Object} $error Is an object hash, containing references to controls or
  18004. * forms with failing validators, where:
  18005. *
  18006. * - keys are validation tokens (error names),
  18007. * - values are arrays of controls or forms that have a failing validator for given error name.
  18008. *
  18009. * Built-in validation tokens:
  18010. *
  18011. * - `email`
  18012. * - `max`
  18013. * - `maxlength`
  18014. * - `min`
  18015. * - `minlength`
  18016. * - `number`
  18017. * - `pattern`
  18018. * - `required`
  18019. * - `url`
  18020. * - `date`
  18021. * - `datetimelocal`
  18022. * - `time`
  18023. * - `week`
  18024. * - `month`
  18025. *
  18026. * @description
  18027. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18028. * such as being valid/invalid or dirty/pristine.
  18029. *
  18030. * Each {@link ng.directive:form form} directive creates an instance
  18031. * of `FormController`.
  18032. *
  18033. */
  18034. //asks for $scope to fool the BC controller module
  18035. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18036. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18037. var form = this,
  18038. controls = [];
  18039. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  18040. // init state
  18041. form.$error = {};
  18042. form.$$success = {};
  18043. form.$pending = undefined;
  18044. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18045. form.$dirty = false;
  18046. form.$pristine = true;
  18047. form.$valid = true;
  18048. form.$invalid = false;
  18049. form.$submitted = false;
  18050. parentForm.$addControl(form);
  18051. /**
  18052. * @ngdoc method
  18053. * @name form.FormController#$rollbackViewValue
  18054. *
  18055. * @description
  18056. * Rollback all form controls pending updates to the `$modelValue`.
  18057. *
  18058. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18059. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18060. * a form that uses `ng-model-options` to pend updates.
  18061. */
  18062. form.$rollbackViewValue = function() {
  18063. forEach(controls, function(control) {
  18064. control.$rollbackViewValue();
  18065. });
  18066. };
  18067. /**
  18068. * @ngdoc method
  18069. * @name form.FormController#$commitViewValue
  18070. *
  18071. * @description
  18072. * Commit all form controls pending updates to the `$modelValue`.
  18073. *
  18074. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18075. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18076. * usually handles calling this in response to input events.
  18077. */
  18078. form.$commitViewValue = function() {
  18079. forEach(controls, function(control) {
  18080. control.$commitViewValue();
  18081. });
  18082. };
  18083. /**
  18084. * @ngdoc method
  18085. * @name form.FormController#$addControl
  18086. *
  18087. * @description
  18088. * Register a control with the form.
  18089. *
  18090. * Input elements using ngModelController do this automatically when they are linked.
  18091. */
  18092. form.$addControl = function(control) {
  18093. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18094. // and not added to the scope. Now we throw an error.
  18095. assertNotHasOwnProperty(control.$name, 'input');
  18096. controls.push(control);
  18097. if (control.$name) {
  18098. form[control.$name] = control;
  18099. }
  18100. };
  18101. // Private API: rename a form control
  18102. form.$$renameControl = function(control, newName) {
  18103. var oldName = control.$name;
  18104. if (form[oldName] === control) {
  18105. delete form[oldName];
  18106. }
  18107. form[newName] = control;
  18108. control.$name = newName;
  18109. };
  18110. /**
  18111. * @ngdoc method
  18112. * @name form.FormController#$removeControl
  18113. *
  18114. * @description
  18115. * Deregister a control from the form.
  18116. *
  18117. * Input elements using ngModelController do this automatically when they are destroyed.
  18118. */
  18119. form.$removeControl = function(control) {
  18120. if (control.$name && form[control.$name] === control) {
  18121. delete form[control.$name];
  18122. }
  18123. forEach(form.$pending, function(value, name) {
  18124. form.$setValidity(name, null, control);
  18125. });
  18126. forEach(form.$error, function(value, name) {
  18127. form.$setValidity(name, null, control);
  18128. });
  18129. forEach(form.$$success, function(value, name) {
  18130. form.$setValidity(name, null, control);
  18131. });
  18132. arrayRemove(controls, control);
  18133. };
  18134. /**
  18135. * @ngdoc method
  18136. * @name form.FormController#$setValidity
  18137. *
  18138. * @description
  18139. * Sets the validity of a form control.
  18140. *
  18141. * This method will also propagate to parent forms.
  18142. */
  18143. addSetValidityMethod({
  18144. ctrl: this,
  18145. $element: element,
  18146. set: function(object, property, controller) {
  18147. var list = object[property];
  18148. if (!list) {
  18149. object[property] = [controller];
  18150. } else {
  18151. var index = list.indexOf(controller);
  18152. if (index === -1) {
  18153. list.push(controller);
  18154. }
  18155. }
  18156. },
  18157. unset: function(object, property, controller) {
  18158. var list = object[property];
  18159. if (!list) {
  18160. return;
  18161. }
  18162. arrayRemove(list, controller);
  18163. if (list.length === 0) {
  18164. delete object[property];
  18165. }
  18166. },
  18167. parentForm: parentForm,
  18168. $animate: $animate
  18169. });
  18170. /**
  18171. * @ngdoc method
  18172. * @name form.FormController#$setDirty
  18173. *
  18174. * @description
  18175. * Sets the form to a dirty state.
  18176. *
  18177. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18178. * state (ng-dirty class). This method will also propagate to parent forms.
  18179. */
  18180. form.$setDirty = function() {
  18181. $animate.removeClass(element, PRISTINE_CLASS);
  18182. $animate.addClass(element, DIRTY_CLASS);
  18183. form.$dirty = true;
  18184. form.$pristine = false;
  18185. parentForm.$setDirty();
  18186. };
  18187. /**
  18188. * @ngdoc method
  18189. * @name form.FormController#$setPristine
  18190. *
  18191. * @description
  18192. * Sets the form to its pristine state.
  18193. *
  18194. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18195. * state (ng-pristine class). This method will also propagate to all the controls contained
  18196. * in this form.
  18197. *
  18198. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18199. * saving or resetting it.
  18200. */
  18201. form.$setPristine = function() {
  18202. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18203. form.$dirty = false;
  18204. form.$pristine = true;
  18205. form.$submitted = false;
  18206. forEach(controls, function(control) {
  18207. control.$setPristine();
  18208. });
  18209. };
  18210. /**
  18211. * @ngdoc method
  18212. * @name form.FormController#$setUntouched
  18213. *
  18214. * @description
  18215. * Sets the form to its untouched state.
  18216. *
  18217. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18218. * untouched state (ng-untouched class).
  18219. *
  18220. * Setting a form controls back to their untouched state is often useful when setting the form
  18221. * back to its pristine state.
  18222. */
  18223. form.$setUntouched = function() {
  18224. forEach(controls, function(control) {
  18225. control.$setUntouched();
  18226. });
  18227. };
  18228. /**
  18229. * @ngdoc method
  18230. * @name form.FormController#$setSubmitted
  18231. *
  18232. * @description
  18233. * Sets the form to its submitted state.
  18234. */
  18235. form.$setSubmitted = function() {
  18236. $animate.addClass(element, SUBMITTED_CLASS);
  18237. form.$submitted = true;
  18238. parentForm.$setSubmitted();
  18239. };
  18240. }
  18241. /**
  18242. * @ngdoc directive
  18243. * @name ngForm
  18244. * @restrict EAC
  18245. *
  18246. * @description
  18247. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18248. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18249. * sub-group of controls needs to be determined.
  18250. *
  18251. * Note: the purpose of `ngForm` is to group controls,
  18252. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18253. * (e.g. posting to the server, ...).
  18254. *
  18255. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18256. * related scope, under this name.
  18257. *
  18258. */
  18259. /**
  18260. * @ngdoc directive
  18261. * @name form
  18262. * @restrict E
  18263. *
  18264. * @description
  18265. * Directive that instantiates
  18266. * {@link form.FormController FormController}.
  18267. *
  18268. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18269. * this name.
  18270. *
  18271. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18272. *
  18273. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18274. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18275. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18276. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18277. * using Angular validation directives in forms that are dynamically generated using the
  18278. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18279. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18280. * `ngForm` directive and nest these in an outer `form` element.
  18281. *
  18282. *
  18283. * # CSS classes
  18284. * - `ng-valid` is set if the form is valid.
  18285. * - `ng-invalid` is set if the form is invalid.
  18286. * - `ng-pristine` is set if the form is pristine.
  18287. * - `ng-dirty` is set if the form is dirty.
  18288. * - `ng-submitted` is set if the form was submitted.
  18289. *
  18290. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18291. *
  18292. *
  18293. * # Submitting a form and preventing the default action
  18294. *
  18295. * Since the role of forms in client-side Angular applications is different than in classical
  18296. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18297. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18298. * to handle the form submission in an application-specific way.
  18299. *
  18300. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18301. * `<form>` element has an `action` attribute specified.
  18302. *
  18303. * You can use one of the following two ways to specify what javascript method should be called when
  18304. * a form is submitted:
  18305. *
  18306. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18307. * - {@link ng.directive:ngClick ngClick} directive on the first
  18308. * button or input field of type submit (input[type=submit])
  18309. *
  18310. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18311. * or {@link ng.directive:ngClick ngClick} directives.
  18312. * This is because of the following form submission rules in the HTML specification:
  18313. *
  18314. * - If a form has only one input field then hitting enter in this field triggers form submit
  18315. * (`ngSubmit`)
  18316. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18317. * doesn't trigger submit
  18318. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18319. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18320. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18321. *
  18322. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18323. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18324. * to have access to the updated model.
  18325. *
  18326. * ## Animation Hooks
  18327. *
  18328. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18329. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18330. * other validations that are performed within the form. Animations in ngForm are similar to how
  18331. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18332. * as JS animations.
  18333. *
  18334. * The following example shows a simple way to utilize CSS transitions to style a form element
  18335. * that has been rendered as invalid after it has been validated:
  18336. *
  18337. * <pre>
  18338. * //be sure to include ngAnimate as a module to hook into more
  18339. * //advanced animations
  18340. * .my-form {
  18341. * transition:0.5s linear all;
  18342. * background: white;
  18343. * }
  18344. * .my-form.ng-invalid {
  18345. * background: red;
  18346. * color:white;
  18347. * }
  18348. * </pre>
  18349. *
  18350. * @example
  18351. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18352. <file name="index.html">
  18353. <script>
  18354. angular.module('formExample', [])
  18355. .controller('FormController', ['$scope', function($scope) {
  18356. $scope.userType = 'guest';
  18357. }]);
  18358. </script>
  18359. <style>
  18360. .my-form {
  18361. -webkit-transition:all linear 0.5s;
  18362. transition:all linear 0.5s;
  18363. background: transparent;
  18364. }
  18365. .my-form.ng-invalid {
  18366. background: red;
  18367. }
  18368. </style>
  18369. <form name="myForm" ng-controller="FormController" class="my-form">
  18370. userType: <input name="input" ng-model="userType" required>
  18371. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18372. <code>userType = {{userType}}</code><br>
  18373. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18374. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18375. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18376. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18377. </form>
  18378. </file>
  18379. <file name="protractor.js" type="protractor">
  18380. it('should initialize to model', function() {
  18381. var userType = element(by.binding('userType'));
  18382. var valid = element(by.binding('myForm.input.$valid'));
  18383. expect(userType.getText()).toContain('guest');
  18384. expect(valid.getText()).toContain('true');
  18385. });
  18386. it('should be invalid if empty', function() {
  18387. var userType = element(by.binding('userType'));
  18388. var valid = element(by.binding('myForm.input.$valid'));
  18389. var userInput = element(by.model('userType'));
  18390. userInput.clear();
  18391. userInput.sendKeys('');
  18392. expect(userType.getText()).toEqual('userType =');
  18393. expect(valid.getText()).toContain('false');
  18394. });
  18395. </file>
  18396. </example>
  18397. *
  18398. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18399. * related scope, under this name.
  18400. */
  18401. var formDirectiveFactory = function(isNgForm) {
  18402. return ['$timeout', function($timeout) {
  18403. var formDirective = {
  18404. name: 'form',
  18405. restrict: isNgForm ? 'EAC' : 'E',
  18406. controller: FormController,
  18407. compile: function ngFormCompile(formElement, attr) {
  18408. // Setup initial state of the control
  18409. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18410. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18411. return {
  18412. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  18413. // if `action` attr is not present on the form, prevent the default action (submission)
  18414. if (!('action' in attr)) {
  18415. // we can't use jq events because if a form is destroyed during submission the default
  18416. // action is not prevented. see #1238
  18417. //
  18418. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18419. // page reload if the form was destroyed by submission of the form via a click handler
  18420. // on a button in the form. Looks like an IE9 specific bug.
  18421. var handleFormSubmission = function(event) {
  18422. scope.$apply(function() {
  18423. controller.$commitViewValue();
  18424. controller.$setSubmitted();
  18425. });
  18426. event.preventDefault();
  18427. };
  18428. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18429. // unregister the preventDefault listener so that we don't not leak memory but in a
  18430. // way that will achieve the prevention of the default action.
  18431. formElement.on('$destroy', function() {
  18432. $timeout(function() {
  18433. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18434. }, 0, false);
  18435. });
  18436. }
  18437. var parentFormCtrl = controller.$$parentForm;
  18438. if (nameAttr) {
  18439. setter(scope, controller.$name, controller, controller.$name);
  18440. attr.$observe(nameAttr, function(newValue) {
  18441. if (controller.$name === newValue) return;
  18442. setter(scope, controller.$name, undefined, controller.$name);
  18443. parentFormCtrl.$$renameControl(controller, newValue);
  18444. setter(scope, controller.$name, controller, controller.$name);
  18445. });
  18446. }
  18447. formElement.on('$destroy', function() {
  18448. parentFormCtrl.$removeControl(controller);
  18449. if (nameAttr) {
  18450. setter(scope, attr[nameAttr], undefined, controller.$name);
  18451. }
  18452. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18453. });
  18454. }
  18455. };
  18456. }
  18457. };
  18458. return formDirective;
  18459. }];
  18460. };
  18461. var formDirective = formDirectiveFactory();
  18462. var ngFormDirective = formDirectiveFactory(true);
  18463. /* global VALID_CLASS: false,
  18464. INVALID_CLASS: false,
  18465. PRISTINE_CLASS: false,
  18466. DIRTY_CLASS: false,
  18467. UNTOUCHED_CLASS: false,
  18468. TOUCHED_CLASS: false,
  18469. $ngModelMinErr: false,
  18470. */
  18471. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18472. 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)/;
  18473. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18474. 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;
  18475. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18476. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18477. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18478. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18479. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18480. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18481. var inputType = {
  18482. /**
  18483. * @ngdoc input
  18484. * @name input[text]
  18485. *
  18486. * @description
  18487. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18488. *
  18489. *
  18490. * @param {string} ngModel Assignable angular expression to data-bind to.
  18491. * @param {string=} name Property name of the form under which the control is published.
  18492. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18493. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18494. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18495. * `required` when you want to data-bind to the `required` attribute.
  18496. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18497. * minlength.
  18498. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18499. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18500. * any length.
  18501. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18502. * that contains the regular expression body that will be converted to a regular expression
  18503. * as in the ngPattern directive.
  18504. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18505. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18506. * If the expression evaluates to a RegExp object, then this is used directly.
  18507. * If the expression evaluates to a string, then it will be converted to a RegExp
  18508. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18509. * `new RegExp('^abc$')`.<br />
  18510. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18511. * start at the index of the last search's match, thus not taking the whole input value into
  18512. * account.
  18513. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18514. * interaction with the input element.
  18515. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18516. * This parameter is ignored for input[type=password] controls, which will never trim the
  18517. * input.
  18518. *
  18519. * @example
  18520. <example name="text-input-directive" module="textInputExample">
  18521. <file name="index.html">
  18522. <script>
  18523. angular.module('textInputExample', [])
  18524. .controller('ExampleController', ['$scope', function($scope) {
  18525. $scope.example = {
  18526. text: 'guest',
  18527. word: /^\s*\w*\s*$/
  18528. };
  18529. }]);
  18530. </script>
  18531. <form name="myForm" ng-controller="ExampleController">
  18532. <label>Single word:
  18533. <input type="text" name="input" ng-model="example.text"
  18534. ng-pattern="example.word" required ng-trim="false">
  18535. </label>
  18536. <div role="alert">
  18537. <span class="error" ng-show="myForm.input.$error.required">
  18538. Required!</span>
  18539. <span class="error" ng-show="myForm.input.$error.pattern">
  18540. Single word only!</span>
  18541. </div>
  18542. <tt>text = {{example.text}}</tt><br/>
  18543. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18544. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18545. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18546. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18547. </form>
  18548. </file>
  18549. <file name="protractor.js" type="protractor">
  18550. var text = element(by.binding('example.text'));
  18551. var valid = element(by.binding('myForm.input.$valid'));
  18552. var input = element(by.model('example.text'));
  18553. it('should initialize to model', function() {
  18554. expect(text.getText()).toContain('guest');
  18555. expect(valid.getText()).toContain('true');
  18556. });
  18557. it('should be invalid if empty', function() {
  18558. input.clear();
  18559. input.sendKeys('');
  18560. expect(text.getText()).toEqual('text =');
  18561. expect(valid.getText()).toContain('false');
  18562. });
  18563. it('should be invalid if multi word', function() {
  18564. input.clear();
  18565. input.sendKeys('hello world');
  18566. expect(valid.getText()).toContain('false');
  18567. });
  18568. </file>
  18569. </example>
  18570. */
  18571. 'text': textInputType,
  18572. /**
  18573. * @ngdoc input
  18574. * @name input[date]
  18575. *
  18576. * @description
  18577. * Input with date validation and transformation. In browsers that do not yet support
  18578. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18579. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18580. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18581. * expected input format via a placeholder or label.
  18582. *
  18583. * The model must always be a Date object, otherwise Angular will throw an error.
  18584. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18585. *
  18586. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18587. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18588. *
  18589. * @param {string} ngModel Assignable angular expression to data-bind to.
  18590. * @param {string=} name Property name of the form under which the control is published.
  18591. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18592. * valid ISO date string (yyyy-MM-dd).
  18593. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18594. * a valid ISO date string (yyyy-MM-dd).
  18595. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18596. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18597. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18598. * `required` when you want to data-bind to the `required` attribute.
  18599. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18600. * interaction with the input element.
  18601. *
  18602. * @example
  18603. <example name="date-input-directive" module="dateInputExample">
  18604. <file name="index.html">
  18605. <script>
  18606. angular.module('dateInputExample', [])
  18607. .controller('DateController', ['$scope', function($scope) {
  18608. $scope.example = {
  18609. value: new Date(2013, 9, 22)
  18610. };
  18611. }]);
  18612. </script>
  18613. <form name="myForm" ng-controller="DateController as dateCtrl">
  18614. <label for="exampleInput">Pick a date in 2013:</label>
  18615. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18616. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18617. <div role="alert">
  18618. <span class="error" ng-show="myForm.input.$error.required">
  18619. Required!</span>
  18620. <span class="error" ng-show="myForm.input.$error.date">
  18621. Not a valid date!</span>
  18622. </div>
  18623. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18624. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18625. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18626. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18627. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18628. </form>
  18629. </file>
  18630. <file name="protractor.js" type="protractor">
  18631. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18632. var valid = element(by.binding('myForm.input.$valid'));
  18633. var input = element(by.model('example.value'));
  18634. // currently protractor/webdriver does not support
  18635. // sending keys to all known HTML5 input controls
  18636. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18637. function setInput(val) {
  18638. // set the value of the element and force validation.
  18639. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18640. "ipt.value = '" + val + "';" +
  18641. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18642. browser.executeScript(scr);
  18643. }
  18644. it('should initialize to model', function() {
  18645. expect(value.getText()).toContain('2013-10-22');
  18646. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18647. });
  18648. it('should be invalid if empty', function() {
  18649. setInput('');
  18650. expect(value.getText()).toEqual('value =');
  18651. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18652. });
  18653. it('should be invalid if over max', function() {
  18654. setInput('2015-01-01');
  18655. expect(value.getText()).toContain('');
  18656. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18657. });
  18658. </file>
  18659. </example>
  18660. */
  18661. 'date': createDateInputType('date', DATE_REGEXP,
  18662. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18663. 'yyyy-MM-dd'),
  18664. /**
  18665. * @ngdoc input
  18666. * @name input[datetime-local]
  18667. *
  18668. * @description
  18669. * Input with datetime validation and transformation. In browsers that do not yet support
  18670. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18671. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18672. *
  18673. * The model must always be a Date object, otherwise Angular will throw an error.
  18674. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18675. *
  18676. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18677. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18678. *
  18679. * @param {string} ngModel Assignable angular expression to data-bind to.
  18680. * @param {string=} name Property name of the form under which the control is published.
  18681. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18682. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18683. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18684. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18685. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18686. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18687. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18688. * `required` when you want to data-bind to the `required` attribute.
  18689. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18690. * interaction with the input element.
  18691. *
  18692. * @example
  18693. <example name="datetimelocal-input-directive" module="dateExample">
  18694. <file name="index.html">
  18695. <script>
  18696. angular.module('dateExample', [])
  18697. .controller('DateController', ['$scope', function($scope) {
  18698. $scope.example = {
  18699. value: new Date(2010, 11, 28, 14, 57)
  18700. };
  18701. }]);
  18702. </script>
  18703. <form name="myForm" ng-controller="DateController as dateCtrl">
  18704. <label for="exampleInput">Pick a date between in 2013:</label>
  18705. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18706. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18707. <div role="alert">
  18708. <span class="error" ng-show="myForm.input.$error.required">
  18709. Required!</span>
  18710. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18711. Not a valid date!</span>
  18712. </div>
  18713. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18714. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18715. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18716. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18717. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18718. </form>
  18719. </file>
  18720. <file name="protractor.js" type="protractor">
  18721. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18722. var valid = element(by.binding('myForm.input.$valid'));
  18723. var input = element(by.model('example.value'));
  18724. // currently protractor/webdriver does not support
  18725. // sending keys to all known HTML5 input controls
  18726. // for various browsers (https://github.com/angular/protractor/issues/562).
  18727. function setInput(val) {
  18728. // set the value of the element and force validation.
  18729. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18730. "ipt.value = '" + val + "';" +
  18731. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18732. browser.executeScript(scr);
  18733. }
  18734. it('should initialize to model', function() {
  18735. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18736. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18737. });
  18738. it('should be invalid if empty', function() {
  18739. setInput('');
  18740. expect(value.getText()).toEqual('value =');
  18741. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18742. });
  18743. it('should be invalid if over max', function() {
  18744. setInput('2015-01-01T23:59:00');
  18745. expect(value.getText()).toContain('');
  18746. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18747. });
  18748. </file>
  18749. </example>
  18750. */
  18751. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18752. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18753. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18754. /**
  18755. * @ngdoc input
  18756. * @name input[time]
  18757. *
  18758. * @description
  18759. * Input with time validation and transformation. In browsers that do not yet support
  18760. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18761. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18762. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18763. *
  18764. * The model must always be a Date object, otherwise Angular will throw an error.
  18765. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18766. *
  18767. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18768. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18769. *
  18770. * @param {string} ngModel Assignable angular expression to data-bind to.
  18771. * @param {string=} name Property name of the form under which the control is published.
  18772. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18773. * valid ISO time format (HH:mm:ss).
  18774. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  18775. * valid ISO time format (HH:mm:ss).
  18776. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18777. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18778. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18779. * `required` when you want to data-bind to the `required` attribute.
  18780. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18781. * interaction with the input element.
  18782. *
  18783. * @example
  18784. <example name="time-input-directive" module="timeExample">
  18785. <file name="index.html">
  18786. <script>
  18787. angular.module('timeExample', [])
  18788. .controller('DateController', ['$scope', function($scope) {
  18789. $scope.example = {
  18790. value: new Date(1970, 0, 1, 14, 57, 0)
  18791. };
  18792. }]);
  18793. </script>
  18794. <form name="myForm" ng-controller="DateController as dateCtrl">
  18795. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18796. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18797. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18798. <div role="alert">
  18799. <span class="error" ng-show="myForm.input.$error.required">
  18800. Required!</span>
  18801. <span class="error" ng-show="myForm.input.$error.time">
  18802. Not a valid date!</span>
  18803. </div>
  18804. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18805. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18806. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18807. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18808. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18809. </form>
  18810. </file>
  18811. <file name="protractor.js" type="protractor">
  18812. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18813. var valid = element(by.binding('myForm.input.$valid'));
  18814. var input = element(by.model('example.value'));
  18815. // currently protractor/webdriver does not support
  18816. // sending keys to all known HTML5 input controls
  18817. // for various browsers (https://github.com/angular/protractor/issues/562).
  18818. function setInput(val) {
  18819. // set the value of the element and force validation.
  18820. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18821. "ipt.value = '" + val + "';" +
  18822. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18823. browser.executeScript(scr);
  18824. }
  18825. it('should initialize to model', function() {
  18826. expect(value.getText()).toContain('14:57:00');
  18827. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18828. });
  18829. it('should be invalid if empty', function() {
  18830. setInput('');
  18831. expect(value.getText()).toEqual('value =');
  18832. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18833. });
  18834. it('should be invalid if over max', function() {
  18835. setInput('23:59:00');
  18836. expect(value.getText()).toContain('');
  18837. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18838. });
  18839. </file>
  18840. </example>
  18841. */
  18842. 'time': createDateInputType('time', TIME_REGEXP,
  18843. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  18844. 'HH:mm:ss.sss'),
  18845. /**
  18846. * @ngdoc input
  18847. * @name input[week]
  18848. *
  18849. * @description
  18850. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  18851. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18852. * week format (yyyy-W##), for example: `2013-W02`.
  18853. *
  18854. * The model must always be a Date object, otherwise Angular will throw an error.
  18855. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18856. *
  18857. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18858. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18859. *
  18860. * @param {string} ngModel Assignable angular expression to data-bind to.
  18861. * @param {string=} name Property name of the form under which the control is published.
  18862. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18863. * valid ISO week format (yyyy-W##).
  18864. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18865. * a valid ISO week format (yyyy-W##).
  18866. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18867. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18868. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18869. * `required` when you want to data-bind to the `required` attribute.
  18870. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18871. * interaction with the input element.
  18872. *
  18873. * @example
  18874. <example name="week-input-directive" module="weekExample">
  18875. <file name="index.html">
  18876. <script>
  18877. angular.module('weekExample', [])
  18878. .controller('DateController', ['$scope', function($scope) {
  18879. $scope.example = {
  18880. value: new Date(2013, 0, 3)
  18881. };
  18882. }]);
  18883. </script>
  18884. <form name="myForm" ng-controller="DateController as dateCtrl">
  18885. <label>Pick a date between in 2013:
  18886. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  18887. placeholder="YYYY-W##" min="2012-W32"
  18888. max="2013-W52" required />
  18889. </label>
  18890. <div role="alert">
  18891. <span class="error" ng-show="myForm.input.$error.required">
  18892. Required!</span>
  18893. <span class="error" ng-show="myForm.input.$error.week">
  18894. Not a valid date!</span>
  18895. </div>
  18896. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  18897. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18898. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18899. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18900. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18901. </form>
  18902. </file>
  18903. <file name="protractor.js" type="protractor">
  18904. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  18905. var valid = element(by.binding('myForm.input.$valid'));
  18906. var input = element(by.model('example.value'));
  18907. // currently protractor/webdriver does not support
  18908. // sending keys to all known HTML5 input controls
  18909. // for various browsers (https://github.com/angular/protractor/issues/562).
  18910. function setInput(val) {
  18911. // set the value of the element and force validation.
  18912. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18913. "ipt.value = '" + val + "';" +
  18914. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18915. browser.executeScript(scr);
  18916. }
  18917. it('should initialize to model', function() {
  18918. expect(value.getText()).toContain('2013-W01');
  18919. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18920. });
  18921. it('should be invalid if empty', function() {
  18922. setInput('');
  18923. expect(value.getText()).toEqual('value =');
  18924. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18925. });
  18926. it('should be invalid if over max', function() {
  18927. setInput('2015-W01');
  18928. expect(value.getText()).toContain('');
  18929. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18930. });
  18931. </file>
  18932. </example>
  18933. */
  18934. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  18935. /**
  18936. * @ngdoc input
  18937. * @name input[month]
  18938. *
  18939. * @description
  18940. * Input with month validation and transformation. In browsers that do not yet support
  18941. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18942. * month format (yyyy-MM), for example: `2009-01`.
  18943. *
  18944. * The model must always be a Date object, otherwise Angular will throw an error.
  18945. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18946. * If the model is not set to the first of the month, the next view to model update will set it
  18947. * to the first of the month.
  18948. *
  18949. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18950. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18951. *
  18952. * @param {string} ngModel Assignable angular expression to data-bind to.
  18953. * @param {string=} name Property name of the form under which the control is published.
  18954. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  18955. * a valid ISO month format (yyyy-MM).
  18956. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  18957. * be a valid ISO month format (yyyy-MM).
  18958. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18959. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18960. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18961. * `required` when you want to data-bind to the `required` attribute.
  18962. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18963. * interaction with the input element.
  18964. *
  18965. * @example
  18966. <example name="month-input-directive" module="monthExample">
  18967. <file name="index.html">
  18968. <script>
  18969. angular.module('monthExample', [])
  18970. .controller('DateController', ['$scope', function($scope) {
  18971. $scope.example = {
  18972. value: new Date(2013, 9, 1)
  18973. };
  18974. }]);
  18975. </script>
  18976. <form name="myForm" ng-controller="DateController as dateCtrl">
  18977. <label for="exampleInput">Pick a month in 2013:</label>
  18978. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  18979. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  18980. <div role="alert">
  18981. <span class="error" ng-show="myForm.input.$error.required">
  18982. Required!</span>
  18983. <span class="error" ng-show="myForm.input.$error.month">
  18984. Not a valid month!</span>
  18985. </div>
  18986. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  18987. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18988. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18989. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18990. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18991. </form>
  18992. </file>
  18993. <file name="protractor.js" type="protractor">
  18994. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  18995. var valid = element(by.binding('myForm.input.$valid'));
  18996. var input = element(by.model('example.value'));
  18997. // currently protractor/webdriver does not support
  18998. // sending keys to all known HTML5 input controls
  18999. // for various browsers (https://github.com/angular/protractor/issues/562).
  19000. function setInput(val) {
  19001. // set the value of the element and force validation.
  19002. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19003. "ipt.value = '" + val + "';" +
  19004. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19005. browser.executeScript(scr);
  19006. }
  19007. it('should initialize to model', function() {
  19008. expect(value.getText()).toContain('2013-10');
  19009. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19010. });
  19011. it('should be invalid if empty', function() {
  19012. setInput('');
  19013. expect(value.getText()).toEqual('value =');
  19014. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19015. });
  19016. it('should be invalid if over max', function() {
  19017. setInput('2015-01');
  19018. expect(value.getText()).toContain('');
  19019. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19020. });
  19021. </file>
  19022. </example>
  19023. */
  19024. 'month': createDateInputType('month', MONTH_REGEXP,
  19025. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19026. 'yyyy-MM'),
  19027. /**
  19028. * @ngdoc input
  19029. * @name input[number]
  19030. *
  19031. * @description
  19032. * Text input with number validation and transformation. Sets the `number` validation
  19033. * error if not a valid number.
  19034. *
  19035. * <div class="alert alert-warning">
  19036. * The model must always be of type `number` otherwise Angular will throw an error.
  19037. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19038. * error docs for more information and an example of how to convert your model if necessary.
  19039. * </div>
  19040. *
  19041. * ## Issues with HTML5 constraint validation
  19042. *
  19043. * In browsers that follow the
  19044. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19045. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19046. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19047. * which means the view / model values in `ngModel` and subsequently the scope value
  19048. * will also be an empty string.
  19049. *
  19050. *
  19051. * @param {string} ngModel Assignable angular expression to data-bind to.
  19052. * @param {string=} name Property name of the form under which the control is published.
  19053. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19054. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19055. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19056. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19057. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19058. * `required` when you want to data-bind to the `required` attribute.
  19059. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19060. * minlength.
  19061. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19062. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19063. * any length.
  19064. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19065. * that contains the regular expression body that will be converted to a regular expression
  19066. * as in the ngPattern directive.
  19067. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19068. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19069. * If the expression evaluates to a RegExp object, then this is used directly.
  19070. * If the expression evaluates to a string, then it will be converted to a RegExp
  19071. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19072. * `new RegExp('^abc$')`.<br />
  19073. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19074. * start at the index of the last search's match, thus not taking the whole input value into
  19075. * account.
  19076. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19077. * interaction with the input element.
  19078. *
  19079. * @example
  19080. <example name="number-input-directive" module="numberExample">
  19081. <file name="index.html">
  19082. <script>
  19083. angular.module('numberExample', [])
  19084. .controller('ExampleController', ['$scope', function($scope) {
  19085. $scope.example = {
  19086. value: 12
  19087. };
  19088. }]);
  19089. </script>
  19090. <form name="myForm" ng-controller="ExampleController">
  19091. <label>Number:
  19092. <input type="number" name="input" ng-model="example.value"
  19093. min="0" max="99" required>
  19094. </label>
  19095. <div role="alert">
  19096. <span class="error" ng-show="myForm.input.$error.required">
  19097. Required!</span>
  19098. <span class="error" ng-show="myForm.input.$error.number">
  19099. Not valid number!</span>
  19100. </div>
  19101. <tt>value = {{example.value}}</tt><br/>
  19102. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19103. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19104. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19105. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19106. </form>
  19107. </file>
  19108. <file name="protractor.js" type="protractor">
  19109. var value = element(by.binding('example.value'));
  19110. var valid = element(by.binding('myForm.input.$valid'));
  19111. var input = element(by.model('example.value'));
  19112. it('should initialize to model', function() {
  19113. expect(value.getText()).toContain('12');
  19114. expect(valid.getText()).toContain('true');
  19115. });
  19116. it('should be invalid if empty', function() {
  19117. input.clear();
  19118. input.sendKeys('');
  19119. expect(value.getText()).toEqual('value =');
  19120. expect(valid.getText()).toContain('false');
  19121. });
  19122. it('should be invalid if over max', function() {
  19123. input.clear();
  19124. input.sendKeys('123');
  19125. expect(value.getText()).toEqual('value =');
  19126. expect(valid.getText()).toContain('false');
  19127. });
  19128. </file>
  19129. </example>
  19130. */
  19131. 'number': numberInputType,
  19132. /**
  19133. * @ngdoc input
  19134. * @name input[url]
  19135. *
  19136. * @description
  19137. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19138. * valid URL.
  19139. *
  19140. * <div class="alert alert-warning">
  19141. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19142. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19143. * the built-in validators (see the {@link guide/forms Forms guide})
  19144. * </div>
  19145. *
  19146. * @param {string} ngModel Assignable angular expression to data-bind to.
  19147. * @param {string=} name Property name of the form under which the control is published.
  19148. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19149. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19150. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19151. * `required` when you want to data-bind to the `required` attribute.
  19152. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19153. * minlength.
  19154. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19155. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19156. * any length.
  19157. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19158. * that contains the regular expression body that will be converted to a regular expression
  19159. * as in the ngPattern directive.
  19160. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19161. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19162. * If the expression evaluates to a RegExp object, then this is used directly.
  19163. * If the expression evaluates to a string, then it will be converted to a RegExp
  19164. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19165. * `new RegExp('^abc$')`.<br />
  19166. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19167. * start at the index of the last search's match, thus not taking the whole input value into
  19168. * account.
  19169. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19170. * interaction with the input element.
  19171. *
  19172. * @example
  19173. <example name="url-input-directive" module="urlExample">
  19174. <file name="index.html">
  19175. <script>
  19176. angular.module('urlExample', [])
  19177. .controller('ExampleController', ['$scope', function($scope) {
  19178. $scope.url = {
  19179. text: 'http://google.com'
  19180. };
  19181. }]);
  19182. </script>
  19183. <form name="myForm" ng-controller="ExampleController">
  19184. <label>URL:
  19185. <input type="url" name="input" ng-model="url.text" required>
  19186. <label>
  19187. <div role="alert">
  19188. <span class="error" ng-show="myForm.input.$error.required">
  19189. Required!</span>
  19190. <span class="error" ng-show="myForm.input.$error.url">
  19191. Not valid url!</span>
  19192. </div>
  19193. <tt>text = {{url.text}}</tt><br/>
  19194. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19195. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19196. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19197. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19198. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19199. </form>
  19200. </file>
  19201. <file name="protractor.js" type="protractor">
  19202. var text = element(by.binding('url.text'));
  19203. var valid = element(by.binding('myForm.input.$valid'));
  19204. var input = element(by.model('url.text'));
  19205. it('should initialize to model', function() {
  19206. expect(text.getText()).toContain('http://google.com');
  19207. expect(valid.getText()).toContain('true');
  19208. });
  19209. it('should be invalid if empty', function() {
  19210. input.clear();
  19211. input.sendKeys('');
  19212. expect(text.getText()).toEqual('text =');
  19213. expect(valid.getText()).toContain('false');
  19214. });
  19215. it('should be invalid if not url', function() {
  19216. input.clear();
  19217. input.sendKeys('box');
  19218. expect(valid.getText()).toContain('false');
  19219. });
  19220. </file>
  19221. </example>
  19222. */
  19223. 'url': urlInputType,
  19224. /**
  19225. * @ngdoc input
  19226. * @name input[email]
  19227. *
  19228. * @description
  19229. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19230. * address.
  19231. *
  19232. * <div class="alert alert-warning">
  19233. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19234. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19235. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19236. * </div>
  19237. *
  19238. * @param {string} ngModel Assignable angular expression to data-bind to.
  19239. * @param {string=} name Property name of the form under which the control is published.
  19240. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19241. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19242. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19243. * `required` when you want to data-bind to the `required` attribute.
  19244. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19245. * minlength.
  19246. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19247. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19248. * any length.
  19249. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19250. * that contains the regular expression body that will be converted to a regular expression
  19251. * as in the ngPattern directive.
  19252. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19253. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19254. * If the expression evaluates to a RegExp object, then this is used directly.
  19255. * If the expression evaluates to a string, then it will be converted to a RegExp
  19256. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19257. * `new RegExp('^abc$')`.<br />
  19258. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19259. * start at the index of the last search's match, thus not taking the whole input value into
  19260. * account.
  19261. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19262. * interaction with the input element.
  19263. *
  19264. * @example
  19265. <example name="email-input-directive" module="emailExample">
  19266. <file name="index.html">
  19267. <script>
  19268. angular.module('emailExample', [])
  19269. .controller('ExampleController', ['$scope', function($scope) {
  19270. $scope.email = {
  19271. text: 'me@example.com'
  19272. };
  19273. }]);
  19274. </script>
  19275. <form name="myForm" ng-controller="ExampleController">
  19276. <label>Email:
  19277. <input type="email" name="input" ng-model="email.text" required>
  19278. </label>
  19279. <div role="alert">
  19280. <span class="error" ng-show="myForm.input.$error.required">
  19281. Required!</span>
  19282. <span class="error" ng-show="myForm.input.$error.email">
  19283. Not valid email!</span>
  19284. </div>
  19285. <tt>text = {{email.text}}</tt><br/>
  19286. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19287. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19288. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19289. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19290. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19291. </form>
  19292. </file>
  19293. <file name="protractor.js" type="protractor">
  19294. var text = element(by.binding('email.text'));
  19295. var valid = element(by.binding('myForm.input.$valid'));
  19296. var input = element(by.model('email.text'));
  19297. it('should initialize to model', function() {
  19298. expect(text.getText()).toContain('me@example.com');
  19299. expect(valid.getText()).toContain('true');
  19300. });
  19301. it('should be invalid if empty', function() {
  19302. input.clear();
  19303. input.sendKeys('');
  19304. expect(text.getText()).toEqual('text =');
  19305. expect(valid.getText()).toContain('false');
  19306. });
  19307. it('should be invalid if not email', function() {
  19308. input.clear();
  19309. input.sendKeys('xxx');
  19310. expect(valid.getText()).toContain('false');
  19311. });
  19312. </file>
  19313. </example>
  19314. */
  19315. 'email': emailInputType,
  19316. /**
  19317. * @ngdoc input
  19318. * @name input[radio]
  19319. *
  19320. * @description
  19321. * HTML radio button.
  19322. *
  19323. * @param {string} ngModel Assignable angular expression to data-bind to.
  19324. * @param {string} value The value to which the expression should be set when selected.
  19325. * @param {string=} name Property name of the form under which the control is published.
  19326. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19327. * interaction with the input element.
  19328. * @param {string} ngValue Angular expression which sets the value to which the expression should
  19329. * be set when selected.
  19330. *
  19331. * @example
  19332. <example name="radio-input-directive" module="radioExample">
  19333. <file name="index.html">
  19334. <script>
  19335. angular.module('radioExample', [])
  19336. .controller('ExampleController', ['$scope', function($scope) {
  19337. $scope.color = {
  19338. name: 'blue'
  19339. };
  19340. $scope.specialValue = {
  19341. "id": "12345",
  19342. "value": "green"
  19343. };
  19344. }]);
  19345. </script>
  19346. <form name="myForm" ng-controller="ExampleController">
  19347. <label>
  19348. <input type="radio" ng-model="color.name" value="red">
  19349. Red
  19350. </label><br/>
  19351. <label>
  19352. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19353. Green
  19354. </label><br/>
  19355. <label>
  19356. <input type="radio" ng-model="color.name" value="blue">
  19357. Blue
  19358. </label><br/>
  19359. <tt>color = {{color.name | json}}</tt><br/>
  19360. </form>
  19361. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19362. </file>
  19363. <file name="protractor.js" type="protractor">
  19364. it('should change state', function() {
  19365. var color = element(by.binding('color.name'));
  19366. expect(color.getText()).toContain('blue');
  19367. element.all(by.model('color.name')).get(0).click();
  19368. expect(color.getText()).toContain('red');
  19369. });
  19370. </file>
  19371. </example>
  19372. */
  19373. 'radio': radioInputType,
  19374. /**
  19375. * @ngdoc input
  19376. * @name input[checkbox]
  19377. *
  19378. * @description
  19379. * HTML checkbox.
  19380. *
  19381. * @param {string} ngModel Assignable angular expression to data-bind to.
  19382. * @param {string=} name Property name of the form under which the control is published.
  19383. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19384. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19385. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19386. * interaction with the input element.
  19387. *
  19388. * @example
  19389. <example name="checkbox-input-directive" module="checkboxExample">
  19390. <file name="index.html">
  19391. <script>
  19392. angular.module('checkboxExample', [])
  19393. .controller('ExampleController', ['$scope', function($scope) {
  19394. $scope.checkboxModel = {
  19395. value1 : true,
  19396. value2 : 'YES'
  19397. };
  19398. }]);
  19399. </script>
  19400. <form name="myForm" ng-controller="ExampleController">
  19401. <label>Value1:
  19402. <input type="checkbox" ng-model="checkboxModel.value1">
  19403. </label><br/>
  19404. <label>Value2:
  19405. <input type="checkbox" ng-model="checkboxModel.value2"
  19406. ng-true-value="'YES'" ng-false-value="'NO'">
  19407. </label><br/>
  19408. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19409. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19410. </form>
  19411. </file>
  19412. <file name="protractor.js" type="protractor">
  19413. it('should change state', function() {
  19414. var value1 = element(by.binding('checkboxModel.value1'));
  19415. var value2 = element(by.binding('checkboxModel.value2'));
  19416. expect(value1.getText()).toContain('true');
  19417. expect(value2.getText()).toContain('YES');
  19418. element(by.model('checkboxModel.value1')).click();
  19419. element(by.model('checkboxModel.value2')).click();
  19420. expect(value1.getText()).toContain('false');
  19421. expect(value2.getText()).toContain('NO');
  19422. });
  19423. </file>
  19424. </example>
  19425. */
  19426. 'checkbox': checkboxInputType,
  19427. 'hidden': noop,
  19428. 'button': noop,
  19429. 'submit': noop,
  19430. 'reset': noop,
  19431. 'file': noop
  19432. };
  19433. function stringBasedInputType(ctrl) {
  19434. ctrl.$formatters.push(function(value) {
  19435. return ctrl.$isEmpty(value) ? value : value.toString();
  19436. });
  19437. }
  19438. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19439. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19440. stringBasedInputType(ctrl);
  19441. }
  19442. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19443. var type = lowercase(element[0].type);
  19444. // In composition mode, users are still inputing intermediate text buffer,
  19445. // hold the listener until composition is done.
  19446. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19447. if (!$sniffer.android) {
  19448. var composing = false;
  19449. element.on('compositionstart', function(data) {
  19450. composing = true;
  19451. });
  19452. element.on('compositionend', function() {
  19453. composing = false;
  19454. listener();
  19455. });
  19456. }
  19457. var listener = function(ev) {
  19458. if (timeout) {
  19459. $browser.defer.cancel(timeout);
  19460. timeout = null;
  19461. }
  19462. if (composing) return;
  19463. var value = element.val(),
  19464. event = ev && ev.type;
  19465. // By default we will trim the value
  19466. // If the attribute ng-trim exists we will avoid trimming
  19467. // If input type is 'password', the value is never trimmed
  19468. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19469. value = trim(value);
  19470. }
  19471. // If a control is suffering from bad input (due to native validators), browsers discard its
  19472. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19473. // control's value is the same empty value twice in a row.
  19474. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19475. ctrl.$setViewValue(value, event);
  19476. }
  19477. };
  19478. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19479. // input event on backspace, delete or cut
  19480. if ($sniffer.hasEvent('input')) {
  19481. element.on('input', listener);
  19482. } else {
  19483. var timeout;
  19484. var deferListener = function(ev, input, origValue) {
  19485. if (!timeout) {
  19486. timeout = $browser.defer(function() {
  19487. timeout = null;
  19488. if (!input || input.value !== origValue) {
  19489. listener(ev);
  19490. }
  19491. });
  19492. }
  19493. };
  19494. element.on('keydown', function(event) {
  19495. var key = event.keyCode;
  19496. // ignore
  19497. // command modifiers arrows
  19498. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19499. deferListener(event, this, this.value);
  19500. });
  19501. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19502. if ($sniffer.hasEvent('paste')) {
  19503. element.on('paste cut', deferListener);
  19504. }
  19505. }
  19506. // if user paste into input using mouse on older browser
  19507. // or form autocomplete on newer browser, we need "change" event to catch it
  19508. element.on('change', listener);
  19509. ctrl.$render = function() {
  19510. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  19511. };
  19512. }
  19513. function weekParser(isoWeek, existingDate) {
  19514. if (isDate(isoWeek)) {
  19515. return isoWeek;
  19516. }
  19517. if (isString(isoWeek)) {
  19518. WEEK_REGEXP.lastIndex = 0;
  19519. var parts = WEEK_REGEXP.exec(isoWeek);
  19520. if (parts) {
  19521. var year = +parts[1],
  19522. week = +parts[2],
  19523. hours = 0,
  19524. minutes = 0,
  19525. seconds = 0,
  19526. milliseconds = 0,
  19527. firstThurs = getFirstThursdayOfYear(year),
  19528. addDays = (week - 1) * 7;
  19529. if (existingDate) {
  19530. hours = existingDate.getHours();
  19531. minutes = existingDate.getMinutes();
  19532. seconds = existingDate.getSeconds();
  19533. milliseconds = existingDate.getMilliseconds();
  19534. }
  19535. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19536. }
  19537. }
  19538. return NaN;
  19539. }
  19540. function createDateParser(regexp, mapping) {
  19541. return function(iso, date) {
  19542. var parts, map;
  19543. if (isDate(iso)) {
  19544. return iso;
  19545. }
  19546. if (isString(iso)) {
  19547. // When a date is JSON'ified to wraps itself inside of an extra
  19548. // set of double quotes. This makes the date parsing code unable
  19549. // to match the date string and parse it as a date.
  19550. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19551. iso = iso.substring(1, iso.length - 1);
  19552. }
  19553. if (ISO_DATE_REGEXP.test(iso)) {
  19554. return new Date(iso);
  19555. }
  19556. regexp.lastIndex = 0;
  19557. parts = regexp.exec(iso);
  19558. if (parts) {
  19559. parts.shift();
  19560. if (date) {
  19561. map = {
  19562. yyyy: date.getFullYear(),
  19563. MM: date.getMonth() + 1,
  19564. dd: date.getDate(),
  19565. HH: date.getHours(),
  19566. mm: date.getMinutes(),
  19567. ss: date.getSeconds(),
  19568. sss: date.getMilliseconds() / 1000
  19569. };
  19570. } else {
  19571. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19572. }
  19573. forEach(parts, function(part, index) {
  19574. if (index < mapping.length) {
  19575. map[mapping[index]] = +part;
  19576. }
  19577. });
  19578. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19579. }
  19580. }
  19581. return NaN;
  19582. };
  19583. }
  19584. function createDateInputType(type, regexp, parseDate, format) {
  19585. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19586. badInputChecker(scope, element, attr, ctrl);
  19587. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19588. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19589. var previousDate;
  19590. ctrl.$$parserName = type;
  19591. ctrl.$parsers.push(function(value) {
  19592. if (ctrl.$isEmpty(value)) return null;
  19593. if (regexp.test(value)) {
  19594. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19595. // parser/formatter in the processing chain so that the model
  19596. // contains some different data format!
  19597. var parsedDate = parseDate(value, previousDate);
  19598. if (timezone) {
  19599. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19600. }
  19601. return parsedDate;
  19602. }
  19603. return undefined;
  19604. });
  19605. ctrl.$formatters.push(function(value) {
  19606. if (value && !isDate(value)) {
  19607. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19608. }
  19609. if (isValidDate(value)) {
  19610. previousDate = value;
  19611. if (previousDate && timezone) {
  19612. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19613. }
  19614. return $filter('date')(value, format, timezone);
  19615. } else {
  19616. previousDate = null;
  19617. return '';
  19618. }
  19619. });
  19620. if (isDefined(attr.min) || attr.ngMin) {
  19621. var minVal;
  19622. ctrl.$validators.min = function(value) {
  19623. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19624. };
  19625. attr.$observe('min', function(val) {
  19626. minVal = parseObservedDateValue(val);
  19627. ctrl.$validate();
  19628. });
  19629. }
  19630. if (isDefined(attr.max) || attr.ngMax) {
  19631. var maxVal;
  19632. ctrl.$validators.max = function(value) {
  19633. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19634. };
  19635. attr.$observe('max', function(val) {
  19636. maxVal = parseObservedDateValue(val);
  19637. ctrl.$validate();
  19638. });
  19639. }
  19640. function isValidDate(value) {
  19641. // Invalid Date: getTime() returns NaN
  19642. return value && !(value.getTime && value.getTime() !== value.getTime());
  19643. }
  19644. function parseObservedDateValue(val) {
  19645. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  19646. }
  19647. };
  19648. }
  19649. function badInputChecker(scope, element, attr, ctrl) {
  19650. var node = element[0];
  19651. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19652. if (nativeValidation) {
  19653. ctrl.$parsers.push(function(value) {
  19654. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19655. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19656. // - also sets validity.badInput (should only be validity.typeMismatch).
  19657. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19658. // - can ignore this case as we can still read out the erroneous email...
  19659. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19660. });
  19661. }
  19662. }
  19663. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19664. badInputChecker(scope, element, attr, ctrl);
  19665. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19666. ctrl.$$parserName = 'number';
  19667. ctrl.$parsers.push(function(value) {
  19668. if (ctrl.$isEmpty(value)) return null;
  19669. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19670. return undefined;
  19671. });
  19672. ctrl.$formatters.push(function(value) {
  19673. if (!ctrl.$isEmpty(value)) {
  19674. if (!isNumber(value)) {
  19675. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19676. }
  19677. value = value.toString();
  19678. }
  19679. return value;
  19680. });
  19681. if (isDefined(attr.min) || attr.ngMin) {
  19682. var minVal;
  19683. ctrl.$validators.min = function(value) {
  19684. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19685. };
  19686. attr.$observe('min', function(val) {
  19687. if (isDefined(val) && !isNumber(val)) {
  19688. val = parseFloat(val, 10);
  19689. }
  19690. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19691. // TODO(matsko): implement validateLater to reduce number of validations
  19692. ctrl.$validate();
  19693. });
  19694. }
  19695. if (isDefined(attr.max) || attr.ngMax) {
  19696. var maxVal;
  19697. ctrl.$validators.max = function(value) {
  19698. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19699. };
  19700. attr.$observe('max', function(val) {
  19701. if (isDefined(val) && !isNumber(val)) {
  19702. val = parseFloat(val, 10);
  19703. }
  19704. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19705. // TODO(matsko): implement validateLater to reduce number of validations
  19706. ctrl.$validate();
  19707. });
  19708. }
  19709. }
  19710. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19711. // Note: no badInputChecker here by purpose as `url` is only a validation
  19712. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19713. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19714. stringBasedInputType(ctrl);
  19715. ctrl.$$parserName = 'url';
  19716. ctrl.$validators.url = function(modelValue, viewValue) {
  19717. var value = modelValue || viewValue;
  19718. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19719. };
  19720. }
  19721. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19722. // Note: no badInputChecker here by purpose as `url` is only a validation
  19723. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19724. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19725. stringBasedInputType(ctrl);
  19726. ctrl.$$parserName = 'email';
  19727. ctrl.$validators.email = function(modelValue, viewValue) {
  19728. var value = modelValue || viewValue;
  19729. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19730. };
  19731. }
  19732. function radioInputType(scope, element, attr, ctrl) {
  19733. // make the name unique, if not defined
  19734. if (isUndefined(attr.name)) {
  19735. element.attr('name', nextUid());
  19736. }
  19737. var listener = function(ev) {
  19738. if (element[0].checked) {
  19739. ctrl.$setViewValue(attr.value, ev && ev.type);
  19740. }
  19741. };
  19742. element.on('click', listener);
  19743. ctrl.$render = function() {
  19744. var value = attr.value;
  19745. element[0].checked = (value == ctrl.$viewValue);
  19746. };
  19747. attr.$observe('value', ctrl.$render);
  19748. }
  19749. function parseConstantExpr($parse, context, name, expression, fallback) {
  19750. var parseFn;
  19751. if (isDefined(expression)) {
  19752. parseFn = $parse(expression);
  19753. if (!parseFn.constant) {
  19754. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19755. '`{1}`.', name, expression);
  19756. }
  19757. return parseFn(context);
  19758. }
  19759. return fallback;
  19760. }
  19761. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19762. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19763. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19764. var listener = function(ev) {
  19765. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19766. };
  19767. element.on('click', listener);
  19768. ctrl.$render = function() {
  19769. element[0].checked = ctrl.$viewValue;
  19770. };
  19771. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19772. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19773. // it to a boolean.
  19774. ctrl.$isEmpty = function(value) {
  19775. return value === false;
  19776. };
  19777. ctrl.$formatters.push(function(value) {
  19778. return equals(value, trueValue);
  19779. });
  19780. ctrl.$parsers.push(function(value) {
  19781. return value ? trueValue : falseValue;
  19782. });
  19783. }
  19784. /**
  19785. * @ngdoc directive
  19786. * @name textarea
  19787. * @restrict E
  19788. *
  19789. * @description
  19790. * HTML textarea element control with angular data-binding. The data-binding and validation
  19791. * properties of this element are exactly the same as those of the
  19792. * {@link ng.directive:input input element}.
  19793. *
  19794. * @param {string} ngModel Assignable angular expression to data-bind to.
  19795. * @param {string=} name Property name of the form under which the control is published.
  19796. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19797. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19798. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19799. * `required` when you want to data-bind to the `required` attribute.
  19800. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19801. * minlength.
  19802. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19803. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19804. * length.
  19805. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19806. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19807. * If the expression evaluates to a RegExp object, then this is used directly.
  19808. * If the expression evaluates to a string, then it will be converted to a RegExp
  19809. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19810. * `new RegExp('^abc$')`.<br />
  19811. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19812. * start at the index of the last search's match, thus not taking the whole input value into
  19813. * account.
  19814. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19815. * interaction with the input element.
  19816. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19817. */
  19818. /**
  19819. * @ngdoc directive
  19820. * @name input
  19821. * @restrict E
  19822. *
  19823. * @description
  19824. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  19825. * input state control, and validation.
  19826. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  19827. *
  19828. * <div class="alert alert-warning">
  19829. * **Note:** Not every feature offered is available for all input types.
  19830. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  19831. * </div>
  19832. *
  19833. * @param {string} ngModel Assignable angular expression to data-bind to.
  19834. * @param {string=} name Property name of the form under which the control is published.
  19835. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19836. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  19837. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19838. * minlength.
  19839. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19840. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19841. * length.
  19842. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19843. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19844. * If the expression evaluates to a RegExp object, then this is used directly.
  19845. * If the expression evaluates to a string, then it will be converted to a RegExp
  19846. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19847. * `new RegExp('^abc$')`.<br />
  19848. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19849. * start at the index of the last search's match, thus not taking the whole input value into
  19850. * account.
  19851. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19852. * interaction with the input element.
  19853. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19854. * This parameter is ignored for input[type=password] controls, which will never trim the
  19855. * input.
  19856. *
  19857. * @example
  19858. <example name="input-directive" module="inputExample">
  19859. <file name="index.html">
  19860. <script>
  19861. angular.module('inputExample', [])
  19862. .controller('ExampleController', ['$scope', function($scope) {
  19863. $scope.user = {name: 'guest', last: 'visitor'};
  19864. }]);
  19865. </script>
  19866. <div ng-controller="ExampleController">
  19867. <form name="myForm">
  19868. <label>
  19869. User name:
  19870. <input type="text" name="userName" ng-model="user.name" required>
  19871. </label>
  19872. <div role="alert">
  19873. <span class="error" ng-show="myForm.userName.$error.required">
  19874. Required!</span>
  19875. </div>
  19876. <label>
  19877. Last name:
  19878. <input type="text" name="lastName" ng-model="user.last"
  19879. ng-minlength="3" ng-maxlength="10">
  19880. </label>
  19881. <div role="alert">
  19882. <span class="error" ng-show="myForm.lastName.$error.minlength">
  19883. Too short!</span>
  19884. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  19885. Too long!</span>
  19886. </div>
  19887. </form>
  19888. <hr>
  19889. <tt>user = {{user}}</tt><br/>
  19890. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  19891. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  19892. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  19893. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  19894. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19895. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19896. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  19897. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  19898. </div>
  19899. </file>
  19900. <file name="protractor.js" type="protractor">
  19901. var user = element(by.exactBinding('user'));
  19902. var userNameValid = element(by.binding('myForm.userName.$valid'));
  19903. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  19904. var lastNameError = element(by.binding('myForm.lastName.$error'));
  19905. var formValid = element(by.binding('myForm.$valid'));
  19906. var userNameInput = element(by.model('user.name'));
  19907. var userLastInput = element(by.model('user.last'));
  19908. it('should initialize to model', function() {
  19909. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  19910. expect(userNameValid.getText()).toContain('true');
  19911. expect(formValid.getText()).toContain('true');
  19912. });
  19913. it('should be invalid if empty when required', function() {
  19914. userNameInput.clear();
  19915. userNameInput.sendKeys('');
  19916. expect(user.getText()).toContain('{"last":"visitor"}');
  19917. expect(userNameValid.getText()).toContain('false');
  19918. expect(formValid.getText()).toContain('false');
  19919. });
  19920. it('should be valid if empty when min length is set', function() {
  19921. userLastInput.clear();
  19922. userLastInput.sendKeys('');
  19923. expect(user.getText()).toContain('{"name":"guest","last":""}');
  19924. expect(lastNameValid.getText()).toContain('true');
  19925. expect(formValid.getText()).toContain('true');
  19926. });
  19927. it('should be invalid if less than required min length', function() {
  19928. userLastInput.clear();
  19929. userLastInput.sendKeys('xx');
  19930. expect(user.getText()).toContain('{"name":"guest"}');
  19931. expect(lastNameValid.getText()).toContain('false');
  19932. expect(lastNameError.getText()).toContain('minlength');
  19933. expect(formValid.getText()).toContain('false');
  19934. });
  19935. it('should be invalid if longer than max length', function() {
  19936. userLastInput.clear();
  19937. userLastInput.sendKeys('some ridiculously long name');
  19938. expect(user.getText()).toContain('{"name":"guest"}');
  19939. expect(lastNameValid.getText()).toContain('false');
  19940. expect(lastNameError.getText()).toContain('maxlength');
  19941. expect(formValid.getText()).toContain('false');
  19942. });
  19943. </file>
  19944. </example>
  19945. */
  19946. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  19947. function($browser, $sniffer, $filter, $parse) {
  19948. return {
  19949. restrict: 'E',
  19950. require: ['?ngModel'],
  19951. link: {
  19952. pre: function(scope, element, attr, ctrls) {
  19953. if (ctrls[0]) {
  19954. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  19955. $browser, $filter, $parse);
  19956. }
  19957. }
  19958. }
  19959. };
  19960. }];
  19961. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19962. /**
  19963. * @ngdoc directive
  19964. * @name ngValue
  19965. *
  19966. * @description
  19967. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  19968. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  19969. * the bound value.
  19970. *
  19971. * `ngValue` is useful when dynamically generating lists of radio buttons using
  19972. * {@link ngRepeat `ngRepeat`}, as shown below.
  19973. *
  19974. * Likewise, `ngValue` can be used to generate `<option>` elements for
  19975. * the {@link select `select`} element. In that case however, only strings are supported
  19976. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  19977. * Support for `select` models with non-string values is available via `ngOptions`.
  19978. *
  19979. * @element input
  19980. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19981. * of the `input` element
  19982. *
  19983. * @example
  19984. <example name="ngValue-directive" module="valueExample">
  19985. <file name="index.html">
  19986. <script>
  19987. angular.module('valueExample', [])
  19988. .controller('ExampleController', ['$scope', function($scope) {
  19989. $scope.names = ['pizza', 'unicorns', 'robots'];
  19990. $scope.my = { favorite: 'unicorns' };
  19991. }]);
  19992. </script>
  19993. <form ng-controller="ExampleController">
  19994. <h2>Which is your favorite?</h2>
  19995. <label ng-repeat="name in names" for="{{name}}">
  19996. {{name}}
  19997. <input type="radio"
  19998. ng-model="my.favorite"
  19999. ng-value="name"
  20000. id="{{name}}"
  20001. name="favorite">
  20002. </label>
  20003. <div>You chose {{my.favorite}}</div>
  20004. </form>
  20005. </file>
  20006. <file name="protractor.js" type="protractor">
  20007. var favorite = element(by.binding('my.favorite'));
  20008. it('should initialize to model', function() {
  20009. expect(favorite.getText()).toContain('unicorns');
  20010. });
  20011. it('should bind the values to the inputs', function() {
  20012. element.all(by.model('my.favorite')).get(0).click();
  20013. expect(favorite.getText()).toContain('pizza');
  20014. });
  20015. </file>
  20016. </example>
  20017. */
  20018. var ngValueDirective = function() {
  20019. return {
  20020. restrict: 'A',
  20021. priority: 100,
  20022. compile: function(tpl, tplAttr) {
  20023. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20024. return function ngValueConstantLink(scope, elm, attr) {
  20025. attr.$set('value', scope.$eval(attr.ngValue));
  20026. };
  20027. } else {
  20028. return function ngValueLink(scope, elm, attr) {
  20029. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20030. attr.$set('value', value);
  20031. });
  20032. };
  20033. }
  20034. }
  20035. };
  20036. };
  20037. /**
  20038. * @ngdoc directive
  20039. * @name ngBind
  20040. * @restrict AC
  20041. *
  20042. * @description
  20043. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20044. * with the value of a given expression, and to update the text content when the value of that
  20045. * expression changes.
  20046. *
  20047. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20048. * `{{ expression }}` which is similar but less verbose.
  20049. *
  20050. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20051. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20052. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20053. *
  20054. * An alternative solution to this problem would be using the
  20055. * {@link ng.directive:ngCloak ngCloak} directive.
  20056. *
  20057. *
  20058. * @element ANY
  20059. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20060. *
  20061. * @example
  20062. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20063. <example module="bindExample">
  20064. <file name="index.html">
  20065. <script>
  20066. angular.module('bindExample', [])
  20067. .controller('ExampleController', ['$scope', function($scope) {
  20068. $scope.name = 'Whirled';
  20069. }]);
  20070. </script>
  20071. <div ng-controller="ExampleController">
  20072. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20073. Hello <span ng-bind="name"></span>!
  20074. </div>
  20075. </file>
  20076. <file name="protractor.js" type="protractor">
  20077. it('should check ng-bind', function() {
  20078. var nameInput = element(by.model('name'));
  20079. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20080. nameInput.clear();
  20081. nameInput.sendKeys('world');
  20082. expect(element(by.binding('name')).getText()).toBe('world');
  20083. });
  20084. </file>
  20085. </example>
  20086. */
  20087. var ngBindDirective = ['$compile', function($compile) {
  20088. return {
  20089. restrict: 'AC',
  20090. compile: function ngBindCompile(templateElement) {
  20091. $compile.$$addBindingClass(templateElement);
  20092. return function ngBindLink(scope, element, attr) {
  20093. $compile.$$addBindingInfo(element, attr.ngBind);
  20094. element = element[0];
  20095. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20096. element.textContent = value === undefined ? '' : value;
  20097. });
  20098. };
  20099. }
  20100. };
  20101. }];
  20102. /**
  20103. * @ngdoc directive
  20104. * @name ngBindTemplate
  20105. *
  20106. * @description
  20107. * The `ngBindTemplate` directive specifies that the element
  20108. * text content should be replaced with the interpolation of the template
  20109. * in the `ngBindTemplate` attribute.
  20110. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20111. * expressions. This directive is needed since some HTML elements
  20112. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20113. *
  20114. * @element ANY
  20115. * @param {string} ngBindTemplate template of form
  20116. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20117. *
  20118. * @example
  20119. * Try it here: enter text in text box and watch the greeting change.
  20120. <example module="bindExample">
  20121. <file name="index.html">
  20122. <script>
  20123. angular.module('bindExample', [])
  20124. .controller('ExampleController', ['$scope', function($scope) {
  20125. $scope.salutation = 'Hello';
  20126. $scope.name = 'World';
  20127. }]);
  20128. </script>
  20129. <div ng-controller="ExampleController">
  20130. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20131. <label>Name: <input type="text" ng-model="name"></label><br>
  20132. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20133. </div>
  20134. </file>
  20135. <file name="protractor.js" type="protractor">
  20136. it('should check ng-bind', function() {
  20137. var salutationElem = element(by.binding('salutation'));
  20138. var salutationInput = element(by.model('salutation'));
  20139. var nameInput = element(by.model('name'));
  20140. expect(salutationElem.getText()).toBe('Hello World!');
  20141. salutationInput.clear();
  20142. salutationInput.sendKeys('Greetings');
  20143. nameInput.clear();
  20144. nameInput.sendKeys('user');
  20145. expect(salutationElem.getText()).toBe('Greetings user!');
  20146. });
  20147. </file>
  20148. </example>
  20149. */
  20150. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20151. return {
  20152. compile: function ngBindTemplateCompile(templateElement) {
  20153. $compile.$$addBindingClass(templateElement);
  20154. return function ngBindTemplateLink(scope, element, attr) {
  20155. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20156. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20157. element = element[0];
  20158. attr.$observe('ngBindTemplate', function(value) {
  20159. element.textContent = value === undefined ? '' : value;
  20160. });
  20161. };
  20162. }
  20163. };
  20164. }];
  20165. /**
  20166. * @ngdoc directive
  20167. * @name ngBindHtml
  20168. *
  20169. * @description
  20170. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20171. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20172. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20173. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20174. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20175. *
  20176. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20177. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20178. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20179. *
  20180. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20181. * will have an exception (instead of an exploit.)
  20182. *
  20183. * @element ANY
  20184. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20185. *
  20186. * @example
  20187. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20188. <file name="index.html">
  20189. <div ng-controller="ExampleController">
  20190. <p ng-bind-html="myHTML"></p>
  20191. </div>
  20192. </file>
  20193. <file name="script.js">
  20194. angular.module('bindHtmlExample', ['ngSanitize'])
  20195. .controller('ExampleController', ['$scope', function($scope) {
  20196. $scope.myHTML =
  20197. 'I am an <code>HTML</code>string with ' +
  20198. '<a href="#">links!</a> and other <em>stuff</em>';
  20199. }]);
  20200. </file>
  20201. <file name="protractor.js" type="protractor">
  20202. it('should check ng-bind-html', function() {
  20203. expect(element(by.binding('myHTML')).getText()).toBe(
  20204. 'I am an HTMLstring with links! and other stuff');
  20205. });
  20206. </file>
  20207. </example>
  20208. */
  20209. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20210. return {
  20211. restrict: 'A',
  20212. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20213. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20214. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20215. return (value || '').toString();
  20216. });
  20217. $compile.$$addBindingClass(tElement);
  20218. return function ngBindHtmlLink(scope, element, attr) {
  20219. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20220. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20221. // we re-evaluate the expr because we want a TrustedValueHolderType
  20222. // for $sce, not a string
  20223. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20224. });
  20225. };
  20226. }
  20227. };
  20228. }];
  20229. /**
  20230. * @ngdoc directive
  20231. * @name ngChange
  20232. *
  20233. * @description
  20234. * Evaluate the given expression when the user changes the input.
  20235. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20236. * which only triggers at the end of a change (usually, when the user leaves the
  20237. * form element or presses the return key).
  20238. *
  20239. * The `ngChange` expression is only evaluated when a change in the input value causes
  20240. * a new value to be committed to the model.
  20241. *
  20242. * It will not be evaluated:
  20243. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20244. * * if the input has continued to be invalid since the model will stay `null`
  20245. * * if the model is changed programmatically and not by a change to the input value
  20246. *
  20247. *
  20248. * Note, this directive requires `ngModel` to be present.
  20249. *
  20250. * @element input
  20251. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20252. * in input value.
  20253. *
  20254. * @example
  20255. * <example name="ngChange-directive" module="changeExample">
  20256. * <file name="index.html">
  20257. * <script>
  20258. * angular.module('changeExample', [])
  20259. * .controller('ExampleController', ['$scope', function($scope) {
  20260. * $scope.counter = 0;
  20261. * $scope.change = function() {
  20262. * $scope.counter++;
  20263. * };
  20264. * }]);
  20265. * </script>
  20266. * <div ng-controller="ExampleController">
  20267. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20268. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20269. * <label for="ng-change-example2">Confirmed</label><br />
  20270. * <tt>debug = {{confirmed}}</tt><br/>
  20271. * <tt>counter = {{counter}}</tt><br/>
  20272. * </div>
  20273. * </file>
  20274. * <file name="protractor.js" type="protractor">
  20275. * var counter = element(by.binding('counter'));
  20276. * var debug = element(by.binding('confirmed'));
  20277. *
  20278. * it('should evaluate the expression if changing from view', function() {
  20279. * expect(counter.getText()).toContain('0');
  20280. *
  20281. * element(by.id('ng-change-example1')).click();
  20282. *
  20283. * expect(counter.getText()).toContain('1');
  20284. * expect(debug.getText()).toContain('true');
  20285. * });
  20286. *
  20287. * it('should not evaluate the expression if changing from model', function() {
  20288. * element(by.id('ng-change-example2')).click();
  20289. * expect(counter.getText()).toContain('0');
  20290. * expect(debug.getText()).toContain('true');
  20291. * });
  20292. * </file>
  20293. * </example>
  20294. */
  20295. var ngChangeDirective = valueFn({
  20296. restrict: 'A',
  20297. require: 'ngModel',
  20298. link: function(scope, element, attr, ctrl) {
  20299. ctrl.$viewChangeListeners.push(function() {
  20300. scope.$eval(attr.ngChange);
  20301. });
  20302. }
  20303. });
  20304. function classDirective(name, selector) {
  20305. name = 'ngClass' + name;
  20306. return ['$animate', function($animate) {
  20307. return {
  20308. restrict: 'AC',
  20309. link: function(scope, element, attr) {
  20310. var oldVal;
  20311. scope.$watch(attr[name], ngClassWatchAction, true);
  20312. attr.$observe('class', function(value) {
  20313. ngClassWatchAction(scope.$eval(attr[name]));
  20314. });
  20315. if (name !== 'ngClass') {
  20316. scope.$watch('$index', function($index, old$index) {
  20317. // jshint bitwise: false
  20318. var mod = $index & 1;
  20319. if (mod !== (old$index & 1)) {
  20320. var classes = arrayClasses(scope.$eval(attr[name]));
  20321. mod === selector ?
  20322. addClasses(classes) :
  20323. removeClasses(classes);
  20324. }
  20325. });
  20326. }
  20327. function addClasses(classes) {
  20328. var newClasses = digestClassCounts(classes, 1);
  20329. attr.$addClass(newClasses);
  20330. }
  20331. function removeClasses(classes) {
  20332. var newClasses = digestClassCounts(classes, -1);
  20333. attr.$removeClass(newClasses);
  20334. }
  20335. function digestClassCounts(classes, count) {
  20336. // Use createMap() to prevent class assumptions involving property
  20337. // names in Object.prototype
  20338. var classCounts = element.data('$classCounts') || createMap();
  20339. var classesToUpdate = [];
  20340. forEach(classes, function(className) {
  20341. if (count > 0 || classCounts[className]) {
  20342. classCounts[className] = (classCounts[className] || 0) + count;
  20343. if (classCounts[className] === +(count > 0)) {
  20344. classesToUpdate.push(className);
  20345. }
  20346. }
  20347. });
  20348. element.data('$classCounts', classCounts);
  20349. return classesToUpdate.join(' ');
  20350. }
  20351. function updateClasses(oldClasses, newClasses) {
  20352. var toAdd = arrayDifference(newClasses, oldClasses);
  20353. var toRemove = arrayDifference(oldClasses, newClasses);
  20354. toAdd = digestClassCounts(toAdd, 1);
  20355. toRemove = digestClassCounts(toRemove, -1);
  20356. if (toAdd && toAdd.length) {
  20357. $animate.addClass(element, toAdd);
  20358. }
  20359. if (toRemove && toRemove.length) {
  20360. $animate.removeClass(element, toRemove);
  20361. }
  20362. }
  20363. function ngClassWatchAction(newVal) {
  20364. if (selector === true || scope.$index % 2 === selector) {
  20365. var newClasses = arrayClasses(newVal || []);
  20366. if (!oldVal) {
  20367. addClasses(newClasses);
  20368. } else if (!equals(newVal,oldVal)) {
  20369. var oldClasses = arrayClasses(oldVal);
  20370. updateClasses(oldClasses, newClasses);
  20371. }
  20372. }
  20373. oldVal = shallowCopy(newVal);
  20374. }
  20375. }
  20376. };
  20377. function arrayDifference(tokens1, tokens2) {
  20378. var values = [];
  20379. outer:
  20380. for (var i = 0; i < tokens1.length; i++) {
  20381. var token = tokens1[i];
  20382. for (var j = 0; j < tokens2.length; j++) {
  20383. if (token == tokens2[j]) continue outer;
  20384. }
  20385. values.push(token);
  20386. }
  20387. return values;
  20388. }
  20389. function arrayClasses(classVal) {
  20390. var classes = [];
  20391. if (isArray(classVal)) {
  20392. forEach(classVal, function(v) {
  20393. classes = classes.concat(arrayClasses(v));
  20394. });
  20395. return classes;
  20396. } else if (isString(classVal)) {
  20397. return classVal.split(' ');
  20398. } else if (isObject(classVal)) {
  20399. forEach(classVal, function(v, k) {
  20400. if (v) {
  20401. classes = classes.concat(k.split(' '));
  20402. }
  20403. });
  20404. return classes;
  20405. }
  20406. return classVal;
  20407. }
  20408. }];
  20409. }
  20410. /**
  20411. * @ngdoc directive
  20412. * @name ngClass
  20413. * @restrict AC
  20414. *
  20415. * @description
  20416. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20417. * an expression that represents all classes to be added.
  20418. *
  20419. * The directive operates in three different ways, depending on which of three types the expression
  20420. * evaluates to:
  20421. *
  20422. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20423. * names.
  20424. *
  20425. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20426. * object with a truthy value the corresponding key is used as a class name.
  20427. *
  20428. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20429. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20430. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20431. *
  20432. *
  20433. * The directive won't add duplicate classes if a particular class was already set.
  20434. *
  20435. * When the expression changes, the previously added classes are removed and only then are the
  20436. * new classes added.
  20437. *
  20438. * @animations
  20439. * **add** - happens just before the class is applied to the elements
  20440. *
  20441. * **remove** - happens just before the class is removed from the element
  20442. *
  20443. * @element ANY
  20444. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20445. * of the evaluation can be a string representing space delimited class
  20446. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20447. * names of the properties whose values are truthy will be added as css classes to the
  20448. * element.
  20449. *
  20450. * @example Example that demonstrates basic bindings via ngClass directive.
  20451. <example>
  20452. <file name="index.html">
  20453. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20454. <label>
  20455. <input type="checkbox" ng-model="deleted">
  20456. deleted (apply "strike" class)
  20457. </label><br>
  20458. <label>
  20459. <input type="checkbox" ng-model="important">
  20460. important (apply "bold" class)
  20461. </label><br>
  20462. <label>
  20463. <input type="checkbox" ng-model="error">
  20464. error (apply "has-error" class)
  20465. </label>
  20466. <hr>
  20467. <p ng-class="style">Using String Syntax</p>
  20468. <input type="text" ng-model="style"
  20469. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20470. <hr>
  20471. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20472. <input ng-model="style1"
  20473. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20474. <input ng-model="style2"
  20475. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20476. <input ng-model="style3"
  20477. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20478. <hr>
  20479. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20480. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20481. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20482. </file>
  20483. <file name="style.css">
  20484. .strike {
  20485. text-decoration: line-through;
  20486. }
  20487. .bold {
  20488. font-weight: bold;
  20489. }
  20490. .red {
  20491. color: red;
  20492. }
  20493. .has-error {
  20494. color: red;
  20495. background-color: yellow;
  20496. }
  20497. .orange {
  20498. color: orange;
  20499. }
  20500. </file>
  20501. <file name="protractor.js" type="protractor">
  20502. var ps = element.all(by.css('p'));
  20503. it('should let you toggle the class', function() {
  20504. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20505. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20506. element(by.model('important')).click();
  20507. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20508. element(by.model('error')).click();
  20509. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20510. });
  20511. it('should let you toggle string example', function() {
  20512. expect(ps.get(1).getAttribute('class')).toBe('');
  20513. element(by.model('style')).clear();
  20514. element(by.model('style')).sendKeys('red');
  20515. expect(ps.get(1).getAttribute('class')).toBe('red');
  20516. });
  20517. it('array example should have 3 classes', function() {
  20518. expect(ps.get(2).getAttribute('class')).toBe('');
  20519. element(by.model('style1')).sendKeys('bold');
  20520. element(by.model('style2')).sendKeys('strike');
  20521. element(by.model('style3')).sendKeys('red');
  20522. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20523. });
  20524. it('array with map example should have 2 classes', function() {
  20525. expect(ps.last().getAttribute('class')).toBe('');
  20526. element(by.model('style4')).sendKeys('bold');
  20527. element(by.model('warning')).click();
  20528. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20529. });
  20530. </file>
  20531. </example>
  20532. ## Animations
  20533. The example below demonstrates how to perform animations using ngClass.
  20534. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20535. <file name="index.html">
  20536. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20537. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20538. <br>
  20539. <span class="base-class" ng-class="myVar">Sample Text</span>
  20540. </file>
  20541. <file name="style.css">
  20542. .base-class {
  20543. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20544. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20545. }
  20546. .base-class.my-class {
  20547. color: red;
  20548. font-size:3em;
  20549. }
  20550. </file>
  20551. <file name="protractor.js" type="protractor">
  20552. it('should check ng-class', function() {
  20553. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20554. toMatch(/my-class/);
  20555. element(by.id('setbtn')).click();
  20556. expect(element(by.css('.base-class')).getAttribute('class')).
  20557. toMatch(/my-class/);
  20558. element(by.id('clearbtn')).click();
  20559. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20560. toMatch(/my-class/);
  20561. });
  20562. </file>
  20563. </example>
  20564. ## ngClass and pre-existing CSS3 Transitions/Animations
  20565. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20566. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20567. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20568. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20569. {@link $animate#removeClass $animate.removeClass}.
  20570. */
  20571. var ngClassDirective = classDirective('', true);
  20572. /**
  20573. * @ngdoc directive
  20574. * @name ngClassOdd
  20575. * @restrict AC
  20576. *
  20577. * @description
  20578. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20579. * {@link ng.directive:ngClass ngClass}, except they work in
  20580. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20581. *
  20582. * This directive can be applied only within the scope of an
  20583. * {@link ng.directive:ngRepeat ngRepeat}.
  20584. *
  20585. * @element ANY
  20586. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20587. * of the evaluation can be a string representing space delimited class names or an array.
  20588. *
  20589. * @example
  20590. <example>
  20591. <file name="index.html">
  20592. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20593. <li ng-repeat="name in names">
  20594. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20595. {{name}}
  20596. </span>
  20597. </li>
  20598. </ol>
  20599. </file>
  20600. <file name="style.css">
  20601. .odd {
  20602. color: red;
  20603. }
  20604. .even {
  20605. color: blue;
  20606. }
  20607. </file>
  20608. <file name="protractor.js" type="protractor">
  20609. it('should check ng-class-odd and ng-class-even', function() {
  20610. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20611. toMatch(/odd/);
  20612. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20613. toMatch(/even/);
  20614. });
  20615. </file>
  20616. </example>
  20617. */
  20618. var ngClassOddDirective = classDirective('Odd', 0);
  20619. /**
  20620. * @ngdoc directive
  20621. * @name ngClassEven
  20622. * @restrict AC
  20623. *
  20624. * @description
  20625. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20626. * {@link ng.directive:ngClass ngClass}, except they work in
  20627. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20628. *
  20629. * This directive can be applied only within the scope of an
  20630. * {@link ng.directive:ngRepeat ngRepeat}.
  20631. *
  20632. * @element ANY
  20633. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20634. * result of the evaluation can be a string representing space delimited class names or an array.
  20635. *
  20636. * @example
  20637. <example>
  20638. <file name="index.html">
  20639. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20640. <li ng-repeat="name in names">
  20641. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20642. {{name}} &nbsp; &nbsp; &nbsp;
  20643. </span>
  20644. </li>
  20645. </ol>
  20646. </file>
  20647. <file name="style.css">
  20648. .odd {
  20649. color: red;
  20650. }
  20651. .even {
  20652. color: blue;
  20653. }
  20654. </file>
  20655. <file name="protractor.js" type="protractor">
  20656. it('should check ng-class-odd and ng-class-even', function() {
  20657. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20658. toMatch(/odd/);
  20659. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20660. toMatch(/even/);
  20661. });
  20662. </file>
  20663. </example>
  20664. */
  20665. var ngClassEvenDirective = classDirective('Even', 1);
  20666. /**
  20667. * @ngdoc directive
  20668. * @name ngCloak
  20669. * @restrict AC
  20670. *
  20671. * @description
  20672. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20673. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20674. * directive to avoid the undesirable flicker effect caused by the html template display.
  20675. *
  20676. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20677. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20678. * of the browser view.
  20679. *
  20680. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20681. * `angular.min.js`.
  20682. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20683. *
  20684. * ```css
  20685. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20686. * display: none !important;
  20687. * }
  20688. * ```
  20689. *
  20690. * When this css rule is loaded by the browser, all html elements (including their children) that
  20691. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20692. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20693. * the compiled element visible.
  20694. *
  20695. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20696. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20697. * application.
  20698. *
  20699. * @element ANY
  20700. *
  20701. * @example
  20702. <example>
  20703. <file name="index.html">
  20704. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20705. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20706. </file>
  20707. <file name="protractor.js" type="protractor">
  20708. it('should remove the template directive and css class', function() {
  20709. expect($('#template1').getAttribute('ng-cloak')).
  20710. toBeNull();
  20711. expect($('#template2').getAttribute('ng-cloak')).
  20712. toBeNull();
  20713. });
  20714. </file>
  20715. </example>
  20716. *
  20717. */
  20718. var ngCloakDirective = ngDirective({
  20719. compile: function(element, attr) {
  20720. attr.$set('ngCloak', undefined);
  20721. element.removeClass('ng-cloak');
  20722. }
  20723. });
  20724. /**
  20725. * @ngdoc directive
  20726. * @name ngController
  20727. *
  20728. * @description
  20729. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20730. * supports the principles behind the Model-View-Controller design pattern.
  20731. *
  20732. * MVC components in angular:
  20733. *
  20734. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20735. * are accessed through bindings.
  20736. * * View — The template (HTML with data bindings) that is rendered into the View.
  20737. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20738. * logic behind the application to decorate the scope with functions and values
  20739. *
  20740. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20741. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20742. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20743. * and executed twice.
  20744. *
  20745. * @element ANY
  20746. * @scope
  20747. * @priority 500
  20748. * @param {expression} ngController Name of a constructor function registered with the current
  20749. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20750. * that on the current scope evaluates to a constructor function.
  20751. *
  20752. * The controller instance can be published into a scope property by specifying
  20753. * `ng-controller="as propertyName"`.
  20754. *
  20755. * If the current `$controllerProvider` is configured to use globals (via
  20756. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20757. * also be the name of a globally accessible constructor function (not recommended).
  20758. *
  20759. * @example
  20760. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20761. * greeting are methods declared on the controller (see source tab). These methods can
  20762. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20763. * in the View without the need for a manual update.
  20764. *
  20765. * Two different declaration styles are included below:
  20766. *
  20767. * * one binds methods and properties directly onto the controller using `this`:
  20768. * `ng-controller="SettingsController1 as settings"`
  20769. * * one injects `$scope` into the controller:
  20770. * `ng-controller="SettingsController2"`
  20771. *
  20772. * The second option is more common in the Angular community, and is generally used in boilerplates
  20773. * and in this guide. However, there are advantages to binding properties directly to the controller
  20774. * and avoiding scope.
  20775. *
  20776. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20777. * multiple controllers apply to an element.
  20778. * * If you are writing your controllers as classes you have easier access to the properties and
  20779. * methods, which will appear on the scope, from inside the controller code.
  20780. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20781. * inheritance masking primitives.
  20782. *
  20783. * This example demonstrates the `controller as` syntax.
  20784. *
  20785. * <example name="ngControllerAs" module="controllerAsExample">
  20786. * <file name="index.html">
  20787. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20788. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20789. * <button ng-click="settings.greet()">greet</button><br/>
  20790. * Contact:
  20791. * <ul>
  20792. * <li ng-repeat="contact in settings.contacts">
  20793. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20794. * <option>phone</option>
  20795. * <option>email</option>
  20796. * </select>
  20797. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20798. * <button ng-click="settings.clearContact(contact)">clear</button>
  20799. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20800. * </li>
  20801. * <li><button ng-click="settings.addContact()">add</button></li>
  20802. * </ul>
  20803. * </div>
  20804. * </file>
  20805. * <file name="app.js">
  20806. * angular.module('controllerAsExample', [])
  20807. * .controller('SettingsController1', SettingsController1);
  20808. *
  20809. * function SettingsController1() {
  20810. * this.name = "John Smith";
  20811. * this.contacts = [
  20812. * {type: 'phone', value: '408 555 1212'},
  20813. * {type: 'email', value: 'john.smith@example.org'} ];
  20814. * }
  20815. *
  20816. * SettingsController1.prototype.greet = function() {
  20817. * alert(this.name);
  20818. * };
  20819. *
  20820. * SettingsController1.prototype.addContact = function() {
  20821. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20822. * };
  20823. *
  20824. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20825. * var index = this.contacts.indexOf(contactToRemove);
  20826. * this.contacts.splice(index, 1);
  20827. * };
  20828. *
  20829. * SettingsController1.prototype.clearContact = function(contact) {
  20830. * contact.type = 'phone';
  20831. * contact.value = '';
  20832. * };
  20833. * </file>
  20834. * <file name="protractor.js" type="protractor">
  20835. * it('should check controller as', function() {
  20836. * var container = element(by.id('ctrl-as-exmpl'));
  20837. * expect(container.element(by.model('settings.name'))
  20838. * .getAttribute('value')).toBe('John Smith');
  20839. *
  20840. * var firstRepeat =
  20841. * container.element(by.repeater('contact in settings.contacts').row(0));
  20842. * var secondRepeat =
  20843. * container.element(by.repeater('contact in settings.contacts').row(1));
  20844. *
  20845. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20846. * .toBe('408 555 1212');
  20847. *
  20848. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20849. * .toBe('john.smith@example.org');
  20850. *
  20851. * firstRepeat.element(by.buttonText('clear')).click();
  20852. *
  20853. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20854. * .toBe('');
  20855. *
  20856. * container.element(by.buttonText('add')).click();
  20857. *
  20858. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20859. * .element(by.model('contact.value'))
  20860. * .getAttribute('value'))
  20861. * .toBe('yourname@example.org');
  20862. * });
  20863. * </file>
  20864. * </example>
  20865. *
  20866. * This example demonstrates the "attach to `$scope`" style of controller.
  20867. *
  20868. * <example name="ngController" module="controllerExample">
  20869. * <file name="index.html">
  20870. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20871. * <label>Name: <input type="text" ng-model="name"/></label>
  20872. * <button ng-click="greet()">greet</button><br/>
  20873. * Contact:
  20874. * <ul>
  20875. * <li ng-repeat="contact in contacts">
  20876. * <select ng-model="contact.type" id="select_{{$index}}">
  20877. * <option>phone</option>
  20878. * <option>email</option>
  20879. * </select>
  20880. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20881. * <button ng-click="clearContact(contact)">clear</button>
  20882. * <button ng-click="removeContact(contact)">X</button>
  20883. * </li>
  20884. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  20885. * </ul>
  20886. * </div>
  20887. * </file>
  20888. * <file name="app.js">
  20889. * angular.module('controllerExample', [])
  20890. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20891. *
  20892. * function SettingsController2($scope) {
  20893. * $scope.name = "John Smith";
  20894. * $scope.contacts = [
  20895. * {type:'phone', value:'408 555 1212'},
  20896. * {type:'email', value:'john.smith@example.org'} ];
  20897. *
  20898. * $scope.greet = function() {
  20899. * alert($scope.name);
  20900. * };
  20901. *
  20902. * $scope.addContact = function() {
  20903. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20904. * };
  20905. *
  20906. * $scope.removeContact = function(contactToRemove) {
  20907. * var index = $scope.contacts.indexOf(contactToRemove);
  20908. * $scope.contacts.splice(index, 1);
  20909. * };
  20910. *
  20911. * $scope.clearContact = function(contact) {
  20912. * contact.type = 'phone';
  20913. * contact.value = '';
  20914. * };
  20915. * }
  20916. * </file>
  20917. * <file name="protractor.js" type="protractor">
  20918. * it('should check controller', function() {
  20919. * var container = element(by.id('ctrl-exmpl'));
  20920. *
  20921. * expect(container.element(by.model('name'))
  20922. * .getAttribute('value')).toBe('John Smith');
  20923. *
  20924. * var firstRepeat =
  20925. * container.element(by.repeater('contact in contacts').row(0));
  20926. * var secondRepeat =
  20927. * container.element(by.repeater('contact in contacts').row(1));
  20928. *
  20929. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20930. * .toBe('408 555 1212');
  20931. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20932. * .toBe('john.smith@example.org');
  20933. *
  20934. * firstRepeat.element(by.buttonText('clear')).click();
  20935. *
  20936. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20937. * .toBe('');
  20938. *
  20939. * container.element(by.buttonText('add')).click();
  20940. *
  20941. * expect(container.element(by.repeater('contact in contacts').row(2))
  20942. * .element(by.model('contact.value'))
  20943. * .getAttribute('value'))
  20944. * .toBe('yourname@example.org');
  20945. * });
  20946. * </file>
  20947. *</example>
  20948. */
  20949. var ngControllerDirective = [function() {
  20950. return {
  20951. restrict: 'A',
  20952. scope: true,
  20953. controller: '@',
  20954. priority: 500
  20955. };
  20956. }];
  20957. /**
  20958. * @ngdoc directive
  20959. * @name ngCsp
  20960. *
  20961. * @element html
  20962. * @description
  20963. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20964. *
  20965. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20966. *
  20967. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20968. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20969. *
  20970. * - don't use `Function` constructor to generate optimized value getters
  20971. * - don't inject custom stylesheet into the document
  20972. *
  20973. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20974. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20975. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20976. * be raised.
  20977. *
  20978. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20979. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20980. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20981. *
  20982. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20983. * autodetection however triggers a CSP error to be logged in the console:
  20984. *
  20985. * ```
  20986. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20987. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20988. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20989. * ```
  20990. *
  20991. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20992. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20993. * appears first in the html document.
  20994. *
  20995. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20996. *
  20997. * @example
  20998. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20999. ```html
  21000. <!doctype html>
  21001. <html ng-app ng-csp>
  21002. ...
  21003. ...
  21004. </html>
  21005. ```
  21006. * @example
  21007. // Note: the suffix `.csp` in the example name triggers
  21008. // csp mode in our http server!
  21009. <example name="example.csp" module="cspExample" ng-csp="true">
  21010. <file name="index.html">
  21011. <div ng-controller="MainController as ctrl">
  21012. <div>
  21013. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21014. <span id="counter">
  21015. {{ctrl.counter}}
  21016. </span>
  21017. </div>
  21018. <div>
  21019. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21020. <span id="evilError">
  21021. {{ctrl.evilError}}
  21022. </span>
  21023. </div>
  21024. </div>
  21025. </file>
  21026. <file name="script.js">
  21027. angular.module('cspExample', [])
  21028. .controller('MainController', function() {
  21029. this.counter = 0;
  21030. this.inc = function() {
  21031. this.counter++;
  21032. };
  21033. this.evil = function() {
  21034. // jshint evil:true
  21035. try {
  21036. eval('1+2');
  21037. } catch (e) {
  21038. this.evilError = e.message;
  21039. }
  21040. };
  21041. });
  21042. </file>
  21043. <file name="protractor.js" type="protractor">
  21044. var util, webdriver;
  21045. var incBtn = element(by.id('inc'));
  21046. var counter = element(by.id('counter'));
  21047. var evilBtn = element(by.id('evil'));
  21048. var evilError = element(by.id('evilError'));
  21049. function getAndClearSevereErrors() {
  21050. return browser.manage().logs().get('browser').then(function(browserLog) {
  21051. return browserLog.filter(function(logEntry) {
  21052. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21053. });
  21054. });
  21055. }
  21056. function clearErrors() {
  21057. getAndClearSevereErrors();
  21058. }
  21059. function expectNoErrors() {
  21060. getAndClearSevereErrors().then(function(filteredLog) {
  21061. expect(filteredLog.length).toEqual(0);
  21062. if (filteredLog.length) {
  21063. console.log('browser console errors: ' + util.inspect(filteredLog));
  21064. }
  21065. });
  21066. }
  21067. function expectError(regex) {
  21068. getAndClearSevereErrors().then(function(filteredLog) {
  21069. var found = false;
  21070. filteredLog.forEach(function(log) {
  21071. if (log.message.match(regex)) {
  21072. found = true;
  21073. }
  21074. });
  21075. if (!found) {
  21076. throw new Error('expected an error that matches ' + regex);
  21077. }
  21078. });
  21079. }
  21080. beforeEach(function() {
  21081. util = require('util');
  21082. webdriver = require('protractor/node_modules/selenium-webdriver');
  21083. });
  21084. // For now, we only test on Chrome,
  21085. // as Safari does not load the page with Protractor's injected scripts,
  21086. // and Firefox webdriver always disables content security policy (#6358)
  21087. if (browser.params.browser !== 'chrome') {
  21088. return;
  21089. }
  21090. it('should not report errors when the page is loaded', function() {
  21091. // clear errors so we are not dependent on previous tests
  21092. clearErrors();
  21093. // Need to reload the page as the page is already loaded when
  21094. // we come here
  21095. browser.driver.getCurrentUrl().then(function(url) {
  21096. browser.get(url);
  21097. });
  21098. expectNoErrors();
  21099. });
  21100. it('should evaluate expressions', function() {
  21101. expect(counter.getText()).toEqual('0');
  21102. incBtn.click();
  21103. expect(counter.getText()).toEqual('1');
  21104. expectNoErrors();
  21105. });
  21106. it('should throw and report an error when using "eval"', function() {
  21107. evilBtn.click();
  21108. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21109. expectError(/Content Security Policy/);
  21110. });
  21111. </file>
  21112. </example>
  21113. */
  21114. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21115. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21116. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  21117. /**
  21118. * @ngdoc directive
  21119. * @name ngClick
  21120. *
  21121. * @description
  21122. * The ngClick directive allows you to specify custom behavior when
  21123. * an element is clicked.
  21124. *
  21125. * @element ANY
  21126. * @priority 0
  21127. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21128. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21129. *
  21130. * @example
  21131. <example>
  21132. <file name="index.html">
  21133. <button ng-click="count = count + 1" ng-init="count=0">
  21134. Increment
  21135. </button>
  21136. <span>
  21137. count: {{count}}
  21138. </span>
  21139. </file>
  21140. <file name="protractor.js" type="protractor">
  21141. it('should check ng-click', function() {
  21142. expect(element(by.binding('count')).getText()).toMatch('0');
  21143. element(by.css('button')).click();
  21144. expect(element(by.binding('count')).getText()).toMatch('1');
  21145. });
  21146. </file>
  21147. </example>
  21148. */
  21149. /*
  21150. * A collection of directives that allows creation of custom event handlers that are defined as
  21151. * angular expressions and are compiled and executed within the current scope.
  21152. */
  21153. var ngEventDirectives = {};
  21154. // For events that might fire synchronously during DOM manipulation
  21155. // we need to execute their event handlers asynchronously using $evalAsync,
  21156. // so that they are not executed in an inconsistent state.
  21157. var forceAsyncEvents = {
  21158. 'blur': true,
  21159. 'focus': true
  21160. };
  21161. forEach(
  21162. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21163. function(eventName) {
  21164. var directiveName = directiveNormalize('ng-' + eventName);
  21165. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21166. return {
  21167. restrict: 'A',
  21168. compile: function($element, attr) {
  21169. // We expose the powerful $event object on the scope that provides access to the Window,
  21170. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21171. // checks at the cost of speed since event handler expressions are not executed as
  21172. // frequently as regular change detection.
  21173. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21174. return function ngEventHandler(scope, element) {
  21175. element.on(eventName, function(event) {
  21176. var callback = function() {
  21177. fn(scope, {$event:event});
  21178. };
  21179. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21180. scope.$evalAsync(callback);
  21181. } else {
  21182. scope.$apply(callback);
  21183. }
  21184. });
  21185. };
  21186. }
  21187. };
  21188. }];
  21189. }
  21190. );
  21191. /**
  21192. * @ngdoc directive
  21193. * @name ngDblclick
  21194. *
  21195. * @description
  21196. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21197. *
  21198. * @element ANY
  21199. * @priority 0
  21200. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21201. * a dblclick. (The Event object is available as `$event`)
  21202. *
  21203. * @example
  21204. <example>
  21205. <file name="index.html">
  21206. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21207. Increment (on double click)
  21208. </button>
  21209. count: {{count}}
  21210. </file>
  21211. </example>
  21212. */
  21213. /**
  21214. * @ngdoc directive
  21215. * @name ngMousedown
  21216. *
  21217. * @description
  21218. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21219. *
  21220. * @element ANY
  21221. * @priority 0
  21222. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21223. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21224. *
  21225. * @example
  21226. <example>
  21227. <file name="index.html">
  21228. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21229. Increment (on mouse down)
  21230. </button>
  21231. count: {{count}}
  21232. </file>
  21233. </example>
  21234. */
  21235. /**
  21236. * @ngdoc directive
  21237. * @name ngMouseup
  21238. *
  21239. * @description
  21240. * Specify custom behavior on mouseup event.
  21241. *
  21242. * @element ANY
  21243. * @priority 0
  21244. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21245. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21246. *
  21247. * @example
  21248. <example>
  21249. <file name="index.html">
  21250. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21251. Increment (on mouse up)
  21252. </button>
  21253. count: {{count}}
  21254. </file>
  21255. </example>
  21256. */
  21257. /**
  21258. * @ngdoc directive
  21259. * @name ngMouseover
  21260. *
  21261. * @description
  21262. * Specify custom behavior on mouseover event.
  21263. *
  21264. * @element ANY
  21265. * @priority 0
  21266. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21267. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21268. *
  21269. * @example
  21270. <example>
  21271. <file name="index.html">
  21272. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21273. Increment (when mouse is over)
  21274. </button>
  21275. count: {{count}}
  21276. </file>
  21277. </example>
  21278. */
  21279. /**
  21280. * @ngdoc directive
  21281. * @name ngMouseenter
  21282. *
  21283. * @description
  21284. * Specify custom behavior on mouseenter event.
  21285. *
  21286. * @element ANY
  21287. * @priority 0
  21288. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21289. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21290. *
  21291. * @example
  21292. <example>
  21293. <file name="index.html">
  21294. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21295. Increment (when mouse enters)
  21296. </button>
  21297. count: {{count}}
  21298. </file>
  21299. </example>
  21300. */
  21301. /**
  21302. * @ngdoc directive
  21303. * @name ngMouseleave
  21304. *
  21305. * @description
  21306. * Specify custom behavior on mouseleave event.
  21307. *
  21308. * @element ANY
  21309. * @priority 0
  21310. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21311. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21312. *
  21313. * @example
  21314. <example>
  21315. <file name="index.html">
  21316. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21317. Increment (when mouse leaves)
  21318. </button>
  21319. count: {{count}}
  21320. </file>
  21321. </example>
  21322. */
  21323. /**
  21324. * @ngdoc directive
  21325. * @name ngMousemove
  21326. *
  21327. * @description
  21328. * Specify custom behavior on mousemove event.
  21329. *
  21330. * @element ANY
  21331. * @priority 0
  21332. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21333. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21334. *
  21335. * @example
  21336. <example>
  21337. <file name="index.html">
  21338. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21339. Increment (when mouse moves)
  21340. </button>
  21341. count: {{count}}
  21342. </file>
  21343. </example>
  21344. */
  21345. /**
  21346. * @ngdoc directive
  21347. * @name ngKeydown
  21348. *
  21349. * @description
  21350. * Specify custom behavior on keydown event.
  21351. *
  21352. * @element ANY
  21353. * @priority 0
  21354. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21355. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21356. *
  21357. * @example
  21358. <example>
  21359. <file name="index.html">
  21360. <input ng-keydown="count = count + 1" ng-init="count=0">
  21361. key down count: {{count}}
  21362. </file>
  21363. </example>
  21364. */
  21365. /**
  21366. * @ngdoc directive
  21367. * @name ngKeyup
  21368. *
  21369. * @description
  21370. * Specify custom behavior on keyup event.
  21371. *
  21372. * @element ANY
  21373. * @priority 0
  21374. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21375. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21376. *
  21377. * @example
  21378. <example>
  21379. <file name="index.html">
  21380. <p>Typing in the input box below updates the key count</p>
  21381. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21382. <p>Typing in the input box below updates the keycode</p>
  21383. <input ng-keyup="event=$event">
  21384. <p>event keyCode: {{ event.keyCode }}</p>
  21385. <p>event altKey: {{ event.altKey }}</p>
  21386. </file>
  21387. </example>
  21388. */
  21389. /**
  21390. * @ngdoc directive
  21391. * @name ngKeypress
  21392. *
  21393. * @description
  21394. * Specify custom behavior on keypress event.
  21395. *
  21396. * @element ANY
  21397. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21398. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21399. * and can be interrogated for keyCode, altKey, etc.)
  21400. *
  21401. * @example
  21402. <example>
  21403. <file name="index.html">
  21404. <input ng-keypress="count = count + 1" ng-init="count=0">
  21405. key press count: {{count}}
  21406. </file>
  21407. </example>
  21408. */
  21409. /**
  21410. * @ngdoc directive
  21411. * @name ngSubmit
  21412. *
  21413. * @description
  21414. * Enables binding angular expressions to onsubmit events.
  21415. *
  21416. * Additionally it prevents the default action (which for form means sending the request to the
  21417. * server and reloading the current page), but only if the form does not contain `action`,
  21418. * `data-action`, or `x-action` attributes.
  21419. *
  21420. * <div class="alert alert-warning">
  21421. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21422. * `ngSubmit` handlers together. See the
  21423. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21424. * for a detailed discussion of when `ngSubmit` may be triggered.
  21425. * </div>
  21426. *
  21427. * @element form
  21428. * @priority 0
  21429. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21430. * ({@link guide/expression#-event- Event object is available as `$event`})
  21431. *
  21432. * @example
  21433. <example module="submitExample">
  21434. <file name="index.html">
  21435. <script>
  21436. angular.module('submitExample', [])
  21437. .controller('ExampleController', ['$scope', function($scope) {
  21438. $scope.list = [];
  21439. $scope.text = 'hello';
  21440. $scope.submit = function() {
  21441. if ($scope.text) {
  21442. $scope.list.push(this.text);
  21443. $scope.text = '';
  21444. }
  21445. };
  21446. }]);
  21447. </script>
  21448. <form ng-submit="submit()" ng-controller="ExampleController">
  21449. Enter text and hit enter:
  21450. <input type="text" ng-model="text" name="text" />
  21451. <input type="submit" id="submit" value="Submit" />
  21452. <pre>list={{list}}</pre>
  21453. </form>
  21454. </file>
  21455. <file name="protractor.js" type="protractor">
  21456. it('should check ng-submit', function() {
  21457. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21458. element(by.css('#submit')).click();
  21459. expect(element(by.binding('list')).getText()).toContain('hello');
  21460. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21461. });
  21462. it('should ignore empty strings', function() {
  21463. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21464. element(by.css('#submit')).click();
  21465. element(by.css('#submit')).click();
  21466. expect(element(by.binding('list')).getText()).toContain('hello');
  21467. });
  21468. </file>
  21469. </example>
  21470. */
  21471. /**
  21472. * @ngdoc directive
  21473. * @name ngFocus
  21474. *
  21475. * @description
  21476. * Specify custom behavior on focus event.
  21477. *
  21478. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21479. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21480. * during an `$apply` to ensure a consistent state.
  21481. *
  21482. * @element window, input, select, textarea, a
  21483. * @priority 0
  21484. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21485. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21486. *
  21487. * @example
  21488. * See {@link ng.directive:ngClick ngClick}
  21489. */
  21490. /**
  21491. * @ngdoc directive
  21492. * @name ngBlur
  21493. *
  21494. * @description
  21495. * Specify custom behavior on blur event.
  21496. *
  21497. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21498. * an element has lost focus.
  21499. *
  21500. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21501. * (e.g. removing a focussed input),
  21502. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21503. * during an `$apply` to ensure a consistent state.
  21504. *
  21505. * @element window, input, select, textarea, a
  21506. * @priority 0
  21507. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21508. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21509. *
  21510. * @example
  21511. * See {@link ng.directive:ngClick ngClick}
  21512. */
  21513. /**
  21514. * @ngdoc directive
  21515. * @name ngCopy
  21516. *
  21517. * @description
  21518. * Specify custom behavior on copy event.
  21519. *
  21520. * @element window, input, select, textarea, a
  21521. * @priority 0
  21522. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21523. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21524. *
  21525. * @example
  21526. <example>
  21527. <file name="index.html">
  21528. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21529. copied: {{copied}}
  21530. </file>
  21531. </example>
  21532. */
  21533. /**
  21534. * @ngdoc directive
  21535. * @name ngCut
  21536. *
  21537. * @description
  21538. * Specify custom behavior on cut event.
  21539. *
  21540. * @element window, input, select, textarea, a
  21541. * @priority 0
  21542. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21543. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21544. *
  21545. * @example
  21546. <example>
  21547. <file name="index.html">
  21548. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21549. cut: {{cut}}
  21550. </file>
  21551. </example>
  21552. */
  21553. /**
  21554. * @ngdoc directive
  21555. * @name ngPaste
  21556. *
  21557. * @description
  21558. * Specify custom behavior on paste event.
  21559. *
  21560. * @element window, input, select, textarea, a
  21561. * @priority 0
  21562. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21563. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21564. *
  21565. * @example
  21566. <example>
  21567. <file name="index.html">
  21568. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21569. pasted: {{paste}}
  21570. </file>
  21571. </example>
  21572. */
  21573. /**
  21574. * @ngdoc directive
  21575. * @name ngIf
  21576. * @restrict A
  21577. *
  21578. * @description
  21579. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21580. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21581. * value then the element is removed from the DOM, otherwise a clone of the
  21582. * element is reinserted into the DOM.
  21583. *
  21584. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21585. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21586. * case when this difference is significant is when using css selectors that rely on an element's
  21587. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21588. *
  21589. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21590. * is created when the element is restored. The scope created within `ngIf` inherits from
  21591. * its parent scope using
  21592. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21593. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21594. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21595. * variable within the child scope will override (hide) the value in the parent scope.
  21596. *
  21597. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21598. * is if an element's class attribute is directly modified after it's compiled, using something like
  21599. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21600. * the added class will be lost because the original compiled state is used to regenerate the element.
  21601. *
  21602. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21603. * and `leave` effects.
  21604. *
  21605. * @animations
  21606. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21607. * leave - happens just before the `ngIf` contents are removed from the DOM
  21608. *
  21609. * @element ANY
  21610. * @scope
  21611. * @priority 600
  21612. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21613. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21614. * element is added to the DOM tree.
  21615. *
  21616. * @example
  21617. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21618. <file name="index.html">
  21619. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21620. Show when checked:
  21621. <span ng-if="checked" class="animate-if">
  21622. This is removed when the checkbox is unchecked.
  21623. </span>
  21624. </file>
  21625. <file name="animations.css">
  21626. .animate-if {
  21627. background:white;
  21628. border:1px solid black;
  21629. padding:10px;
  21630. }
  21631. .animate-if.ng-enter, .animate-if.ng-leave {
  21632. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21633. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21634. }
  21635. .animate-if.ng-enter,
  21636. .animate-if.ng-leave.ng-leave-active {
  21637. opacity:0;
  21638. }
  21639. .animate-if.ng-leave,
  21640. .animate-if.ng-enter.ng-enter-active {
  21641. opacity:1;
  21642. }
  21643. </file>
  21644. </example>
  21645. */
  21646. var ngIfDirective = ['$animate', function($animate) {
  21647. return {
  21648. multiElement: true,
  21649. transclude: 'element',
  21650. priority: 600,
  21651. terminal: true,
  21652. restrict: 'A',
  21653. $$tlb: true,
  21654. link: function($scope, $element, $attr, ctrl, $transclude) {
  21655. var block, childScope, previousElements;
  21656. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21657. if (value) {
  21658. if (!childScope) {
  21659. $transclude(function(clone, newScope) {
  21660. childScope = newScope;
  21661. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21662. // Note: We only need the first/last node of the cloned nodes.
  21663. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21664. // by a directive with templateUrl when its template arrives.
  21665. block = {
  21666. clone: clone
  21667. };
  21668. $animate.enter(clone, $element.parent(), $element);
  21669. });
  21670. }
  21671. } else {
  21672. if (previousElements) {
  21673. previousElements.remove();
  21674. previousElements = null;
  21675. }
  21676. if (childScope) {
  21677. childScope.$destroy();
  21678. childScope = null;
  21679. }
  21680. if (block) {
  21681. previousElements = getBlockNodes(block.clone);
  21682. $animate.leave(previousElements).then(function() {
  21683. previousElements = null;
  21684. });
  21685. block = null;
  21686. }
  21687. }
  21688. });
  21689. }
  21690. };
  21691. }];
  21692. /**
  21693. * @ngdoc directive
  21694. * @name ngInclude
  21695. * @restrict ECA
  21696. *
  21697. * @description
  21698. * Fetches, compiles and includes an external HTML fragment.
  21699. *
  21700. * By default, the template URL is restricted to the same domain and protocol as the
  21701. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21702. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21703. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21704. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21705. * ng.$sce Strict Contextual Escaping}.
  21706. *
  21707. * In addition, the browser's
  21708. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21709. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21710. * policy may further restrict whether the template is successfully loaded.
  21711. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21712. * access on some browsers.
  21713. *
  21714. * @animations
  21715. * enter - animation is used to bring new content into the browser.
  21716. * leave - animation is used to animate existing content away.
  21717. *
  21718. * The enter and leave animation occur concurrently.
  21719. *
  21720. * @scope
  21721. * @priority 400
  21722. *
  21723. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21724. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21725. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21726. *
  21727. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21728. * $anchorScroll} to scroll the viewport after the content is loaded.
  21729. *
  21730. * - If the attribute is not set, disable scrolling.
  21731. * - If the attribute is set without value, enable scrolling.
  21732. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21733. *
  21734. * @example
  21735. <example module="includeExample" deps="angular-animate.js" animations="true">
  21736. <file name="index.html">
  21737. <div ng-controller="ExampleController">
  21738. <select ng-model="template" ng-options="t.name for t in templates">
  21739. <option value="">(blank)</option>
  21740. </select>
  21741. url of the template: <code>{{template.url}}</code>
  21742. <hr/>
  21743. <div class="slide-animate-container">
  21744. <div class="slide-animate" ng-include="template.url"></div>
  21745. </div>
  21746. </div>
  21747. </file>
  21748. <file name="script.js">
  21749. angular.module('includeExample', ['ngAnimate'])
  21750. .controller('ExampleController', ['$scope', function($scope) {
  21751. $scope.templates =
  21752. [ { name: 'template1.html', url: 'template1.html'},
  21753. { name: 'template2.html', url: 'template2.html'} ];
  21754. $scope.template = $scope.templates[0];
  21755. }]);
  21756. </file>
  21757. <file name="template1.html">
  21758. Content of template1.html
  21759. </file>
  21760. <file name="template2.html">
  21761. Content of template2.html
  21762. </file>
  21763. <file name="animations.css">
  21764. .slide-animate-container {
  21765. position:relative;
  21766. background:white;
  21767. border:1px solid black;
  21768. height:40px;
  21769. overflow:hidden;
  21770. }
  21771. .slide-animate {
  21772. padding:10px;
  21773. }
  21774. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21775. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21776. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21777. position:absolute;
  21778. top:0;
  21779. left:0;
  21780. right:0;
  21781. bottom:0;
  21782. display:block;
  21783. padding:10px;
  21784. }
  21785. .slide-animate.ng-enter {
  21786. top:-50px;
  21787. }
  21788. .slide-animate.ng-enter.ng-enter-active {
  21789. top:0;
  21790. }
  21791. .slide-animate.ng-leave {
  21792. top:0;
  21793. }
  21794. .slide-animate.ng-leave.ng-leave-active {
  21795. top:50px;
  21796. }
  21797. </file>
  21798. <file name="protractor.js" type="protractor">
  21799. var templateSelect = element(by.model('template'));
  21800. var includeElem = element(by.css('[ng-include]'));
  21801. it('should load template1.html', function() {
  21802. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21803. });
  21804. it('should load template2.html', function() {
  21805. if (browser.params.browser == 'firefox') {
  21806. // Firefox can't handle using selects
  21807. // See https://github.com/angular/protractor/issues/480
  21808. return;
  21809. }
  21810. templateSelect.click();
  21811. templateSelect.all(by.css('option')).get(2).click();
  21812. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21813. });
  21814. it('should change to blank', function() {
  21815. if (browser.params.browser == 'firefox') {
  21816. // Firefox can't handle using selects
  21817. return;
  21818. }
  21819. templateSelect.click();
  21820. templateSelect.all(by.css('option')).get(0).click();
  21821. expect(includeElem.isPresent()).toBe(false);
  21822. });
  21823. </file>
  21824. </example>
  21825. */
  21826. /**
  21827. * @ngdoc event
  21828. * @name ngInclude#$includeContentRequested
  21829. * @eventType emit on the scope ngInclude was declared in
  21830. * @description
  21831. * Emitted every time the ngInclude content is requested.
  21832. *
  21833. * @param {Object} angularEvent Synthetic event object.
  21834. * @param {String} src URL of content to load.
  21835. */
  21836. /**
  21837. * @ngdoc event
  21838. * @name ngInclude#$includeContentLoaded
  21839. * @eventType emit on the current ngInclude scope
  21840. * @description
  21841. * Emitted every time the ngInclude content is reloaded.
  21842. *
  21843. * @param {Object} angularEvent Synthetic event object.
  21844. * @param {String} src URL of content to load.
  21845. */
  21846. /**
  21847. * @ngdoc event
  21848. * @name ngInclude#$includeContentError
  21849. * @eventType emit on the scope ngInclude was declared in
  21850. * @description
  21851. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  21852. *
  21853. * @param {Object} angularEvent Synthetic event object.
  21854. * @param {String} src URL of content to load.
  21855. */
  21856. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21857. function($templateRequest, $anchorScroll, $animate, $sce) {
  21858. return {
  21859. restrict: 'ECA',
  21860. priority: 400,
  21861. terminal: true,
  21862. transclude: 'element',
  21863. controller: angular.noop,
  21864. compile: function(element, attr) {
  21865. var srcExp = attr.ngInclude || attr.src,
  21866. onloadExp = attr.onload || '',
  21867. autoScrollExp = attr.autoscroll;
  21868. return function(scope, $element, $attr, ctrl, $transclude) {
  21869. var changeCounter = 0,
  21870. currentScope,
  21871. previousElement,
  21872. currentElement;
  21873. var cleanupLastIncludeContent = function() {
  21874. if (previousElement) {
  21875. previousElement.remove();
  21876. previousElement = null;
  21877. }
  21878. if (currentScope) {
  21879. currentScope.$destroy();
  21880. currentScope = null;
  21881. }
  21882. if (currentElement) {
  21883. $animate.leave(currentElement).then(function() {
  21884. previousElement = null;
  21885. });
  21886. previousElement = currentElement;
  21887. currentElement = null;
  21888. }
  21889. };
  21890. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21891. var afterAnimation = function() {
  21892. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21893. $anchorScroll();
  21894. }
  21895. };
  21896. var thisChangeId = ++changeCounter;
  21897. if (src) {
  21898. //set the 2nd param to true to ignore the template request error so that the inner
  21899. //contents and scope can be cleaned up.
  21900. $templateRequest(src, true).then(function(response) {
  21901. if (thisChangeId !== changeCounter) return;
  21902. var newScope = scope.$new();
  21903. ctrl.template = response;
  21904. // Note: This will also link all children of ng-include that were contained in the original
  21905. // html. If that content contains controllers, ... they could pollute/change the scope.
  21906. // However, using ng-include on an element with additional content does not make sense...
  21907. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21908. // function is called before linking the content, which would apply child
  21909. // directives to non existing elements.
  21910. var clone = $transclude(newScope, function(clone) {
  21911. cleanupLastIncludeContent();
  21912. $animate.enter(clone, null, $element).then(afterAnimation);
  21913. });
  21914. currentScope = newScope;
  21915. currentElement = clone;
  21916. currentScope.$emit('$includeContentLoaded', src);
  21917. scope.$eval(onloadExp);
  21918. }, function() {
  21919. if (thisChangeId === changeCounter) {
  21920. cleanupLastIncludeContent();
  21921. scope.$emit('$includeContentError', src);
  21922. }
  21923. });
  21924. scope.$emit('$includeContentRequested', src);
  21925. } else {
  21926. cleanupLastIncludeContent();
  21927. ctrl.template = null;
  21928. }
  21929. });
  21930. };
  21931. }
  21932. };
  21933. }];
  21934. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21935. // It will replace and compile the content of the element with the loaded template.
  21936. // We need this directive so that the element content is already filled when
  21937. // the link function of another directive on the same element as ngInclude
  21938. // is called.
  21939. var ngIncludeFillContentDirective = ['$compile',
  21940. function($compile) {
  21941. return {
  21942. restrict: 'ECA',
  21943. priority: -400,
  21944. require: 'ngInclude',
  21945. link: function(scope, $element, $attr, ctrl) {
  21946. if (/SVG/.test($element[0].toString())) {
  21947. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21948. // support innerHTML, so detect this here and try to generate the contents
  21949. // specially.
  21950. $element.empty();
  21951. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21952. function namespaceAdaptedClone(clone) {
  21953. $element.append(clone);
  21954. }, {futureParentElement: $element});
  21955. return;
  21956. }
  21957. $element.html(ctrl.template);
  21958. $compile($element.contents())(scope);
  21959. }
  21960. };
  21961. }];
  21962. /**
  21963. * @ngdoc directive
  21964. * @name ngInit
  21965. * @restrict AC
  21966. *
  21967. * @description
  21968. * The `ngInit` directive allows you to evaluate an expression in the
  21969. * current scope.
  21970. *
  21971. * <div class="alert alert-danger">
  21972. * The only appropriate use of `ngInit` is for aliasing special properties of
  21973. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21974. * should use {@link guide/controller controllers} rather than `ngInit`
  21975. * to initialize values on a scope.
  21976. * </div>
  21977. * <div class="alert alert-warning">
  21978. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21979. * sure you have parenthesis for correct precedence:
  21980. * <pre class="prettyprint">
  21981. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  21982. * </pre>
  21983. * </div>
  21984. *
  21985. * @priority 450
  21986. *
  21987. * @element ANY
  21988. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21989. *
  21990. * @example
  21991. <example module="initExample">
  21992. <file name="index.html">
  21993. <script>
  21994. angular.module('initExample', [])
  21995. .controller('ExampleController', ['$scope', function($scope) {
  21996. $scope.list = [['a', 'b'], ['c', 'd']];
  21997. }]);
  21998. </script>
  21999. <div ng-controller="ExampleController">
  22000. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22001. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22002. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22003. </div>
  22004. </div>
  22005. </div>
  22006. </file>
  22007. <file name="protractor.js" type="protractor">
  22008. it('should alias index positions', function() {
  22009. var elements = element.all(by.css('.example-init'));
  22010. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22011. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22012. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22013. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22014. });
  22015. </file>
  22016. </example>
  22017. */
  22018. var ngInitDirective = ngDirective({
  22019. priority: 450,
  22020. compile: function() {
  22021. return {
  22022. pre: function(scope, element, attrs) {
  22023. scope.$eval(attrs.ngInit);
  22024. }
  22025. };
  22026. }
  22027. });
  22028. /**
  22029. * @ngdoc directive
  22030. * @name ngList
  22031. *
  22032. * @description
  22033. * Text input that converts between a delimited string and an array of strings. The default
  22034. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22035. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22036. *
  22037. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22038. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22039. * list item is respected. This implies that the user of the directive is responsible for
  22040. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22041. * tab or newline character.
  22042. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22043. * when joining the list items back together) and whitespace around each list item is stripped
  22044. * before it is added to the model.
  22045. *
  22046. * ### Example with Validation
  22047. *
  22048. * <example name="ngList-directive" module="listExample">
  22049. * <file name="app.js">
  22050. * angular.module('listExample', [])
  22051. * .controller('ExampleController', ['$scope', function($scope) {
  22052. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22053. * }]);
  22054. * </file>
  22055. * <file name="index.html">
  22056. * <form name="myForm" ng-controller="ExampleController">
  22057. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22058. * <span role="alert">
  22059. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22060. * Required!</span>
  22061. * </span>
  22062. * <br>
  22063. * <tt>names = {{names}}</tt><br/>
  22064. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22065. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22066. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22067. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22068. * </form>
  22069. * </file>
  22070. * <file name="protractor.js" type="protractor">
  22071. * var listInput = element(by.model('names'));
  22072. * var names = element(by.exactBinding('names'));
  22073. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22074. * var error = element(by.css('span.error'));
  22075. *
  22076. * it('should initialize to model', function() {
  22077. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22078. * expect(valid.getText()).toContain('true');
  22079. * expect(error.getCssValue('display')).toBe('none');
  22080. * });
  22081. *
  22082. * it('should be invalid if empty', function() {
  22083. * listInput.clear();
  22084. * listInput.sendKeys('');
  22085. *
  22086. * expect(names.getText()).toContain('');
  22087. * expect(valid.getText()).toContain('false');
  22088. * expect(error.getCssValue('display')).not.toBe('none');
  22089. * });
  22090. * </file>
  22091. * </example>
  22092. *
  22093. * ### Example - splitting on whitespace
  22094. * <example name="ngList-directive-newlines">
  22095. * <file name="index.html">
  22096. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22097. * <pre>{{ list | json }}</pre>
  22098. * </file>
  22099. * <file name="protractor.js" type="protractor">
  22100. * it("should split the text by newlines", function() {
  22101. * var listInput = element(by.model('list'));
  22102. * var output = element(by.binding('list | json'));
  22103. * listInput.sendKeys('abc\ndef\nghi');
  22104. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22105. * });
  22106. * </file>
  22107. * </example>
  22108. *
  22109. * @element input
  22110. * @param {string=} ngList optional delimiter that should be used to split the value.
  22111. */
  22112. var ngListDirective = function() {
  22113. return {
  22114. restrict: 'A',
  22115. priority: 100,
  22116. require: 'ngModel',
  22117. link: function(scope, element, attr, ctrl) {
  22118. // We want to control whitespace trimming so we use this convoluted approach
  22119. // to access the ngList attribute, which doesn't pre-trim the attribute
  22120. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22121. var trimValues = attr.ngTrim !== 'false';
  22122. var separator = trimValues ? trim(ngList) : ngList;
  22123. var parse = function(viewValue) {
  22124. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22125. if (isUndefined(viewValue)) return;
  22126. var list = [];
  22127. if (viewValue) {
  22128. forEach(viewValue.split(separator), function(value) {
  22129. if (value) list.push(trimValues ? trim(value) : value);
  22130. });
  22131. }
  22132. return list;
  22133. };
  22134. ctrl.$parsers.push(parse);
  22135. ctrl.$formatters.push(function(value) {
  22136. if (isArray(value)) {
  22137. return value.join(ngList);
  22138. }
  22139. return undefined;
  22140. });
  22141. // Override the standard $isEmpty because an empty array means the input is empty.
  22142. ctrl.$isEmpty = function(value) {
  22143. return !value || !value.length;
  22144. };
  22145. }
  22146. };
  22147. };
  22148. /* global VALID_CLASS: true,
  22149. INVALID_CLASS: true,
  22150. PRISTINE_CLASS: true,
  22151. DIRTY_CLASS: true,
  22152. UNTOUCHED_CLASS: true,
  22153. TOUCHED_CLASS: true,
  22154. */
  22155. var VALID_CLASS = 'ng-valid',
  22156. INVALID_CLASS = 'ng-invalid',
  22157. PRISTINE_CLASS = 'ng-pristine',
  22158. DIRTY_CLASS = 'ng-dirty',
  22159. UNTOUCHED_CLASS = 'ng-untouched',
  22160. TOUCHED_CLASS = 'ng-touched',
  22161. PENDING_CLASS = 'ng-pending';
  22162. var $ngModelMinErr = new minErr('ngModel');
  22163. /**
  22164. * @ngdoc type
  22165. * @name ngModel.NgModelController
  22166. *
  22167. * @property {string} $viewValue Actual string value in the view.
  22168. * @property {*} $modelValue The value in the model that the control is bound to.
  22169. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22170. the control reads value from the DOM. The functions are called in array order, each passing
  22171. its return value through to the next. The last return value is forwarded to the
  22172. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22173. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22174. `$viewValue`}.
  22175. Returning `undefined` from a parser means a parse error occurred. In that case,
  22176. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22177. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22178. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22179. *
  22180. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22181. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22182. next. The last return value is used as the actual DOM value.
  22183. Used to format / convert values for display in the control.
  22184. * ```js
  22185. * function formatter(value) {
  22186. * if (value) {
  22187. * return value.toUpperCase();
  22188. * }
  22189. * }
  22190. * ngModel.$formatters.push(formatter);
  22191. * ```
  22192. *
  22193. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22194. * whenever the model value changes. The key value within the object refers to the name of the
  22195. * validator while the function refers to the validation operation. The validation operation is
  22196. * provided with the model value as an argument and must return a true or false value depending
  22197. * on the response of that validation.
  22198. *
  22199. * ```js
  22200. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22201. * var value = modelValue || viewValue;
  22202. * return /[0-9]+/.test(value) &&
  22203. * /[a-z]+/.test(value) &&
  22204. * /[A-Z]+/.test(value) &&
  22205. * /\W+/.test(value);
  22206. * };
  22207. * ```
  22208. *
  22209. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22210. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22211. * is expected to return a promise when it is run during the model validation process. Once the promise
  22212. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22213. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22214. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22215. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22216. * will only run once all synchronous validators have passed.
  22217. *
  22218. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22219. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22220. *
  22221. * ```js
  22222. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22223. * var value = modelValue || viewValue;
  22224. *
  22225. * // Lookup user by username
  22226. * return $http.get('/api/users/' + value).
  22227. * then(function resolved() {
  22228. * //username exists, this means validation fails
  22229. * return $q.reject('exists');
  22230. * }, function rejected() {
  22231. * //username does not exist, therefore this validation passes
  22232. * return true;
  22233. * });
  22234. * };
  22235. * ```
  22236. *
  22237. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22238. * view value has changed. It is called with no arguments, and its return value is ignored.
  22239. * This can be used in place of additional $watches against the model value.
  22240. *
  22241. * @property {Object} $error An object hash with all failing validator ids as keys.
  22242. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22243. *
  22244. * @property {boolean} $untouched True if control has not lost focus yet.
  22245. * @property {boolean} $touched True if control has lost focus.
  22246. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22247. * @property {boolean} $dirty True if user has already interacted with the control.
  22248. * @property {boolean} $valid True if there is no error.
  22249. * @property {boolean} $invalid True if at least one error on the control.
  22250. * @property {string} $name The name attribute of the control.
  22251. *
  22252. * @description
  22253. *
  22254. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22255. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22256. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22257. * listening to DOM events.
  22258. * Such DOM related logic should be provided by other directives which make use of
  22259. * `NgModelController` for data-binding to control elements.
  22260. * Angular provides this DOM logic for most {@link input `input`} elements.
  22261. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22262. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22263. *
  22264. * @example
  22265. * ### Custom Control Example
  22266. * This example shows how to use `NgModelController` with a custom control to achieve
  22267. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22268. * collaborate together to achieve the desired result.
  22269. *
  22270. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22271. * contents be edited in place by the user.
  22272. *
  22273. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22274. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22275. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22276. * that content using the `$sce` service.
  22277. *
  22278. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22279. <file name="style.css">
  22280. [contenteditable] {
  22281. border: 1px solid black;
  22282. background-color: white;
  22283. min-height: 20px;
  22284. }
  22285. .ng-invalid {
  22286. border: 1px solid red;
  22287. }
  22288. </file>
  22289. <file name="script.js">
  22290. angular.module('customControl', ['ngSanitize']).
  22291. directive('contenteditable', ['$sce', function($sce) {
  22292. return {
  22293. restrict: 'A', // only activate on element attribute
  22294. require: '?ngModel', // get a hold of NgModelController
  22295. link: function(scope, element, attrs, ngModel) {
  22296. if (!ngModel) return; // do nothing if no ng-model
  22297. // Specify how UI should be updated
  22298. ngModel.$render = function() {
  22299. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22300. };
  22301. // Listen for change events to enable binding
  22302. element.on('blur keyup change', function() {
  22303. scope.$evalAsync(read);
  22304. });
  22305. read(); // initialize
  22306. // Write data to the model
  22307. function read() {
  22308. var html = element.html();
  22309. // When we clear the content editable the browser leaves a <br> behind
  22310. // If strip-br attribute is provided then we strip this out
  22311. if ( attrs.stripBr && html == '<br>' ) {
  22312. html = '';
  22313. }
  22314. ngModel.$setViewValue(html);
  22315. }
  22316. }
  22317. };
  22318. }]);
  22319. </file>
  22320. <file name="index.html">
  22321. <form name="myForm">
  22322. <div contenteditable
  22323. name="myWidget" ng-model="userContent"
  22324. strip-br="true"
  22325. required>Change me!</div>
  22326. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22327. <hr>
  22328. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22329. </form>
  22330. </file>
  22331. <file name="protractor.js" type="protractor">
  22332. it('should data-bind and become invalid', function() {
  22333. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22334. // SafariDriver can't handle contenteditable
  22335. // and Firefox driver can't clear contenteditables very well
  22336. return;
  22337. }
  22338. var contentEditable = element(by.css('[contenteditable]'));
  22339. var content = 'Change me!';
  22340. expect(contentEditable.getText()).toEqual(content);
  22341. contentEditable.clear();
  22342. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22343. expect(contentEditable.getText()).toEqual('');
  22344. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22345. });
  22346. </file>
  22347. * </example>
  22348. *
  22349. *
  22350. */
  22351. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22352. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22353. this.$viewValue = Number.NaN;
  22354. this.$modelValue = Number.NaN;
  22355. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22356. this.$validators = {};
  22357. this.$asyncValidators = {};
  22358. this.$parsers = [];
  22359. this.$formatters = [];
  22360. this.$viewChangeListeners = [];
  22361. this.$untouched = true;
  22362. this.$touched = false;
  22363. this.$pristine = true;
  22364. this.$dirty = false;
  22365. this.$valid = true;
  22366. this.$invalid = false;
  22367. this.$error = {}; // keep invalid keys here
  22368. this.$$success = {}; // keep valid keys here
  22369. this.$pending = undefined; // keep pending keys here
  22370. this.$name = $interpolate($attr.name || '', false)($scope);
  22371. var parsedNgModel = $parse($attr.ngModel),
  22372. parsedNgModelAssign = parsedNgModel.assign,
  22373. ngModelGet = parsedNgModel,
  22374. ngModelSet = parsedNgModelAssign,
  22375. pendingDebounce = null,
  22376. parserValid,
  22377. ctrl = this;
  22378. this.$$setOptions = function(options) {
  22379. ctrl.$options = options;
  22380. if (options && options.getterSetter) {
  22381. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22382. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22383. ngModelGet = function($scope) {
  22384. var modelValue = parsedNgModel($scope);
  22385. if (isFunction(modelValue)) {
  22386. modelValue = invokeModelGetter($scope);
  22387. }
  22388. return modelValue;
  22389. };
  22390. ngModelSet = function($scope, newValue) {
  22391. if (isFunction(parsedNgModel($scope))) {
  22392. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22393. } else {
  22394. parsedNgModelAssign($scope, ctrl.$modelValue);
  22395. }
  22396. };
  22397. } else if (!parsedNgModel.assign) {
  22398. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22399. $attr.ngModel, startingTag($element));
  22400. }
  22401. };
  22402. /**
  22403. * @ngdoc method
  22404. * @name ngModel.NgModelController#$render
  22405. *
  22406. * @description
  22407. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22408. * directive will implement this method.
  22409. *
  22410. * The `$render()` method is invoked in the following situations:
  22411. *
  22412. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22413. * committed value then `$render()` is called to update the input control.
  22414. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22415. * the `$viewValue` are different from last time.
  22416. *
  22417. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22418. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22419. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22420. * invoked if you only change a property on the objects.
  22421. */
  22422. this.$render = noop;
  22423. /**
  22424. * @ngdoc method
  22425. * @name ngModel.NgModelController#$isEmpty
  22426. *
  22427. * @description
  22428. * This is called when we need to determine if the value of an input is empty.
  22429. *
  22430. * For instance, the required directive does this to work out if the input has data or not.
  22431. *
  22432. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22433. *
  22434. * You can override this for input directives whose concept of being empty is different from the
  22435. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22436. * implies empty.
  22437. *
  22438. * @param {*} value The value of the input to check for emptiness.
  22439. * @returns {boolean} True if `value` is "empty".
  22440. */
  22441. this.$isEmpty = function(value) {
  22442. return isUndefined(value) || value === '' || value === null || value !== value;
  22443. };
  22444. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  22445. currentValidationRunId = 0;
  22446. /**
  22447. * @ngdoc method
  22448. * @name ngModel.NgModelController#$setValidity
  22449. *
  22450. * @description
  22451. * Change the validity state, and notify the form.
  22452. *
  22453. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22454. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22455. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22456. *
  22457. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22458. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22459. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22460. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22461. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22462. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22463. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22464. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22465. * Skipped is used by Angular when validators do not run because of parse errors and
  22466. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22467. */
  22468. addSetValidityMethod({
  22469. ctrl: this,
  22470. $element: $element,
  22471. set: function(object, property) {
  22472. object[property] = true;
  22473. },
  22474. unset: function(object, property) {
  22475. delete object[property];
  22476. },
  22477. parentForm: parentForm,
  22478. $animate: $animate
  22479. });
  22480. /**
  22481. * @ngdoc method
  22482. * @name ngModel.NgModelController#$setPristine
  22483. *
  22484. * @description
  22485. * Sets the control to its pristine state.
  22486. *
  22487. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22488. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22489. * has not been changed from when first compiled.
  22490. */
  22491. this.$setPristine = function() {
  22492. ctrl.$dirty = false;
  22493. ctrl.$pristine = true;
  22494. $animate.removeClass($element, DIRTY_CLASS);
  22495. $animate.addClass($element, PRISTINE_CLASS);
  22496. };
  22497. /**
  22498. * @ngdoc method
  22499. * @name ngModel.NgModelController#$setDirty
  22500. *
  22501. * @description
  22502. * Sets the control to its dirty state.
  22503. *
  22504. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22505. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22506. * from when first compiled.
  22507. */
  22508. this.$setDirty = function() {
  22509. ctrl.$dirty = true;
  22510. ctrl.$pristine = false;
  22511. $animate.removeClass($element, PRISTINE_CLASS);
  22512. $animate.addClass($element, DIRTY_CLASS);
  22513. parentForm.$setDirty();
  22514. };
  22515. /**
  22516. * @ngdoc method
  22517. * @name ngModel.NgModelController#$setUntouched
  22518. *
  22519. * @description
  22520. * Sets the control to its untouched state.
  22521. *
  22522. * This method can be called to remove the `ng-touched` class and set the control to its
  22523. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22524. * by default, however this function can be used to restore that state if the model has
  22525. * already been touched by the user.
  22526. */
  22527. this.$setUntouched = function() {
  22528. ctrl.$touched = false;
  22529. ctrl.$untouched = true;
  22530. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22531. };
  22532. /**
  22533. * @ngdoc method
  22534. * @name ngModel.NgModelController#$setTouched
  22535. *
  22536. * @description
  22537. * Sets the control to its touched state.
  22538. *
  22539. * This method can be called to remove the `ng-untouched` class and set the control to its
  22540. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22541. * first focused the control element and then shifted focus away from the control (blur event).
  22542. */
  22543. this.$setTouched = function() {
  22544. ctrl.$touched = true;
  22545. ctrl.$untouched = false;
  22546. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22547. };
  22548. /**
  22549. * @ngdoc method
  22550. * @name ngModel.NgModelController#$rollbackViewValue
  22551. *
  22552. * @description
  22553. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22554. * which may be caused by a pending debounced event or because the input is waiting for a some
  22555. * future event.
  22556. *
  22557. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22558. * as blur you can have a situation where there is a period when the `$viewValue`
  22559. * is out of synch with the ngModel's `$modelValue`.
  22560. *
  22561. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22562. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22563. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22564. *
  22565. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22566. * input which may have such events pending. This is important in order to make sure that the
  22567. * input field will be updated with the new model value and any pending operations are cancelled.
  22568. *
  22569. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22570. * <file name="app.js">
  22571. * angular.module('cancel-update-example', [])
  22572. *
  22573. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22574. * $scope.resetWithCancel = function(e) {
  22575. * if (e.keyCode == 27) {
  22576. * $scope.myForm.myInput1.$rollbackViewValue();
  22577. * $scope.myValue = '';
  22578. * }
  22579. * };
  22580. * $scope.resetWithoutCancel = function(e) {
  22581. * if (e.keyCode == 27) {
  22582. * $scope.myValue = '';
  22583. * }
  22584. * };
  22585. * }]);
  22586. * </file>
  22587. * <file name="index.html">
  22588. * <div ng-controller="CancelUpdateController">
  22589. * <p>Try typing something in each input. See that the model only updates when you
  22590. * blur off the input.
  22591. * </p>
  22592. * <p>Now see what happens if you start typing then press the Escape key</p>
  22593. *
  22594. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22595. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22596. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22597. * ng-keydown="resetWithCancel($event)"><br/>
  22598. * myValue: "{{ myValue }}"
  22599. *
  22600. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22601. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22602. * ng-keydown="resetWithoutCancel($event)"><br/>
  22603. * myValue: "{{ myValue }}"
  22604. * </form>
  22605. * </div>
  22606. * </file>
  22607. * </example>
  22608. */
  22609. this.$rollbackViewValue = function() {
  22610. $timeout.cancel(pendingDebounce);
  22611. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22612. ctrl.$render();
  22613. };
  22614. /**
  22615. * @ngdoc method
  22616. * @name ngModel.NgModelController#$validate
  22617. *
  22618. * @description
  22619. * Runs each of the registered validators (first synchronous validators and then
  22620. * asynchronous validators).
  22621. * If the validity changes to invalid, the model will be set to `undefined`,
  22622. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22623. * If the validity changes to valid, it will set the model to the last available valid
  22624. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22625. */
  22626. this.$validate = function() {
  22627. // ignore $validate before model is initialized
  22628. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22629. return;
  22630. }
  22631. var viewValue = ctrl.$$lastCommittedViewValue;
  22632. // Note: we use the $$rawModelValue as $modelValue might have been
  22633. // set to undefined during a view -> model update that found validation
  22634. // errors. We can't parse the view here, since that could change
  22635. // the model although neither viewValue nor the model on the scope changed
  22636. var modelValue = ctrl.$$rawModelValue;
  22637. var prevValid = ctrl.$valid;
  22638. var prevModelValue = ctrl.$modelValue;
  22639. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22640. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22641. // If there was no change in validity, don't update the model
  22642. // This prevents changing an invalid modelValue to undefined
  22643. if (!allowInvalid && prevValid !== allValid) {
  22644. // Note: Don't check ctrl.$valid here, as we could have
  22645. // external validators (e.g. calculated on the server),
  22646. // that just call $setValidity and need the model value
  22647. // to calculate their validity.
  22648. ctrl.$modelValue = allValid ? modelValue : undefined;
  22649. if (ctrl.$modelValue !== prevModelValue) {
  22650. ctrl.$$writeModelToScope();
  22651. }
  22652. }
  22653. });
  22654. };
  22655. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22656. currentValidationRunId++;
  22657. var localValidationRunId = currentValidationRunId;
  22658. // check parser error
  22659. if (!processParseErrors()) {
  22660. validationDone(false);
  22661. return;
  22662. }
  22663. if (!processSyncValidators()) {
  22664. validationDone(false);
  22665. return;
  22666. }
  22667. processAsyncValidators();
  22668. function processParseErrors() {
  22669. var errorKey = ctrl.$$parserName || 'parse';
  22670. if (parserValid === undefined) {
  22671. setValidity(errorKey, null);
  22672. } else {
  22673. if (!parserValid) {
  22674. forEach(ctrl.$validators, function(v, name) {
  22675. setValidity(name, null);
  22676. });
  22677. forEach(ctrl.$asyncValidators, function(v, name) {
  22678. setValidity(name, null);
  22679. });
  22680. }
  22681. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22682. setValidity(errorKey, parserValid);
  22683. return parserValid;
  22684. }
  22685. return true;
  22686. }
  22687. function processSyncValidators() {
  22688. var syncValidatorsValid = true;
  22689. forEach(ctrl.$validators, function(validator, name) {
  22690. var result = validator(modelValue, viewValue);
  22691. syncValidatorsValid = syncValidatorsValid && result;
  22692. setValidity(name, result);
  22693. });
  22694. if (!syncValidatorsValid) {
  22695. forEach(ctrl.$asyncValidators, function(v, name) {
  22696. setValidity(name, null);
  22697. });
  22698. return false;
  22699. }
  22700. return true;
  22701. }
  22702. function processAsyncValidators() {
  22703. var validatorPromises = [];
  22704. var allValid = true;
  22705. forEach(ctrl.$asyncValidators, function(validator, name) {
  22706. var promise = validator(modelValue, viewValue);
  22707. if (!isPromiseLike(promise)) {
  22708. throw $ngModelMinErr("$asyncValidators",
  22709. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22710. }
  22711. setValidity(name, undefined);
  22712. validatorPromises.push(promise.then(function() {
  22713. setValidity(name, true);
  22714. }, function(error) {
  22715. allValid = false;
  22716. setValidity(name, false);
  22717. }));
  22718. });
  22719. if (!validatorPromises.length) {
  22720. validationDone(true);
  22721. } else {
  22722. $q.all(validatorPromises).then(function() {
  22723. validationDone(allValid);
  22724. }, noop);
  22725. }
  22726. }
  22727. function setValidity(name, isValid) {
  22728. if (localValidationRunId === currentValidationRunId) {
  22729. ctrl.$setValidity(name, isValid);
  22730. }
  22731. }
  22732. function validationDone(allValid) {
  22733. if (localValidationRunId === currentValidationRunId) {
  22734. doneCallback(allValid);
  22735. }
  22736. }
  22737. };
  22738. /**
  22739. * @ngdoc method
  22740. * @name ngModel.NgModelController#$commitViewValue
  22741. *
  22742. * @description
  22743. * Commit a pending update to the `$modelValue`.
  22744. *
  22745. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22746. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22747. * usually handles calling this in response to input events.
  22748. */
  22749. this.$commitViewValue = function() {
  22750. var viewValue = ctrl.$viewValue;
  22751. $timeout.cancel(pendingDebounce);
  22752. // If the view value has not changed then we should just exit, except in the case where there is
  22753. // a native validator on the element. In this case the validation state may have changed even though
  22754. // the viewValue has stayed empty.
  22755. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22756. return;
  22757. }
  22758. ctrl.$$lastCommittedViewValue = viewValue;
  22759. // change to dirty
  22760. if (ctrl.$pristine) {
  22761. this.$setDirty();
  22762. }
  22763. this.$$parseAndValidate();
  22764. };
  22765. this.$$parseAndValidate = function() {
  22766. var viewValue = ctrl.$$lastCommittedViewValue;
  22767. var modelValue = viewValue;
  22768. parserValid = isUndefined(modelValue) ? undefined : true;
  22769. if (parserValid) {
  22770. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22771. modelValue = ctrl.$parsers[i](modelValue);
  22772. if (isUndefined(modelValue)) {
  22773. parserValid = false;
  22774. break;
  22775. }
  22776. }
  22777. }
  22778. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22779. // ctrl.$modelValue has not been touched yet...
  22780. ctrl.$modelValue = ngModelGet($scope);
  22781. }
  22782. var prevModelValue = ctrl.$modelValue;
  22783. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22784. ctrl.$$rawModelValue = modelValue;
  22785. if (allowInvalid) {
  22786. ctrl.$modelValue = modelValue;
  22787. writeToModelIfNeeded();
  22788. }
  22789. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  22790. // This can happen if e.g. $setViewValue is called from inside a parser
  22791. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  22792. if (!allowInvalid) {
  22793. // Note: Don't check ctrl.$valid here, as we could have
  22794. // external validators (e.g. calculated on the server),
  22795. // that just call $setValidity and need the model value
  22796. // to calculate their validity.
  22797. ctrl.$modelValue = allValid ? modelValue : undefined;
  22798. writeToModelIfNeeded();
  22799. }
  22800. });
  22801. function writeToModelIfNeeded() {
  22802. if (ctrl.$modelValue !== prevModelValue) {
  22803. ctrl.$$writeModelToScope();
  22804. }
  22805. }
  22806. };
  22807. this.$$writeModelToScope = function() {
  22808. ngModelSet($scope, ctrl.$modelValue);
  22809. forEach(ctrl.$viewChangeListeners, function(listener) {
  22810. try {
  22811. listener();
  22812. } catch (e) {
  22813. $exceptionHandler(e);
  22814. }
  22815. });
  22816. };
  22817. /**
  22818. * @ngdoc method
  22819. * @name ngModel.NgModelController#$setViewValue
  22820. *
  22821. * @description
  22822. * Update the view value.
  22823. *
  22824. * This method should be called when an input directive want to change the view value; typically,
  22825. * this is done from within a DOM event handler.
  22826. *
  22827. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  22828. * {@link ng.directive:select select} calls it when an option is selected.
  22829. *
  22830. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  22831. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  22832. * watch of objects, it only looks for a change of identity. If you only change the property of
  22833. * the object then ngModel will not realise that the object has changed and will not invoke the
  22834. * `$parsers` and `$validators` pipelines.
  22835. *
  22836. * For this reason, you should not change properties of the copy once it has been passed to
  22837. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  22838. *
  22839. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  22840. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  22841. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  22842. * **expression** specified in the `ng-model` attribute.
  22843. *
  22844. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  22845. *
  22846. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  22847. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  22848. * `updateOn` events is triggered on the DOM element.
  22849. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  22850. * directive is used with a custom debounce for this particular event.
  22851. *
  22852. * Note that calling this function does not trigger a `$digest`.
  22853. *
  22854. * @param {string} value Value from the view.
  22855. * @param {string} trigger Event that triggered the update.
  22856. */
  22857. this.$setViewValue = function(value, trigger) {
  22858. ctrl.$viewValue = value;
  22859. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  22860. ctrl.$$debounceViewValueCommit(trigger);
  22861. }
  22862. };
  22863. this.$$debounceViewValueCommit = function(trigger) {
  22864. var debounceDelay = 0,
  22865. options = ctrl.$options,
  22866. debounce;
  22867. if (options && isDefined(options.debounce)) {
  22868. debounce = options.debounce;
  22869. if (isNumber(debounce)) {
  22870. debounceDelay = debounce;
  22871. } else if (isNumber(debounce[trigger])) {
  22872. debounceDelay = debounce[trigger];
  22873. } else if (isNumber(debounce['default'])) {
  22874. debounceDelay = debounce['default'];
  22875. }
  22876. }
  22877. $timeout.cancel(pendingDebounce);
  22878. if (debounceDelay) {
  22879. pendingDebounce = $timeout(function() {
  22880. ctrl.$commitViewValue();
  22881. }, debounceDelay);
  22882. } else if ($rootScope.$$phase) {
  22883. ctrl.$commitViewValue();
  22884. } else {
  22885. $scope.$apply(function() {
  22886. ctrl.$commitViewValue();
  22887. });
  22888. }
  22889. };
  22890. // model -> value
  22891. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  22892. // 1. scope value is 'a'
  22893. // 2. user enters 'b'
  22894. // 3. ng-change kicks in and reverts scope value to 'a'
  22895. // -> scope value did not change since the last digest as
  22896. // ng-change executes in apply phase
  22897. // 4. view should be changed back to 'a'
  22898. $scope.$watch(function ngModelWatch() {
  22899. var modelValue = ngModelGet($scope);
  22900. // if scope model value and ngModel value are out of sync
  22901. // TODO(perf): why not move this to the action fn?
  22902. if (modelValue !== ctrl.$modelValue &&
  22903. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  22904. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  22905. ) {
  22906. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  22907. parserValid = undefined;
  22908. var formatters = ctrl.$formatters,
  22909. idx = formatters.length;
  22910. var viewValue = modelValue;
  22911. while (idx--) {
  22912. viewValue = formatters[idx](viewValue);
  22913. }
  22914. if (ctrl.$viewValue !== viewValue) {
  22915. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  22916. ctrl.$render();
  22917. ctrl.$$runValidators(modelValue, viewValue, noop);
  22918. }
  22919. }
  22920. return modelValue;
  22921. });
  22922. }];
  22923. /**
  22924. * @ngdoc directive
  22925. * @name ngModel
  22926. *
  22927. * @element input
  22928. * @priority 1
  22929. *
  22930. * @description
  22931. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  22932. * property on the scope using {@link ngModel.NgModelController NgModelController},
  22933. * which is created and exposed by this directive.
  22934. *
  22935. * `ngModel` is responsible for:
  22936. *
  22937. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  22938. * require.
  22939. * - Providing validation behavior (i.e. required, number, email, url).
  22940. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  22941. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  22942. * - Registering the control with its parent {@link ng.directive:form form}.
  22943. *
  22944. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  22945. * current scope. If the property doesn't already exist on this scope, it will be created
  22946. * implicitly and added to the scope.
  22947. *
  22948. * For best practices on using `ngModel`, see:
  22949. *
  22950. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  22951. *
  22952. * For basic examples, how to use `ngModel`, see:
  22953. *
  22954. * - {@link ng.directive:input input}
  22955. * - {@link input[text] text}
  22956. * - {@link input[checkbox] checkbox}
  22957. * - {@link input[radio] radio}
  22958. * - {@link input[number] number}
  22959. * - {@link input[email] email}
  22960. * - {@link input[url] url}
  22961. * - {@link input[date] date}
  22962. * - {@link input[datetime-local] datetime-local}
  22963. * - {@link input[time] time}
  22964. * - {@link input[month] month}
  22965. * - {@link input[week] week}
  22966. * - {@link ng.directive:select select}
  22967. * - {@link ng.directive:textarea textarea}
  22968. *
  22969. * # CSS classes
  22970. * The following CSS classes are added and removed on the associated input/select/textarea element
  22971. * depending on the validity of the model.
  22972. *
  22973. * - `ng-valid`: the model is valid
  22974. * - `ng-invalid`: the model is invalid
  22975. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  22976. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  22977. * - `ng-pristine`: the control hasn't been interacted with yet
  22978. * - `ng-dirty`: the control has been interacted with
  22979. * - `ng-touched`: the control has been blurred
  22980. * - `ng-untouched`: the control hasn't been blurred
  22981. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  22982. *
  22983. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  22984. *
  22985. * ## Animation Hooks
  22986. *
  22987. * Animations within models are triggered when any of the associated CSS classes are added and removed
  22988. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  22989. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  22990. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  22991. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  22992. *
  22993. * The following example shows a simple way to utilize CSS transitions to style an input element
  22994. * that has been rendered as invalid after it has been validated:
  22995. *
  22996. * <pre>
  22997. * //be sure to include ngAnimate as a module to hook into more
  22998. * //advanced animations
  22999. * .my-input {
  23000. * transition:0.5s linear all;
  23001. * background: white;
  23002. * }
  23003. * .my-input.ng-invalid {
  23004. * background: red;
  23005. * color:white;
  23006. * }
  23007. * </pre>
  23008. *
  23009. * @example
  23010. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23011. <file name="index.html">
  23012. <script>
  23013. angular.module('inputExample', [])
  23014. .controller('ExampleController', ['$scope', function($scope) {
  23015. $scope.val = '1';
  23016. }]);
  23017. </script>
  23018. <style>
  23019. .my-input {
  23020. -webkit-transition:all linear 0.5s;
  23021. transition:all linear 0.5s;
  23022. background: transparent;
  23023. }
  23024. .my-input.ng-invalid {
  23025. color:white;
  23026. background: red;
  23027. }
  23028. </style>
  23029. <p id="inputDescription">
  23030. Update input to see transitions when valid/invalid.
  23031. Integer is a valid value.
  23032. </p>
  23033. <form name="testForm" ng-controller="ExampleController">
  23034. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23035. aria-describedby="inputDescription" />
  23036. </form>
  23037. </file>
  23038. * </example>
  23039. *
  23040. * ## Binding to a getter/setter
  23041. *
  23042. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23043. * function that returns a representation of the model when called with zero arguments, and sets
  23044. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23045. * for models that have an internal representation that's different from what the model exposes
  23046. * to the view.
  23047. *
  23048. * <div class="alert alert-success">
  23049. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23050. * frequently than other parts of your code.
  23051. * </div>
  23052. *
  23053. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23054. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23055. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23056. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23057. *
  23058. * The following example shows how to use `ngModel` with a getter/setter:
  23059. *
  23060. * @example
  23061. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23062. <file name="index.html">
  23063. <div ng-controller="ExampleController">
  23064. <form name="userForm">
  23065. <label>Name:
  23066. <input type="text" name="userName"
  23067. ng-model="user.name"
  23068. ng-model-options="{ getterSetter: true }" />
  23069. </label>
  23070. </form>
  23071. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23072. </div>
  23073. </file>
  23074. <file name="app.js">
  23075. angular.module('getterSetterExample', [])
  23076. .controller('ExampleController', ['$scope', function($scope) {
  23077. var _name = 'Brian';
  23078. $scope.user = {
  23079. name: function(newName) {
  23080. // Note that newName can be undefined for two reasons:
  23081. // 1. Because it is called as a getter and thus called with no arguments
  23082. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23083. // input is invalid
  23084. return arguments.length ? (_name = newName) : _name;
  23085. }
  23086. };
  23087. }]);
  23088. </file>
  23089. * </example>
  23090. */
  23091. var ngModelDirective = ['$rootScope', function($rootScope) {
  23092. return {
  23093. restrict: 'A',
  23094. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23095. controller: NgModelController,
  23096. // Prelink needs to run before any input directive
  23097. // so that we can set the NgModelOptions in NgModelController
  23098. // before anyone else uses it.
  23099. priority: 1,
  23100. compile: function ngModelCompile(element) {
  23101. // Setup initial state of the control
  23102. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23103. return {
  23104. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23105. var modelCtrl = ctrls[0],
  23106. formCtrl = ctrls[1] || nullFormCtrl;
  23107. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23108. // notify others, especially parent forms
  23109. formCtrl.$addControl(modelCtrl);
  23110. attr.$observe('name', function(newValue) {
  23111. if (modelCtrl.$name !== newValue) {
  23112. formCtrl.$$renameControl(modelCtrl, newValue);
  23113. }
  23114. });
  23115. scope.$on('$destroy', function() {
  23116. formCtrl.$removeControl(modelCtrl);
  23117. });
  23118. },
  23119. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23120. var modelCtrl = ctrls[0];
  23121. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23122. element.on(modelCtrl.$options.updateOn, function(ev) {
  23123. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23124. });
  23125. }
  23126. element.on('blur', function(ev) {
  23127. if (modelCtrl.$touched) return;
  23128. if ($rootScope.$$phase) {
  23129. scope.$evalAsync(modelCtrl.$setTouched);
  23130. } else {
  23131. scope.$apply(modelCtrl.$setTouched);
  23132. }
  23133. });
  23134. }
  23135. };
  23136. }
  23137. };
  23138. }];
  23139. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23140. /**
  23141. * @ngdoc directive
  23142. * @name ngModelOptions
  23143. *
  23144. * @description
  23145. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23146. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23147. * takes place when a timer expires; this timer will be reset after another change takes place.
  23148. *
  23149. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23150. * be different from the value in the actual model. This means that if you update the model you
  23151. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23152. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23153. *
  23154. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23155. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23156. * important because `form` controllers are published to the related scope under the name in their
  23157. * `name` attribute.
  23158. *
  23159. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23160. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23161. * to have access to the updated model.
  23162. *
  23163. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23164. *
  23165. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23166. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23167. * events using an space delimited list. There is a special event called `default` that
  23168. * matches the default events belonging of the control.
  23169. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23170. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23171. * custom value for each event. For example:
  23172. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23173. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23174. * not validate correctly instead of the default behavior of setting the model to undefined.
  23175. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23176. `ngModel` as getters/setters.
  23177. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23178. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23179. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23180. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23181. * If not specified, the timezone of the browser will be used.
  23182. *
  23183. * @example
  23184. The following example shows how to override immediate updates. Changes on the inputs within the
  23185. form will update the model only when the control loses focus (blur event). If `escape` key is
  23186. pressed while the input field is focused, the value is reset to the value in the current model.
  23187. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23188. <file name="index.html">
  23189. <div ng-controller="ExampleController">
  23190. <form name="userForm">
  23191. <label>Name:
  23192. <input type="text" name="userName"
  23193. ng-model="user.name"
  23194. ng-model-options="{ updateOn: 'blur' }"
  23195. ng-keyup="cancel($event)" />
  23196. </label><br />
  23197. <label>Other data:
  23198. <input type="text" ng-model="user.data" />
  23199. </label><br />
  23200. </form>
  23201. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23202. </div>
  23203. </file>
  23204. <file name="app.js">
  23205. angular.module('optionsExample', [])
  23206. .controller('ExampleController', ['$scope', function($scope) {
  23207. $scope.user = { name: 'say', data: '' };
  23208. $scope.cancel = function(e) {
  23209. if (e.keyCode == 27) {
  23210. $scope.userForm.userName.$rollbackViewValue();
  23211. }
  23212. };
  23213. }]);
  23214. </file>
  23215. <file name="protractor.js" type="protractor">
  23216. var model = element(by.binding('user.name'));
  23217. var input = element(by.model('user.name'));
  23218. var other = element(by.model('user.data'));
  23219. it('should allow custom events', function() {
  23220. input.sendKeys(' hello');
  23221. input.click();
  23222. expect(model.getText()).toEqual('say');
  23223. other.click();
  23224. expect(model.getText()).toEqual('say hello');
  23225. });
  23226. it('should $rollbackViewValue when model changes', function() {
  23227. input.sendKeys(' hello');
  23228. expect(input.getAttribute('value')).toEqual('say hello');
  23229. input.sendKeys(protractor.Key.ESCAPE);
  23230. expect(input.getAttribute('value')).toEqual('say');
  23231. other.click();
  23232. expect(model.getText()).toEqual('say');
  23233. });
  23234. </file>
  23235. </example>
  23236. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23237. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23238. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23239. <file name="index.html">
  23240. <div ng-controller="ExampleController">
  23241. <form name="userForm">
  23242. <label>Name:
  23243. <input type="text" name="userName"
  23244. ng-model="user.name"
  23245. ng-model-options="{ debounce: 1000 }" />
  23246. </label>
  23247. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23248. <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' };
  23257. }]);
  23258. </file>
  23259. </example>
  23260. This one shows how to bind to getter/setters:
  23261. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23262. <file name="index.html">
  23263. <div ng-controller="ExampleController">
  23264. <form name="userForm">
  23265. <label>Name:
  23266. <input type="text" name="userName"
  23267. ng-model="user.name"
  23268. ng-model-options="{ getterSetter: true }" />
  23269. </label>
  23270. </form>
  23271. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23272. </div>
  23273. </file>
  23274. <file name="app.js">
  23275. angular.module('getterSetterExample', [])
  23276. .controller('ExampleController', ['$scope', function($scope) {
  23277. var _name = 'Brian';
  23278. $scope.user = {
  23279. name: function(newName) {
  23280. // Note that newName can be undefined for two reasons:
  23281. // 1. Because it is called as a getter and thus called with no arguments
  23282. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23283. // input is invalid
  23284. return arguments.length ? (_name = newName) : _name;
  23285. }
  23286. };
  23287. }]);
  23288. </file>
  23289. </example>
  23290. */
  23291. var ngModelOptionsDirective = function() {
  23292. return {
  23293. restrict: 'A',
  23294. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23295. var that = this;
  23296. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23297. // Allow adding/overriding bound events
  23298. if (this.$options.updateOn !== undefined) {
  23299. this.$options.updateOnDefault = false;
  23300. // extract "default" pseudo-event from list of events that can trigger a model update
  23301. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23302. that.$options.updateOnDefault = true;
  23303. return ' ';
  23304. }));
  23305. } else {
  23306. this.$options.updateOnDefault = true;
  23307. }
  23308. }]
  23309. };
  23310. };
  23311. // helper methods
  23312. function addSetValidityMethod(context) {
  23313. var ctrl = context.ctrl,
  23314. $element = context.$element,
  23315. classCache = {},
  23316. set = context.set,
  23317. unset = context.unset,
  23318. parentForm = context.parentForm,
  23319. $animate = context.$animate;
  23320. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23321. ctrl.$setValidity = setValidity;
  23322. function setValidity(validationErrorKey, state, controller) {
  23323. if (state === undefined) {
  23324. createAndSet('$pending', validationErrorKey, controller);
  23325. } else {
  23326. unsetAndCleanup('$pending', validationErrorKey, controller);
  23327. }
  23328. if (!isBoolean(state)) {
  23329. unset(ctrl.$error, validationErrorKey, controller);
  23330. unset(ctrl.$$success, validationErrorKey, controller);
  23331. } else {
  23332. if (state) {
  23333. unset(ctrl.$error, validationErrorKey, controller);
  23334. set(ctrl.$$success, validationErrorKey, controller);
  23335. } else {
  23336. set(ctrl.$error, validationErrorKey, controller);
  23337. unset(ctrl.$$success, validationErrorKey, controller);
  23338. }
  23339. }
  23340. if (ctrl.$pending) {
  23341. cachedToggleClass(PENDING_CLASS, true);
  23342. ctrl.$valid = ctrl.$invalid = undefined;
  23343. toggleValidationCss('', null);
  23344. } else {
  23345. cachedToggleClass(PENDING_CLASS, false);
  23346. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23347. ctrl.$invalid = !ctrl.$valid;
  23348. toggleValidationCss('', ctrl.$valid);
  23349. }
  23350. // re-read the state as the set/unset methods could have
  23351. // combined state in ctrl.$error[validationError] (used for forms),
  23352. // where setting/unsetting only increments/decrements the value,
  23353. // and does not replace it.
  23354. var combinedState;
  23355. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23356. combinedState = undefined;
  23357. } else if (ctrl.$error[validationErrorKey]) {
  23358. combinedState = false;
  23359. } else if (ctrl.$$success[validationErrorKey]) {
  23360. combinedState = true;
  23361. } else {
  23362. combinedState = null;
  23363. }
  23364. toggleValidationCss(validationErrorKey, combinedState);
  23365. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23366. }
  23367. function createAndSet(name, value, controller) {
  23368. if (!ctrl[name]) {
  23369. ctrl[name] = {};
  23370. }
  23371. set(ctrl[name], value, controller);
  23372. }
  23373. function unsetAndCleanup(name, value, controller) {
  23374. if (ctrl[name]) {
  23375. unset(ctrl[name], value, controller);
  23376. }
  23377. if (isObjectEmpty(ctrl[name])) {
  23378. ctrl[name] = undefined;
  23379. }
  23380. }
  23381. function cachedToggleClass(className, switchValue) {
  23382. if (switchValue && !classCache[className]) {
  23383. $animate.addClass($element, className);
  23384. classCache[className] = true;
  23385. } else if (!switchValue && classCache[className]) {
  23386. $animate.removeClass($element, className);
  23387. classCache[className] = false;
  23388. }
  23389. }
  23390. function toggleValidationCss(validationErrorKey, isValid) {
  23391. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23392. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23393. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23394. }
  23395. }
  23396. function isObjectEmpty(obj) {
  23397. if (obj) {
  23398. for (var prop in obj) {
  23399. if (obj.hasOwnProperty(prop)) {
  23400. return false;
  23401. }
  23402. }
  23403. }
  23404. return true;
  23405. }
  23406. /**
  23407. * @ngdoc directive
  23408. * @name ngNonBindable
  23409. * @restrict AC
  23410. * @priority 1000
  23411. *
  23412. * @description
  23413. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23414. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23415. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23416. * displays snippets of code, for instance.
  23417. *
  23418. * @element ANY
  23419. *
  23420. * @example
  23421. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23422. * but the one wrapped in `ngNonBindable` is left alone.
  23423. *
  23424. * @example
  23425. <example>
  23426. <file name="index.html">
  23427. <div>Normal: {{1 + 2}}</div>
  23428. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23429. </file>
  23430. <file name="protractor.js" type="protractor">
  23431. it('should check ng-non-bindable', function() {
  23432. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23433. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23434. });
  23435. </file>
  23436. </example>
  23437. */
  23438. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23439. /* global jqLiteRemove */
  23440. var ngOptionsMinErr = minErr('ngOptions');
  23441. /**
  23442. * @ngdoc directive
  23443. * @name ngOptions
  23444. * @restrict A
  23445. *
  23446. * @description
  23447. *
  23448. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23449. * elements for the `<select>` element using the array or object obtained by evaluating the
  23450. * `ngOptions` comprehension expression.
  23451. *
  23452. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23453. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23454. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23455. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23456. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23457. * to a non-string value. This is because an option element can only be bound to string values at
  23458. * present.
  23459. *
  23460. * When an item in the `<select>` menu is selected, the array element or object property
  23461. * represented by the selected option will be bound to the model identified by the `ngModel`
  23462. * directive.
  23463. *
  23464. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23465. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23466. * option. See example below for demonstration.
  23467. *
  23468. * ## Complex Models (objects or collections)
  23469. *
  23470. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23471. * binding any input directive to a model that is an object or a collection.
  23472. *
  23473. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23474. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23475. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23476. * object/collection has not changed identity but only a property on the object or an item in the collection
  23477. * changes.
  23478. *
  23479. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23480. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23481. * first level will not trigger a re-rendering.
  23482. *
  23483. *
  23484. * ## `select` **`as`**
  23485. *
  23486. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23487. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23488. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23489. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23490. *
  23491. *
  23492. * ### `select` **`as`** and **`track by`**
  23493. *
  23494. * <div class="alert alert-warning">
  23495. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23496. * </div>
  23497. *
  23498. * Consider the following example:
  23499. *
  23500. * ```html
  23501. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23502. * ```
  23503. *
  23504. * ```js
  23505. * $scope.values = [{
  23506. * id: 1,
  23507. * label: 'aLabel',
  23508. * subItem: { name: 'aSubItem' }
  23509. * }, {
  23510. * id: 2,
  23511. * label: 'bLabel',
  23512. * subItem: { name: 'bSubItem' }
  23513. * }];
  23514. *
  23515. * $scope.selected = { name: 'aSubItem' };
  23516. * ```
  23517. *
  23518. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23519. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23520. * following:
  23521. *
  23522. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23523. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23524. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23525. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23526. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23527. * selected" option.
  23528. *
  23529. *
  23530. * @param {string} ngModel Assignable angular expression to data-bind to.
  23531. * @param {string=} name Property name of the form under which the control is published.
  23532. * @param {string=} required The control is considered valid only if value is entered.
  23533. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23534. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23535. * `required` when you want to data-bind to the `required` attribute.
  23536. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23537. *
  23538. * * for array data sources:
  23539. * * `label` **`for`** `value` **`in`** `array`
  23540. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23541. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23542. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23543. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23544. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23545. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23546. * (for including a filter with `track by`)
  23547. * * for object data sources:
  23548. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23549. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23550. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23551. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23552. * * `select` **`as`** `label` **`group by`** `group`
  23553. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23554. * * `select` **`as`** `label` **`disable when`** `disable`
  23555. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23556. *
  23557. * Where:
  23558. *
  23559. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23560. * * `value`: local variable which will refer to each item in the `array` or each property value
  23561. * of `object` during iteration.
  23562. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23563. * * `label`: The result of this expression will be the label for `<option>` element. The
  23564. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23565. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23566. * element. If not specified, `select` expression will default to `value`.
  23567. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23568. * DOM element.
  23569. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23570. * element. Return `true` to disable.
  23571. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23572. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23573. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23574. * even when the options are recreated (e.g. reloaded from the server).
  23575. *
  23576. * @example
  23577. <example module="selectExample">
  23578. <file name="index.html">
  23579. <script>
  23580. angular.module('selectExample', [])
  23581. .controller('ExampleController', ['$scope', function($scope) {
  23582. $scope.colors = [
  23583. {name:'black', shade:'dark'},
  23584. {name:'white', shade:'light', notAnOption: true},
  23585. {name:'red', shade:'dark'},
  23586. {name:'blue', shade:'dark', notAnOption: true},
  23587. {name:'yellow', shade:'light', notAnOption: false}
  23588. ];
  23589. $scope.myColor = $scope.colors[2]; // red
  23590. }]);
  23591. </script>
  23592. <div ng-controller="ExampleController">
  23593. <ul>
  23594. <li ng-repeat="color in colors">
  23595. <label>Name: <input ng-model="color.name"></label>
  23596. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23597. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23598. </li>
  23599. <li>
  23600. <button ng-click="colors.push({})">add</button>
  23601. </li>
  23602. </ul>
  23603. <hr/>
  23604. <label>Color (null not allowed):
  23605. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23606. </label><br/>
  23607. <label>Color (null allowed):
  23608. <span class="nullable">
  23609. <select ng-model="myColor" ng-options="color.name for color in colors">
  23610. <option value="">-- choose color --</option>
  23611. </select>
  23612. </span></label><br/>
  23613. <label>Color grouped by shade:
  23614. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23615. </select>
  23616. </label><br/>
  23617. <label>Color grouped by shade, with some disabled:
  23618. <select ng-model="myColor"
  23619. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23620. </select>
  23621. </label><br/>
  23622. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23623. <br/>
  23624. <hr/>
  23625. Currently selected: {{ {selected_color:myColor} }}
  23626. <div style="border:solid 1px black; height:20px"
  23627. ng-style="{'background-color':myColor.name}">
  23628. </div>
  23629. </div>
  23630. </file>
  23631. <file name="protractor.js" type="protractor">
  23632. it('should check ng-options', function() {
  23633. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23634. element.all(by.model('myColor')).first().click();
  23635. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23636. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23637. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23638. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23639. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23640. });
  23641. </file>
  23642. </example>
  23643. */
  23644. // jshint maxlen: false
  23645. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23646. 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]+?))?$/;
  23647. // 1: value expression (valueFn)
  23648. // 2: label expression (displayFn)
  23649. // 3: group by expression (groupByFn)
  23650. // 4: disable when expression (disableWhenFn)
  23651. // 5: array item variable name
  23652. // 6: object item key variable name
  23653. // 7: object item value variable name
  23654. // 8: collection expression
  23655. // 9: track by expression
  23656. // jshint maxlen: 100
  23657. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23658. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23659. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23660. if (!(match)) {
  23661. throw ngOptionsMinErr('iexp',
  23662. "Expected expression in form of " +
  23663. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23664. " but got '{0}'. Element: {1}",
  23665. optionsExp, startingTag(selectElement));
  23666. }
  23667. // Extract the parts from the ngOptions expression
  23668. // The variable name for the value of the item in the collection
  23669. var valueName = match[5] || match[7];
  23670. // The variable name for the key of the item in the collection
  23671. var keyName = match[6];
  23672. // An expression that generates the viewValue for an option if there is a label expression
  23673. var selectAs = / as /.test(match[0]) && match[1];
  23674. // An expression that is used to track the id of each object in the options collection
  23675. var trackBy = match[9];
  23676. // An expression that generates the viewValue for an option if there is no label expression
  23677. var valueFn = $parse(match[2] ? match[1] : valueName);
  23678. var selectAsFn = selectAs && $parse(selectAs);
  23679. var viewValueFn = selectAsFn || valueFn;
  23680. var trackByFn = trackBy && $parse(trackBy);
  23681. // Get the value by which we are going to track the option
  23682. // if we have a trackFn then use that (passing scope and locals)
  23683. // otherwise just hash the given viewValue
  23684. var getTrackByValueFn = trackBy ?
  23685. function(value, locals) { return trackByFn(scope, locals); } :
  23686. function getHashOfValue(value) { return hashKey(value); };
  23687. var getTrackByValue = function(value, key) {
  23688. return getTrackByValueFn(value, getLocals(value, key));
  23689. };
  23690. var displayFn = $parse(match[2] || match[1]);
  23691. var groupByFn = $parse(match[3] || '');
  23692. var disableWhenFn = $parse(match[4] || '');
  23693. var valuesFn = $parse(match[8]);
  23694. var locals = {};
  23695. var getLocals = keyName ? function(value, key) {
  23696. locals[keyName] = key;
  23697. locals[valueName] = value;
  23698. return locals;
  23699. } : function(value) {
  23700. locals[valueName] = value;
  23701. return locals;
  23702. };
  23703. function Option(selectValue, viewValue, label, group, disabled) {
  23704. this.selectValue = selectValue;
  23705. this.viewValue = viewValue;
  23706. this.label = label;
  23707. this.group = group;
  23708. this.disabled = disabled;
  23709. }
  23710. return {
  23711. trackBy: trackBy,
  23712. getTrackByValue: getTrackByValue,
  23713. getWatchables: $parse(valuesFn, function(values) {
  23714. // Create a collection of things that we would like to watch (watchedArray)
  23715. // so that they can all be watched using a single $watchCollection
  23716. // that only runs the handler once if anything changes
  23717. var watchedArray = [];
  23718. values = values || [];
  23719. Object.keys(values).forEach(function getWatchable(key) {
  23720. if (key.charAt(0) === '$') return;
  23721. var locals = getLocals(values[key], key);
  23722. var selectValue = getTrackByValueFn(values[key], locals);
  23723. watchedArray.push(selectValue);
  23724. // Only need to watch the displayFn if there is a specific label expression
  23725. if (match[2] || match[1]) {
  23726. var label = displayFn(scope, locals);
  23727. watchedArray.push(label);
  23728. }
  23729. // Only need to watch the disableWhenFn if there is a specific disable expression
  23730. if (match[4]) {
  23731. var disableWhen = disableWhenFn(scope, locals);
  23732. watchedArray.push(disableWhen);
  23733. }
  23734. });
  23735. return watchedArray;
  23736. }),
  23737. getOptions: function() {
  23738. var optionItems = [];
  23739. var selectValueMap = {};
  23740. // The option values were already computed in the `getWatchables` fn,
  23741. // which must have been called to trigger `getOptions`
  23742. var optionValues = valuesFn(scope) || [];
  23743. var optionValuesKeys;
  23744. if (!keyName && isArrayLike(optionValues)) {
  23745. optionValuesKeys = optionValues;
  23746. } else {
  23747. // if object, extract keys, in enumeration order, unsorted
  23748. optionValuesKeys = [];
  23749. for (var itemKey in optionValues) {
  23750. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23751. optionValuesKeys.push(itemKey);
  23752. }
  23753. }
  23754. }
  23755. var optionValuesLength = optionValuesKeys.length;
  23756. for (var index = 0; index < optionValuesLength; index++) {
  23757. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23758. var value = optionValues[key];
  23759. var locals = getLocals(value, key);
  23760. var viewValue = viewValueFn(scope, locals);
  23761. var selectValue = getTrackByValueFn(viewValue, locals);
  23762. var label = displayFn(scope, locals);
  23763. var group = groupByFn(scope, locals);
  23764. var disabled = disableWhenFn(scope, locals);
  23765. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  23766. optionItems.push(optionItem);
  23767. selectValueMap[selectValue] = optionItem;
  23768. }
  23769. return {
  23770. items: optionItems,
  23771. selectValueMap: selectValueMap,
  23772. getOptionFromViewValue: function(value) {
  23773. return selectValueMap[getTrackByValue(value)];
  23774. },
  23775. getViewValueFromOption: function(option) {
  23776. // If the viewValue could be an object that may be mutated by the application,
  23777. // we need to make a copy and not return the reference to the value on the option.
  23778. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  23779. }
  23780. };
  23781. }
  23782. };
  23783. }
  23784. // we can't just jqLite('<option>') since jqLite is not smart enough
  23785. // to create it in <select> and IE barfs otherwise.
  23786. var optionTemplate = document.createElement('option'),
  23787. optGroupTemplate = document.createElement('optgroup');
  23788. return {
  23789. restrict: 'A',
  23790. terminal: true,
  23791. require: ['select', '?ngModel'],
  23792. link: function(scope, selectElement, attr, ctrls) {
  23793. // if ngModel is not defined, we don't need to do anything
  23794. var ngModelCtrl = ctrls[1];
  23795. if (!ngModelCtrl) return;
  23796. var selectCtrl = ctrls[0];
  23797. var multiple = attr.multiple;
  23798. // The emptyOption allows the application developer to provide their own custom "empty"
  23799. // option when the viewValue does not match any of the option values.
  23800. var emptyOption;
  23801. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  23802. if (children[i].value === '') {
  23803. emptyOption = children.eq(i);
  23804. break;
  23805. }
  23806. }
  23807. var providedEmptyOption = !!emptyOption;
  23808. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  23809. unknownOption.val('?');
  23810. var options;
  23811. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  23812. var renderEmptyOption = function() {
  23813. if (!providedEmptyOption) {
  23814. selectElement.prepend(emptyOption);
  23815. }
  23816. selectElement.val('');
  23817. emptyOption.prop('selected', true); // needed for IE
  23818. emptyOption.attr('selected', true);
  23819. };
  23820. var removeEmptyOption = function() {
  23821. if (!providedEmptyOption) {
  23822. emptyOption.remove();
  23823. }
  23824. };
  23825. var renderUnknownOption = function() {
  23826. selectElement.prepend(unknownOption);
  23827. selectElement.val('?');
  23828. unknownOption.prop('selected', true); // needed for IE
  23829. unknownOption.attr('selected', true);
  23830. };
  23831. var removeUnknownOption = function() {
  23832. unknownOption.remove();
  23833. };
  23834. // Update the controller methods for multiple selectable options
  23835. if (!multiple) {
  23836. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  23837. var option = options.getOptionFromViewValue(value);
  23838. if (option && !option.disabled) {
  23839. if (selectElement[0].value !== option.selectValue) {
  23840. removeUnknownOption();
  23841. removeEmptyOption();
  23842. selectElement[0].value = option.selectValue;
  23843. option.element.selected = true;
  23844. option.element.setAttribute('selected', 'selected');
  23845. }
  23846. } else {
  23847. if (value === null || providedEmptyOption) {
  23848. removeUnknownOption();
  23849. renderEmptyOption();
  23850. } else {
  23851. removeEmptyOption();
  23852. renderUnknownOption();
  23853. }
  23854. }
  23855. };
  23856. selectCtrl.readValue = function readNgOptionsValue() {
  23857. var selectedOption = options.selectValueMap[selectElement.val()];
  23858. if (selectedOption && !selectedOption.disabled) {
  23859. removeEmptyOption();
  23860. removeUnknownOption();
  23861. return options.getViewValueFromOption(selectedOption);
  23862. }
  23863. return null;
  23864. };
  23865. // If we are using `track by` then we must watch the tracked value on the model
  23866. // since ngModel only watches for object identity change
  23867. if (ngOptions.trackBy) {
  23868. scope.$watch(
  23869. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  23870. function() { ngModelCtrl.$render(); }
  23871. );
  23872. }
  23873. } else {
  23874. ngModelCtrl.$isEmpty = function(value) {
  23875. return !value || value.length === 0;
  23876. };
  23877. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  23878. options.items.forEach(function(option) {
  23879. option.element.selected = false;
  23880. });
  23881. if (value) {
  23882. value.forEach(function(item) {
  23883. var option = options.getOptionFromViewValue(item);
  23884. if (option && !option.disabled) option.element.selected = true;
  23885. });
  23886. }
  23887. };
  23888. selectCtrl.readValue = function readNgOptionsMultiple() {
  23889. var selectedValues = selectElement.val() || [],
  23890. selections = [];
  23891. forEach(selectedValues, function(value) {
  23892. var option = options.selectValueMap[value];
  23893. if (!option.disabled) selections.push(options.getViewValueFromOption(option));
  23894. });
  23895. return selections;
  23896. };
  23897. // If we are using `track by` then we must watch these tracked values on the model
  23898. // since ngModel only watches for object identity change
  23899. if (ngOptions.trackBy) {
  23900. scope.$watchCollection(function() {
  23901. if (isArray(ngModelCtrl.$viewValue)) {
  23902. return ngModelCtrl.$viewValue.map(function(value) {
  23903. return ngOptions.getTrackByValue(value);
  23904. });
  23905. }
  23906. }, function() {
  23907. ngModelCtrl.$render();
  23908. });
  23909. }
  23910. }
  23911. if (providedEmptyOption) {
  23912. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23913. // remove the label from the element. wtf?
  23914. emptyOption.remove();
  23915. // compile the element since there might be bindings in it
  23916. $compile(emptyOption)(scope);
  23917. // remove the class, which is added automatically because we recompile the element and it
  23918. // becomes the compilation root
  23919. emptyOption.removeClass('ng-scope');
  23920. } else {
  23921. emptyOption = jqLite(optionTemplate.cloneNode(false));
  23922. }
  23923. // We need to do this here to ensure that the options object is defined
  23924. // when we first hit it in writeNgOptionsValue
  23925. updateOptions();
  23926. // We will re-render the option elements if the option values or labels change
  23927. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  23928. // ------------------------------------------------------------------ //
  23929. function updateOptionElement(option, element) {
  23930. option.element = element;
  23931. element.disabled = option.disabled;
  23932. if (option.value !== element.value) element.value = option.selectValue;
  23933. if (option.label !== element.label) {
  23934. element.label = option.label;
  23935. element.textContent = option.label;
  23936. }
  23937. }
  23938. function addOrReuseElement(parent, current, type, templateElement) {
  23939. var element;
  23940. // Check whether we can reuse the next element
  23941. if (current && lowercase(current.nodeName) === type) {
  23942. // The next element is the right type so reuse it
  23943. element = current;
  23944. } else {
  23945. // The next element is not the right type so create a new one
  23946. element = templateElement.cloneNode(false);
  23947. if (!current) {
  23948. // There are no more elements so just append it to the select
  23949. parent.appendChild(element);
  23950. } else {
  23951. // The next element is not a group so insert the new one
  23952. parent.insertBefore(element, current);
  23953. }
  23954. }
  23955. return element;
  23956. }
  23957. function removeExcessElements(current) {
  23958. var next;
  23959. while (current) {
  23960. next = current.nextSibling;
  23961. jqLiteRemove(current);
  23962. current = next;
  23963. }
  23964. }
  23965. function skipEmptyAndUnknownOptions(current) {
  23966. var emptyOption_ = emptyOption && emptyOption[0];
  23967. var unknownOption_ = unknownOption && unknownOption[0];
  23968. if (emptyOption_ || unknownOption_) {
  23969. while (current &&
  23970. (current === emptyOption_ ||
  23971. current === unknownOption_)) {
  23972. current = current.nextSibling;
  23973. }
  23974. }
  23975. return current;
  23976. }
  23977. function updateOptions() {
  23978. var previousValue = options && selectCtrl.readValue();
  23979. options = ngOptions.getOptions();
  23980. var groupMap = {};
  23981. var currentElement = selectElement[0].firstChild;
  23982. // Ensure that the empty option is always there if it was explicitly provided
  23983. if (providedEmptyOption) {
  23984. selectElement.prepend(emptyOption);
  23985. }
  23986. currentElement = skipEmptyAndUnknownOptions(currentElement);
  23987. options.items.forEach(function updateOption(option) {
  23988. var group;
  23989. var groupElement;
  23990. var optionElement;
  23991. if (option.group) {
  23992. // This option is to live in a group
  23993. // See if we have already created this group
  23994. group = groupMap[option.group];
  23995. if (!group) {
  23996. // We have not already created this group
  23997. groupElement = addOrReuseElement(selectElement[0],
  23998. currentElement,
  23999. 'optgroup',
  24000. optGroupTemplate);
  24001. // Move to the next element
  24002. currentElement = groupElement.nextSibling;
  24003. // Update the label on the group element
  24004. groupElement.label = option.group;
  24005. // Store it for use later
  24006. group = groupMap[option.group] = {
  24007. groupElement: groupElement,
  24008. currentOptionElement: groupElement.firstChild
  24009. };
  24010. }
  24011. // So now we have a group for this option we add the option to the group
  24012. optionElement = addOrReuseElement(group.groupElement,
  24013. group.currentOptionElement,
  24014. 'option',
  24015. optionTemplate);
  24016. updateOptionElement(option, optionElement);
  24017. // Move to the next element
  24018. group.currentOptionElement = optionElement.nextSibling;
  24019. } else {
  24020. // This option is not in a group
  24021. optionElement = addOrReuseElement(selectElement[0],
  24022. currentElement,
  24023. 'option',
  24024. optionTemplate);
  24025. updateOptionElement(option, optionElement);
  24026. // Move to the next element
  24027. currentElement = optionElement.nextSibling;
  24028. }
  24029. });
  24030. // Now remove all excess options and group
  24031. Object.keys(groupMap).forEach(function(key) {
  24032. removeExcessElements(groupMap[key].currentOptionElement);
  24033. });
  24034. removeExcessElements(currentElement);
  24035. ngModelCtrl.$render();
  24036. // Check to see if the value has changed due to the update to the options
  24037. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24038. var nextValue = selectCtrl.readValue();
  24039. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24040. ngModelCtrl.$setViewValue(nextValue);
  24041. ngModelCtrl.$render();
  24042. }
  24043. }
  24044. }
  24045. }
  24046. };
  24047. }];
  24048. /**
  24049. * @ngdoc directive
  24050. * @name ngPluralize
  24051. * @restrict EA
  24052. *
  24053. * @description
  24054. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24055. * These rules are bundled with angular.js, but can be overridden
  24056. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24057. * by specifying the mappings between
  24058. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24059. * and the strings to be displayed.
  24060. *
  24061. * # Plural categories and explicit number rules
  24062. * There are two
  24063. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24064. * in Angular's default en-US locale: "one" and "other".
  24065. *
  24066. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24067. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24068. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24069. * and explicit number rules throughout the rest of this documentation.
  24070. *
  24071. * # Configuring ngPluralize
  24072. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24073. * You can also provide an optional attribute, `offset`.
  24074. *
  24075. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24076. * Angular expression}; these are evaluated on the current scope for its bound value.
  24077. *
  24078. * The `when` attribute specifies the mappings between plural categories and the actual
  24079. * string to be displayed. The value of the attribute should be a JSON object.
  24080. *
  24081. * The following example shows how to configure ngPluralize:
  24082. *
  24083. * ```html
  24084. * <ng-pluralize count="personCount"
  24085. when="{'0': 'Nobody is viewing.',
  24086. * 'one': '1 person is viewing.',
  24087. * 'other': '{} people are viewing.'}">
  24088. * </ng-pluralize>
  24089. *```
  24090. *
  24091. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24092. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24093. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24094. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24095. * show "a dozen people are viewing".
  24096. *
  24097. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24098. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24099. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24100. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24101. *
  24102. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24103. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24104. *
  24105. * # Configuring ngPluralize with offset
  24106. * The `offset` attribute allows further customization of pluralized text, which can result in
  24107. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24108. * you might display "John, Kate and 2 others are viewing this document".
  24109. * The offset attribute allows you to offset a number by any desired value.
  24110. * Let's take a look at an example:
  24111. *
  24112. * ```html
  24113. * <ng-pluralize count="personCount" offset=2
  24114. * when="{'0': 'Nobody is viewing.',
  24115. * '1': '{{person1}} is viewing.',
  24116. * '2': '{{person1}} and {{person2}} are viewing.',
  24117. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24118. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24119. * </ng-pluralize>
  24120. * ```
  24121. *
  24122. * Notice that we are still using two plural categories(one, other), but we added
  24123. * three explicit number rules 0, 1 and 2.
  24124. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24125. * When three people view the document, no explicit number rule is found, so
  24126. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24127. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24128. * is shown.
  24129. *
  24130. * Note that when you specify offsets, you must provide explicit number rules for
  24131. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24132. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24133. * plural categories "one" and "other".
  24134. *
  24135. * @param {string|expression} count The variable to be bound to.
  24136. * @param {string} when The mapping between plural category to its corresponding strings.
  24137. * @param {number=} offset Offset to deduct from the total number.
  24138. *
  24139. * @example
  24140. <example module="pluralizeExample">
  24141. <file name="index.html">
  24142. <script>
  24143. angular.module('pluralizeExample', [])
  24144. .controller('ExampleController', ['$scope', function($scope) {
  24145. $scope.person1 = 'Igor';
  24146. $scope.person2 = 'Misko';
  24147. $scope.personCount = 1;
  24148. }]);
  24149. </script>
  24150. <div ng-controller="ExampleController">
  24151. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24152. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24153. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24154. <!--- Example with simple pluralization rules for en locale --->
  24155. Without Offset:
  24156. <ng-pluralize count="personCount"
  24157. when="{'0': 'Nobody is viewing.',
  24158. 'one': '1 person is viewing.',
  24159. 'other': '{} people are viewing.'}">
  24160. </ng-pluralize><br>
  24161. <!--- Example with offset --->
  24162. With Offset(2):
  24163. <ng-pluralize count="personCount" offset=2
  24164. when="{'0': 'Nobody is viewing.',
  24165. '1': '{{person1}} is viewing.',
  24166. '2': '{{person1}} and {{person2}} are viewing.',
  24167. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24168. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24169. </ng-pluralize>
  24170. </div>
  24171. </file>
  24172. <file name="protractor.js" type="protractor">
  24173. it('should show correct pluralized string', function() {
  24174. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24175. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24176. var countInput = element(by.model('personCount'));
  24177. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24178. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24179. countInput.clear();
  24180. countInput.sendKeys('0');
  24181. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24182. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24183. countInput.clear();
  24184. countInput.sendKeys('2');
  24185. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24186. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24187. countInput.clear();
  24188. countInput.sendKeys('3');
  24189. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24190. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24191. countInput.clear();
  24192. countInput.sendKeys('4');
  24193. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24194. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24195. });
  24196. it('should show data-bound names', function() {
  24197. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24198. var personCount = element(by.model('personCount'));
  24199. var person1 = element(by.model('person1'));
  24200. var person2 = element(by.model('person2'));
  24201. personCount.clear();
  24202. personCount.sendKeys('4');
  24203. person1.clear();
  24204. person1.sendKeys('Di');
  24205. person2.clear();
  24206. person2.sendKeys('Vojta');
  24207. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24208. });
  24209. </file>
  24210. </example>
  24211. */
  24212. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24213. var BRACE = /{}/g,
  24214. IS_WHEN = /^when(Minus)?(.+)$/;
  24215. return {
  24216. link: function(scope, element, attr) {
  24217. var numberExp = attr.count,
  24218. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24219. offset = attr.offset || 0,
  24220. whens = scope.$eval(whenExp) || {},
  24221. whensExpFns = {},
  24222. startSymbol = $interpolate.startSymbol(),
  24223. endSymbol = $interpolate.endSymbol(),
  24224. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24225. watchRemover = angular.noop,
  24226. lastCount;
  24227. forEach(attr, function(expression, attributeName) {
  24228. var tmpMatch = IS_WHEN.exec(attributeName);
  24229. if (tmpMatch) {
  24230. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24231. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24232. }
  24233. });
  24234. forEach(whens, function(expression, key) {
  24235. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24236. });
  24237. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24238. var count = parseFloat(newVal);
  24239. var countIsNaN = isNaN(count);
  24240. if (!countIsNaN && !(count in whens)) {
  24241. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24242. // Otherwise, check it against pluralization rules in $locale service.
  24243. count = $locale.pluralCat(count - offset);
  24244. }
  24245. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24246. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24247. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24248. watchRemover();
  24249. var whenExpFn = whensExpFns[count];
  24250. if (isUndefined(whenExpFn)) {
  24251. if (newVal != null) {
  24252. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24253. }
  24254. watchRemover = noop;
  24255. updateElementText();
  24256. } else {
  24257. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24258. }
  24259. lastCount = count;
  24260. }
  24261. });
  24262. function updateElementText(newText) {
  24263. element.text(newText || '');
  24264. }
  24265. }
  24266. };
  24267. }];
  24268. /**
  24269. * @ngdoc directive
  24270. * @name ngRepeat
  24271. *
  24272. * @description
  24273. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24274. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24275. * and `$index` is set to the item index or key.
  24276. *
  24277. * Special properties are exposed on the local scope of each template instance, including:
  24278. *
  24279. * | Variable | Type | Details |
  24280. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24281. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24282. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24283. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24284. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24285. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24286. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24287. *
  24288. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24289. * This may be useful when, for instance, nesting ngRepeats.
  24290. *
  24291. *
  24292. * # Iterating over object properties
  24293. *
  24294. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24295. * syntax:
  24296. *
  24297. * ```js
  24298. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24299. * ```
  24300. *
  24301. * You need to be aware that the JavaScript specification does not define the order of keys
  24302. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24303. * used to sort the keys alphabetically.)
  24304. *
  24305. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24306. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24307. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24308. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24309. *
  24310. * If this is not desired, the recommended workaround is to convert your object into an array
  24311. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24312. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24313. * or implement a `$watch` on the object yourself.
  24314. *
  24315. *
  24316. * # Tracking and Duplicates
  24317. *
  24318. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24319. *
  24320. * * When an item is added, a new instance of the template is added to the DOM.
  24321. * * When an item is removed, its template instance is removed from the DOM.
  24322. * * When items are reordered, their respective templates are reordered in the DOM.
  24323. *
  24324. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24325. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24326. * items and DOM elements.
  24327. *
  24328. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24329. * with your own using the `track by` expression.
  24330. *
  24331. * For example, you may track items by the index of each item in the collection, using the
  24332. * special scope property `$index`:
  24333. * ```html
  24334. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24335. * {{n}}
  24336. * </div>
  24337. * ```
  24338. *
  24339. * You may use arbitrary expressions in `track by`, including references to custom functions
  24340. * on the scope:
  24341. * ```html
  24342. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24343. * {{n}}
  24344. * </div>
  24345. * ```
  24346. *
  24347. * If you are working with objects that have an identifier property, you can track
  24348. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24349. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24350. * JavaScript objects in the collection have been substituted for new ones:
  24351. * ```html
  24352. * <div ng-repeat="model in collection track by model.id">
  24353. * {{model.name}}
  24354. * </div>
  24355. * ```
  24356. *
  24357. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24358. * `$id` function, which tracks items by their identity:
  24359. * ```html
  24360. * <div ng-repeat="obj in collection track by $id(obj)">
  24361. * {{obj.prop}}
  24362. * </div>
  24363. * ```
  24364. *
  24365. * <div class="alert alert-warning">
  24366. * **Note:** `track by` must always be the last expression:
  24367. * </div>
  24368. * ```
  24369. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24370. * {{model.name}}
  24371. * </div>
  24372. * ```
  24373. *
  24374. * # Special repeat start and end points
  24375. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24376. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24377. * 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)
  24378. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24379. *
  24380. * The example below makes use of this feature:
  24381. * ```html
  24382. * <header ng-repeat-start="item in items">
  24383. * Header {{ item }}
  24384. * </header>
  24385. * <div class="body">
  24386. * Body {{ item }}
  24387. * </div>
  24388. * <footer ng-repeat-end>
  24389. * Footer {{ item }}
  24390. * </footer>
  24391. * ```
  24392. *
  24393. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24394. * ```html
  24395. * <header>
  24396. * Header A
  24397. * </header>
  24398. * <div class="body">
  24399. * Body A
  24400. * </div>
  24401. * <footer>
  24402. * Footer A
  24403. * </footer>
  24404. * <header>
  24405. * Header B
  24406. * </header>
  24407. * <div class="body">
  24408. * Body B
  24409. * </div>
  24410. * <footer>
  24411. * Footer B
  24412. * </footer>
  24413. * ```
  24414. *
  24415. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24416. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24417. *
  24418. * @animations
  24419. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24420. *
  24421. * **.leave** - when an item is removed from the list or when an item is filtered out
  24422. *
  24423. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24424. *
  24425. * @element ANY
  24426. * @scope
  24427. * @priority 1000
  24428. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24429. * formats are currently supported:
  24430. *
  24431. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24432. * is a scope expression giving the collection to enumerate.
  24433. *
  24434. * For example: `album in artist.albums`.
  24435. *
  24436. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24437. * and `expression` is the scope expression giving the collection to enumerate.
  24438. *
  24439. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24440. *
  24441. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24442. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24443. * is specified, ng-repeat associates elements by identity. It is an error to have
  24444. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24445. * mapped to the same DOM element, which is not possible.)
  24446. *
  24447. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24448. *
  24449. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24450. * will be associated by item identity in the array.
  24451. *
  24452. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24453. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24454. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24455. * element in the same way in the DOM.
  24456. *
  24457. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24458. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24459. * property is same.
  24460. *
  24461. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24462. * to items in conjunction with a tracking expression.
  24463. *
  24464. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24465. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24466. * when a filter is active on the repeater, but the filtered result set is empty.
  24467. *
  24468. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24469. * the items have been processed through the filter.
  24470. *
  24471. * 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
  24472. * (and not as operator, inside an expression).
  24473. *
  24474. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24475. *
  24476. * @example
  24477. * This example initializes the scope to a list of names and
  24478. * then uses `ngRepeat` to display every person:
  24479. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24480. <file name="index.html">
  24481. <div ng-init="friends = [
  24482. {name:'John', age:25, gender:'boy'},
  24483. {name:'Jessie', age:30, gender:'girl'},
  24484. {name:'Johanna', age:28, gender:'girl'},
  24485. {name:'Joy', age:15, gender:'girl'},
  24486. {name:'Mary', age:28, gender:'girl'},
  24487. {name:'Peter', age:95, gender:'boy'},
  24488. {name:'Sebastian', age:50, gender:'boy'},
  24489. {name:'Erika', age:27, gender:'girl'},
  24490. {name:'Patrick', age:40, gender:'boy'},
  24491. {name:'Samantha', age:60, gender:'girl'}
  24492. ]">
  24493. I have {{friends.length}} friends. They are:
  24494. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24495. <ul class="example-animate-container">
  24496. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24497. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24498. </li>
  24499. <li class="animate-repeat" ng-if="results.length == 0">
  24500. <strong>No results found...</strong>
  24501. </li>
  24502. </ul>
  24503. </div>
  24504. </file>
  24505. <file name="animations.css">
  24506. .example-animate-container {
  24507. background:white;
  24508. border:1px solid black;
  24509. list-style:none;
  24510. margin:0;
  24511. padding:0 10px;
  24512. }
  24513. .animate-repeat {
  24514. line-height:40px;
  24515. list-style:none;
  24516. box-sizing:border-box;
  24517. }
  24518. .animate-repeat.ng-move,
  24519. .animate-repeat.ng-enter,
  24520. .animate-repeat.ng-leave {
  24521. -webkit-transition:all linear 0.5s;
  24522. transition:all linear 0.5s;
  24523. }
  24524. .animate-repeat.ng-leave.ng-leave-active,
  24525. .animate-repeat.ng-move,
  24526. .animate-repeat.ng-enter {
  24527. opacity:0;
  24528. max-height:0;
  24529. }
  24530. .animate-repeat.ng-leave,
  24531. .animate-repeat.ng-move.ng-move-active,
  24532. .animate-repeat.ng-enter.ng-enter-active {
  24533. opacity:1;
  24534. max-height:40px;
  24535. }
  24536. </file>
  24537. <file name="protractor.js" type="protractor">
  24538. var friends = element.all(by.repeater('friend in friends'));
  24539. it('should render initial data set', function() {
  24540. expect(friends.count()).toBe(10);
  24541. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24542. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24543. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24544. expect(element(by.binding('friends.length')).getText())
  24545. .toMatch("I have 10 friends. They are:");
  24546. });
  24547. it('should update repeater when filter predicate changes', function() {
  24548. expect(friends.count()).toBe(10);
  24549. element(by.model('q')).sendKeys('ma');
  24550. expect(friends.count()).toBe(2);
  24551. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24552. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24553. });
  24554. </file>
  24555. </example>
  24556. */
  24557. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24558. var NG_REMOVED = '$$NG_REMOVED';
  24559. var ngRepeatMinErr = minErr('ngRepeat');
  24560. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24561. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24562. scope[valueIdentifier] = value;
  24563. if (keyIdentifier) scope[keyIdentifier] = key;
  24564. scope.$index = index;
  24565. scope.$first = (index === 0);
  24566. scope.$last = (index === (arrayLength - 1));
  24567. scope.$middle = !(scope.$first || scope.$last);
  24568. // jshint bitwise: false
  24569. scope.$odd = !(scope.$even = (index&1) === 0);
  24570. // jshint bitwise: true
  24571. };
  24572. var getBlockStart = function(block) {
  24573. return block.clone[0];
  24574. };
  24575. var getBlockEnd = function(block) {
  24576. return block.clone[block.clone.length - 1];
  24577. };
  24578. return {
  24579. restrict: 'A',
  24580. multiElement: true,
  24581. transclude: 'element',
  24582. priority: 1000,
  24583. terminal: true,
  24584. $$tlb: true,
  24585. compile: function ngRepeatCompile($element, $attr) {
  24586. var expression = $attr.ngRepeat;
  24587. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24588. 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*$/);
  24589. if (!match) {
  24590. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24591. expression);
  24592. }
  24593. var lhs = match[1];
  24594. var rhs = match[2];
  24595. var aliasAs = match[3];
  24596. var trackByExp = match[4];
  24597. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24598. if (!match) {
  24599. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24600. lhs);
  24601. }
  24602. var valueIdentifier = match[3] || match[1];
  24603. var keyIdentifier = match[2];
  24604. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24605. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24606. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24607. aliasAs);
  24608. }
  24609. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24610. var hashFnLocals = {$id: hashKey};
  24611. if (trackByExp) {
  24612. trackByExpGetter = $parse(trackByExp);
  24613. } else {
  24614. trackByIdArrayFn = function(key, value) {
  24615. return hashKey(value);
  24616. };
  24617. trackByIdObjFn = function(key) {
  24618. return key;
  24619. };
  24620. }
  24621. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24622. if (trackByExpGetter) {
  24623. trackByIdExpFn = function(key, value, index) {
  24624. // assign key, value, and $index to the locals so that they can be used in hash functions
  24625. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24626. hashFnLocals[valueIdentifier] = value;
  24627. hashFnLocals.$index = index;
  24628. return trackByExpGetter($scope, hashFnLocals);
  24629. };
  24630. }
  24631. // Store a list of elements from previous run. This is a hash where key is the item from the
  24632. // iterator, and the value is objects with following properties.
  24633. // - scope: bound scope
  24634. // - element: previous element.
  24635. // - index: position
  24636. //
  24637. // We are using no-proto object so that we don't need to guard against inherited props via
  24638. // hasOwnProperty.
  24639. var lastBlockMap = createMap();
  24640. //watch props
  24641. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24642. var index, length,
  24643. previousNode = $element[0], // node that cloned nodes should be inserted after
  24644. // initialized to the comment node anchor
  24645. nextNode,
  24646. // Same as lastBlockMap but it has the current state. It will become the
  24647. // lastBlockMap on the next iteration.
  24648. nextBlockMap = createMap(),
  24649. collectionLength,
  24650. key, value, // key/value of iteration
  24651. trackById,
  24652. trackByIdFn,
  24653. collectionKeys,
  24654. block, // last object information {scope, element, id}
  24655. nextBlockOrder,
  24656. elementsToRemove;
  24657. if (aliasAs) {
  24658. $scope[aliasAs] = collection;
  24659. }
  24660. if (isArrayLike(collection)) {
  24661. collectionKeys = collection;
  24662. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24663. } else {
  24664. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24665. // if object, extract keys, in enumeration order, unsorted
  24666. collectionKeys = [];
  24667. for (var itemKey in collection) {
  24668. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24669. collectionKeys.push(itemKey);
  24670. }
  24671. }
  24672. }
  24673. collectionLength = collectionKeys.length;
  24674. nextBlockOrder = new Array(collectionLength);
  24675. // locate existing items
  24676. for (index = 0; index < collectionLength; index++) {
  24677. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24678. value = collection[key];
  24679. trackById = trackByIdFn(key, value, index);
  24680. if (lastBlockMap[trackById]) {
  24681. // found previously seen block
  24682. block = lastBlockMap[trackById];
  24683. delete lastBlockMap[trackById];
  24684. nextBlockMap[trackById] = block;
  24685. nextBlockOrder[index] = block;
  24686. } else if (nextBlockMap[trackById]) {
  24687. // if collision detected. restore lastBlockMap and throw an error
  24688. forEach(nextBlockOrder, function(block) {
  24689. if (block && block.scope) lastBlockMap[block.id] = block;
  24690. });
  24691. throw ngRepeatMinErr('dupes',
  24692. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24693. expression, trackById, value);
  24694. } else {
  24695. // new never before seen block
  24696. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24697. nextBlockMap[trackById] = true;
  24698. }
  24699. }
  24700. // remove leftover items
  24701. for (var blockKey in lastBlockMap) {
  24702. block = lastBlockMap[blockKey];
  24703. elementsToRemove = getBlockNodes(block.clone);
  24704. $animate.leave(elementsToRemove);
  24705. if (elementsToRemove[0].parentNode) {
  24706. // if the element was not removed yet because of pending animation, mark it as deleted
  24707. // so that we can ignore it later
  24708. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24709. elementsToRemove[index][NG_REMOVED] = true;
  24710. }
  24711. }
  24712. block.scope.$destroy();
  24713. }
  24714. // we are not using forEach for perf reasons (trying to avoid #call)
  24715. for (index = 0; index < collectionLength; index++) {
  24716. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24717. value = collection[key];
  24718. block = nextBlockOrder[index];
  24719. if (block.scope) {
  24720. // if we have already seen this object, then we need to reuse the
  24721. // associated scope/element
  24722. nextNode = previousNode;
  24723. // skip nodes that are already pending removal via leave animation
  24724. do {
  24725. nextNode = nextNode.nextSibling;
  24726. } while (nextNode && nextNode[NG_REMOVED]);
  24727. if (getBlockStart(block) != nextNode) {
  24728. // existing item which got moved
  24729. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24730. }
  24731. previousNode = getBlockEnd(block);
  24732. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24733. } else {
  24734. // new item which we don't know about
  24735. $transclude(function ngRepeatTransclude(clone, scope) {
  24736. block.scope = scope;
  24737. // http://jsperf.com/clone-vs-createcomment
  24738. var endNode = ngRepeatEndComment.cloneNode(false);
  24739. clone[clone.length++] = endNode;
  24740. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24741. $animate.enter(clone, null, jqLite(previousNode));
  24742. previousNode = endNode;
  24743. // Note: We only need the first/last node of the cloned nodes.
  24744. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24745. // by a directive with templateUrl when its template arrives.
  24746. block.clone = clone;
  24747. nextBlockMap[block.id] = block;
  24748. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24749. });
  24750. }
  24751. }
  24752. lastBlockMap = nextBlockMap;
  24753. });
  24754. };
  24755. }
  24756. };
  24757. }];
  24758. var NG_HIDE_CLASS = 'ng-hide';
  24759. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  24760. /**
  24761. * @ngdoc directive
  24762. * @name ngShow
  24763. *
  24764. * @description
  24765. * The `ngShow` directive shows or hides the given HTML element based on the expression
  24766. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  24767. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24768. * in AngularJS and sets the display style to none (using an !important flag).
  24769. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24770. *
  24771. * ```html
  24772. * <!-- when $scope.myValue is truthy (element is visible) -->
  24773. * <div ng-show="myValue"></div>
  24774. *
  24775. * <!-- when $scope.myValue is falsy (element is hidden) -->
  24776. * <div ng-show="myValue" class="ng-hide"></div>
  24777. * ```
  24778. *
  24779. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  24780. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  24781. * from the element causing the element not to appear hidden.
  24782. *
  24783. * ## Why is !important used?
  24784. *
  24785. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24786. * can be easily overridden by heavier selectors. For example, something as simple
  24787. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24788. * This also becomes a bigger issue when dealing with CSS frameworks.
  24789. *
  24790. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24791. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24792. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24793. *
  24794. * ### Overriding `.ng-hide`
  24795. *
  24796. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24797. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24798. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  24799. * with extra animation classes that can be added.
  24800. *
  24801. * ```css
  24802. * .ng-hide:not(.ng-hide-animate) {
  24803. * /&#42; this is just another form of hiding an element &#42;/
  24804. * display: block!important;
  24805. * position: absolute;
  24806. * top: -9999px;
  24807. * left: -9999px;
  24808. * }
  24809. * ```
  24810. *
  24811. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24812. *
  24813. * ## A note about animations with `ngShow`
  24814. *
  24815. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24816. * is true and false. This system works like the animation system present with ngClass except that
  24817. * you must also include the !important flag to override the display property
  24818. * so that you can perform an animation when the element is hidden during the time of the animation.
  24819. *
  24820. * ```css
  24821. * //
  24822. * //a working example can be found at the bottom of this page
  24823. * //
  24824. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24825. * /&#42; this is required as of 1.3x to properly
  24826. * apply all styling in a show/hide animation &#42;/
  24827. * transition: 0s linear all;
  24828. * }
  24829. *
  24830. * .my-element.ng-hide-add-active,
  24831. * .my-element.ng-hide-remove-active {
  24832. * /&#42; the transition is defined in the active class &#42;/
  24833. * transition: 1s linear all;
  24834. * }
  24835. *
  24836. * .my-element.ng-hide-add { ... }
  24837. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24838. * .my-element.ng-hide-remove { ... }
  24839. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24840. * ```
  24841. *
  24842. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  24843. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  24844. *
  24845. * @animations
  24846. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  24847. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  24848. *
  24849. * @element ANY
  24850. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  24851. * then the element is shown or hidden respectively.
  24852. *
  24853. * @example
  24854. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24855. <file name="index.html">
  24856. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  24857. <div>
  24858. Show:
  24859. <div class="check-element animate-show" ng-show="checked">
  24860. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  24861. </div>
  24862. </div>
  24863. <div>
  24864. Hide:
  24865. <div class="check-element animate-show" ng-hide="checked">
  24866. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  24867. </div>
  24868. </div>
  24869. </file>
  24870. <file name="glyphicons.css">
  24871. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  24872. </file>
  24873. <file name="animations.css">
  24874. .animate-show {
  24875. line-height: 20px;
  24876. opacity: 1;
  24877. padding: 10px;
  24878. border: 1px solid black;
  24879. background: white;
  24880. }
  24881. .animate-show.ng-hide-add.ng-hide-add-active,
  24882. .animate-show.ng-hide-remove.ng-hide-remove-active {
  24883. -webkit-transition: all linear 0.5s;
  24884. transition: all linear 0.5s;
  24885. }
  24886. .animate-show.ng-hide {
  24887. line-height: 0;
  24888. opacity: 0;
  24889. padding: 0 10px;
  24890. }
  24891. .check-element {
  24892. padding: 10px;
  24893. border: 1px solid black;
  24894. background: white;
  24895. }
  24896. </file>
  24897. <file name="protractor.js" type="protractor">
  24898. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  24899. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  24900. it('should check ng-show / ng-hide', function() {
  24901. expect(thumbsUp.isDisplayed()).toBeFalsy();
  24902. expect(thumbsDown.isDisplayed()).toBeTruthy();
  24903. element(by.model('checked')).click();
  24904. expect(thumbsUp.isDisplayed()).toBeTruthy();
  24905. expect(thumbsDown.isDisplayed()).toBeFalsy();
  24906. });
  24907. </file>
  24908. </example>
  24909. */
  24910. var ngShowDirective = ['$animate', function($animate) {
  24911. return {
  24912. restrict: 'A',
  24913. multiElement: true,
  24914. link: function(scope, element, attr) {
  24915. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  24916. // we're adding a temporary, animation-specific class for ng-hide since this way
  24917. // we can control when the element is actually displayed on screen without having
  24918. // to have a global/greedy CSS selector that breaks when other animations are run.
  24919. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  24920. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  24921. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  24922. });
  24923. });
  24924. }
  24925. };
  24926. }];
  24927. /**
  24928. * @ngdoc directive
  24929. * @name ngHide
  24930. *
  24931. * @description
  24932. * The `ngHide` directive shows or hides the given HTML element based on the expression
  24933. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  24934. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24935. * in AngularJS and sets the display style to none (using an !important flag).
  24936. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24937. *
  24938. * ```html
  24939. * <!-- when $scope.myValue is truthy (element is hidden) -->
  24940. * <div ng-hide="myValue" class="ng-hide"></div>
  24941. *
  24942. * <!-- when $scope.myValue is falsy (element is visible) -->
  24943. * <div ng-hide="myValue"></div>
  24944. * ```
  24945. *
  24946. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  24947. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  24948. * from the element causing the element not to appear hidden.
  24949. *
  24950. * ## Why is !important used?
  24951. *
  24952. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24953. * can be easily overridden by heavier selectors. For example, something as simple
  24954. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24955. * This also becomes a bigger issue when dealing with CSS frameworks.
  24956. *
  24957. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24958. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24959. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24960. *
  24961. * ### Overriding `.ng-hide`
  24962. *
  24963. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24964. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24965. * class in CSS:
  24966. *
  24967. * ```css
  24968. * .ng-hide {
  24969. * /&#42; this is just another form of hiding an element &#42;/
  24970. * display: block!important;
  24971. * position: absolute;
  24972. * top: -9999px;
  24973. * left: -9999px;
  24974. * }
  24975. * ```
  24976. *
  24977. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24978. *
  24979. * ## A note about animations with `ngHide`
  24980. *
  24981. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24982. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  24983. * CSS class is added and removed for you instead of your own CSS class.
  24984. *
  24985. * ```css
  24986. * //
  24987. * //a working example can be found at the bottom of this page
  24988. * //
  24989. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24990. * transition: 0.5s linear all;
  24991. * }
  24992. *
  24993. * .my-element.ng-hide-add { ... }
  24994. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24995. * .my-element.ng-hide-remove { ... }
  24996. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24997. * ```
  24998. *
  24999. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25000. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25001. *
  25002. * @animations
  25003. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25004. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25005. *
  25006. * @element ANY
  25007. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25008. * the element is shown or hidden respectively.
  25009. *
  25010. * @example
  25011. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25012. <file name="index.html">
  25013. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25014. <div>
  25015. Show:
  25016. <div class="check-element animate-hide" ng-show="checked">
  25017. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25018. </div>
  25019. </div>
  25020. <div>
  25021. Hide:
  25022. <div class="check-element animate-hide" ng-hide="checked">
  25023. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25024. </div>
  25025. </div>
  25026. </file>
  25027. <file name="glyphicons.css">
  25028. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25029. </file>
  25030. <file name="animations.css">
  25031. .animate-hide {
  25032. -webkit-transition: all linear 0.5s;
  25033. transition: all linear 0.5s;
  25034. line-height: 20px;
  25035. opacity: 1;
  25036. padding: 10px;
  25037. border: 1px solid black;
  25038. background: white;
  25039. }
  25040. .animate-hide.ng-hide {
  25041. line-height: 0;
  25042. opacity: 0;
  25043. padding: 0 10px;
  25044. }
  25045. .check-element {
  25046. padding: 10px;
  25047. border: 1px solid black;
  25048. background: white;
  25049. }
  25050. </file>
  25051. <file name="protractor.js" type="protractor">
  25052. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25053. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25054. it('should check ng-show / ng-hide', function() {
  25055. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25056. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25057. element(by.model('checked')).click();
  25058. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25059. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25060. });
  25061. </file>
  25062. </example>
  25063. */
  25064. var ngHideDirective = ['$animate', function($animate) {
  25065. return {
  25066. restrict: 'A',
  25067. multiElement: true,
  25068. link: function(scope, element, attr) {
  25069. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25070. // The comment inside of the ngShowDirective explains why we add and
  25071. // remove a temporary class for the show/hide animation
  25072. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25073. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25074. });
  25075. });
  25076. }
  25077. };
  25078. }];
  25079. /**
  25080. * @ngdoc directive
  25081. * @name ngStyle
  25082. * @restrict AC
  25083. *
  25084. * @description
  25085. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25086. *
  25087. * @element ANY
  25088. * @param {expression} ngStyle
  25089. *
  25090. * {@link guide/expression Expression} which evals to an
  25091. * object whose keys are CSS style names and values are corresponding values for those CSS
  25092. * keys.
  25093. *
  25094. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25095. * See the 'background-color' style in the example below.
  25096. *
  25097. * @example
  25098. <example>
  25099. <file name="index.html">
  25100. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25101. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25102. <input type="button" value="clear" ng-click="myStyle={}">
  25103. <br/>
  25104. <span ng-style="myStyle">Sample Text</span>
  25105. <pre>myStyle={{myStyle}}</pre>
  25106. </file>
  25107. <file name="style.css">
  25108. span {
  25109. color: black;
  25110. }
  25111. </file>
  25112. <file name="protractor.js" type="protractor">
  25113. var colorSpan = element(by.css('span'));
  25114. it('should check ng-style', function() {
  25115. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25116. element(by.css('input[value=\'set color\']')).click();
  25117. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25118. element(by.css('input[value=clear]')).click();
  25119. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25120. });
  25121. </file>
  25122. </example>
  25123. */
  25124. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25125. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25126. if (oldStyles && (newStyles !== oldStyles)) {
  25127. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25128. }
  25129. if (newStyles) element.css(newStyles);
  25130. }, true);
  25131. });
  25132. /**
  25133. * @ngdoc directive
  25134. * @name ngSwitch
  25135. * @restrict EA
  25136. *
  25137. * @description
  25138. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25139. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25140. * as specified in the template.
  25141. *
  25142. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25143. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25144. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25145. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25146. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25147. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25148. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25149. * attribute is displayed.
  25150. *
  25151. * <div class="alert alert-info">
  25152. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25153. * as literal string values to match against.
  25154. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25155. * value of the expression `$scope.someVal`.
  25156. * </div>
  25157. * @animations
  25158. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25159. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25160. *
  25161. * @usage
  25162. *
  25163. * ```
  25164. * <ANY ng-switch="expression">
  25165. * <ANY ng-switch-when="matchValue1">...</ANY>
  25166. * <ANY ng-switch-when="matchValue2">...</ANY>
  25167. * <ANY ng-switch-default>...</ANY>
  25168. * </ANY>
  25169. * ```
  25170. *
  25171. *
  25172. * @scope
  25173. * @priority 1200
  25174. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25175. * On child elements add:
  25176. *
  25177. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25178. * case will be displayed. If the same match appears multiple times, all the
  25179. * elements will be displayed.
  25180. * * `ngSwitchDefault`: the default case when no other case match. If there
  25181. * are multiple default cases, all of them will be displayed when no other
  25182. * case match.
  25183. *
  25184. *
  25185. * @example
  25186. <example module="switchExample" deps="angular-animate.js" animations="true">
  25187. <file name="index.html">
  25188. <div ng-controller="ExampleController">
  25189. <select ng-model="selection" ng-options="item for item in items">
  25190. </select>
  25191. <code>selection={{selection}}</code>
  25192. <hr/>
  25193. <div class="animate-switch-container"
  25194. ng-switch on="selection">
  25195. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25196. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25197. <div class="animate-switch" ng-switch-default>default</div>
  25198. </div>
  25199. </div>
  25200. </file>
  25201. <file name="script.js">
  25202. angular.module('switchExample', ['ngAnimate'])
  25203. .controller('ExampleController', ['$scope', function($scope) {
  25204. $scope.items = ['settings', 'home', 'other'];
  25205. $scope.selection = $scope.items[0];
  25206. }]);
  25207. </file>
  25208. <file name="animations.css">
  25209. .animate-switch-container {
  25210. position:relative;
  25211. background:white;
  25212. border:1px solid black;
  25213. height:40px;
  25214. overflow:hidden;
  25215. }
  25216. .animate-switch {
  25217. padding:10px;
  25218. }
  25219. .animate-switch.ng-animate {
  25220. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25221. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25222. position:absolute;
  25223. top:0;
  25224. left:0;
  25225. right:0;
  25226. bottom:0;
  25227. }
  25228. .animate-switch.ng-leave.ng-leave-active,
  25229. .animate-switch.ng-enter {
  25230. top:-50px;
  25231. }
  25232. .animate-switch.ng-leave,
  25233. .animate-switch.ng-enter.ng-enter-active {
  25234. top:0;
  25235. }
  25236. </file>
  25237. <file name="protractor.js" type="protractor">
  25238. var switchElem = element(by.css('[ng-switch]'));
  25239. var select = element(by.model('selection'));
  25240. it('should start in settings', function() {
  25241. expect(switchElem.getText()).toMatch(/Settings Div/);
  25242. });
  25243. it('should change to home', function() {
  25244. select.all(by.css('option')).get(1).click();
  25245. expect(switchElem.getText()).toMatch(/Home Span/);
  25246. });
  25247. it('should select default', function() {
  25248. select.all(by.css('option')).get(2).click();
  25249. expect(switchElem.getText()).toMatch(/default/);
  25250. });
  25251. </file>
  25252. </example>
  25253. */
  25254. var ngSwitchDirective = ['$animate', function($animate) {
  25255. return {
  25256. require: 'ngSwitch',
  25257. // asks for $scope to fool the BC controller module
  25258. controller: ['$scope', function ngSwitchController() {
  25259. this.cases = {};
  25260. }],
  25261. link: function(scope, element, attr, ngSwitchController) {
  25262. var watchExpr = attr.ngSwitch || attr.on,
  25263. selectedTranscludes = [],
  25264. selectedElements = [],
  25265. previousLeaveAnimations = [],
  25266. selectedScopes = [];
  25267. var spliceFactory = function(array, index) {
  25268. return function() { array.splice(index, 1); };
  25269. };
  25270. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25271. var i, ii;
  25272. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25273. $animate.cancel(previousLeaveAnimations[i]);
  25274. }
  25275. previousLeaveAnimations.length = 0;
  25276. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25277. var selected = getBlockNodes(selectedElements[i].clone);
  25278. selectedScopes[i].$destroy();
  25279. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25280. promise.then(spliceFactory(previousLeaveAnimations, i));
  25281. }
  25282. selectedElements.length = 0;
  25283. selectedScopes.length = 0;
  25284. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25285. forEach(selectedTranscludes, function(selectedTransclude) {
  25286. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25287. selectedScopes.push(selectedScope);
  25288. var anchor = selectedTransclude.element;
  25289. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25290. var block = { clone: caseElement };
  25291. selectedElements.push(block);
  25292. $animate.enter(caseElement, anchor.parent(), anchor);
  25293. });
  25294. });
  25295. }
  25296. });
  25297. }
  25298. };
  25299. }];
  25300. var ngSwitchWhenDirective = ngDirective({
  25301. transclude: 'element',
  25302. priority: 1200,
  25303. require: '^ngSwitch',
  25304. multiElement: true,
  25305. link: function(scope, element, attrs, ctrl, $transclude) {
  25306. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25307. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25308. }
  25309. });
  25310. var ngSwitchDefaultDirective = ngDirective({
  25311. transclude: 'element',
  25312. priority: 1200,
  25313. require: '^ngSwitch',
  25314. multiElement: true,
  25315. link: function(scope, element, attr, ctrl, $transclude) {
  25316. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25317. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25318. }
  25319. });
  25320. /**
  25321. * @ngdoc directive
  25322. * @name ngTransclude
  25323. * @restrict EAC
  25324. *
  25325. * @description
  25326. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25327. *
  25328. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25329. *
  25330. * @element ANY
  25331. *
  25332. * @example
  25333. <example module="transcludeExample">
  25334. <file name="index.html">
  25335. <script>
  25336. angular.module('transcludeExample', [])
  25337. .directive('pane', function(){
  25338. return {
  25339. restrict: 'E',
  25340. transclude: true,
  25341. scope: { title:'@' },
  25342. template: '<div style="border: 1px solid black;">' +
  25343. '<div style="background-color: gray">{{title}}</div>' +
  25344. '<ng-transclude></ng-transclude>' +
  25345. '</div>'
  25346. };
  25347. })
  25348. .controller('ExampleController', ['$scope', function($scope) {
  25349. $scope.title = 'Lorem Ipsum';
  25350. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25351. }]);
  25352. </script>
  25353. <div ng-controller="ExampleController">
  25354. <input ng-model="title" aria-label="title"> <br/>
  25355. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25356. <pane title="{{title}}">{{text}}</pane>
  25357. </div>
  25358. </file>
  25359. <file name="protractor.js" type="protractor">
  25360. it('should have transcluded', function() {
  25361. var titleElement = element(by.model('title'));
  25362. titleElement.clear();
  25363. titleElement.sendKeys('TITLE');
  25364. var textElement = element(by.model('text'));
  25365. textElement.clear();
  25366. textElement.sendKeys('TEXT');
  25367. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25368. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25369. });
  25370. </file>
  25371. </example>
  25372. *
  25373. */
  25374. var ngTranscludeDirective = ngDirective({
  25375. restrict: 'EAC',
  25376. link: function($scope, $element, $attrs, controller, $transclude) {
  25377. if (!$transclude) {
  25378. throw minErr('ngTransclude')('orphan',
  25379. 'Illegal use of ngTransclude directive in the template! ' +
  25380. 'No parent directive that requires a transclusion found. ' +
  25381. 'Element: {0}',
  25382. startingTag($element));
  25383. }
  25384. $transclude(function(clone) {
  25385. $element.empty();
  25386. $element.append(clone);
  25387. });
  25388. }
  25389. });
  25390. /**
  25391. * @ngdoc directive
  25392. * @name script
  25393. * @restrict E
  25394. *
  25395. * @description
  25396. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25397. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25398. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25399. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25400. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25401. *
  25402. * @param {string} type Must be set to `'text/ng-template'`.
  25403. * @param {string} id Cache name of the template.
  25404. *
  25405. * @example
  25406. <example>
  25407. <file name="index.html">
  25408. <script type="text/ng-template" id="/tpl.html">
  25409. Content of the template.
  25410. </script>
  25411. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25412. <div id="tpl-content" ng-include src="currentTpl"></div>
  25413. </file>
  25414. <file name="protractor.js" type="protractor">
  25415. it('should load template defined inside script tag', function() {
  25416. element(by.css('#tpl-link')).click();
  25417. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25418. });
  25419. </file>
  25420. </example>
  25421. */
  25422. var scriptDirective = ['$templateCache', function($templateCache) {
  25423. return {
  25424. restrict: 'E',
  25425. terminal: true,
  25426. compile: function(element, attr) {
  25427. if (attr.type == 'text/ng-template') {
  25428. var templateUrl = attr.id,
  25429. text = element[0].text;
  25430. $templateCache.put(templateUrl, text);
  25431. }
  25432. }
  25433. };
  25434. }];
  25435. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25436. /**
  25437. * @ngdoc type
  25438. * @name select.SelectController
  25439. * @description
  25440. * The controller for the `<select>` directive. This provides support for reading
  25441. * and writing the selected value(s) of the control and also coordinates dynamically
  25442. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25443. */
  25444. var SelectController =
  25445. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25446. var self = this,
  25447. optionsMap = new HashMap();
  25448. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25449. self.ngModelCtrl = noopNgModelController;
  25450. // The "unknown" option is one that is prepended to the list if the viewValue
  25451. // does not match any of the options. When it is rendered the value of the unknown
  25452. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25453. //
  25454. // We can't just jqLite('<option>') since jqLite is not smart enough
  25455. // to create it in <select> and IE barfs otherwise.
  25456. self.unknownOption = jqLite(document.createElement('option'));
  25457. self.renderUnknownOption = function(val) {
  25458. var unknownVal = '? ' + hashKey(val) + ' ?';
  25459. self.unknownOption.val(unknownVal);
  25460. $element.prepend(self.unknownOption);
  25461. $element.val(unknownVal);
  25462. };
  25463. $scope.$on('$destroy', function() {
  25464. // disable unknown option so that we don't do work when the whole select is being destroyed
  25465. self.renderUnknownOption = noop;
  25466. });
  25467. self.removeUnknownOption = function() {
  25468. if (self.unknownOption.parent()) self.unknownOption.remove();
  25469. };
  25470. // Read the value of the select control, the implementation of this changes depending
  25471. // upon whether the select can have multiple values and whether ngOptions is at work.
  25472. self.readValue = function readSingleValue() {
  25473. self.removeUnknownOption();
  25474. return $element.val();
  25475. };
  25476. // Write the value to the select control, the implementation of this changes depending
  25477. // upon whether the select can have multiple values and whether ngOptions is at work.
  25478. self.writeValue = function writeSingleValue(value) {
  25479. if (self.hasOption(value)) {
  25480. self.removeUnknownOption();
  25481. $element.val(value);
  25482. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25483. } else {
  25484. if (value == null && self.emptyOption) {
  25485. self.removeUnknownOption();
  25486. $element.val('');
  25487. } else {
  25488. self.renderUnknownOption(value);
  25489. }
  25490. }
  25491. };
  25492. // Tell the select control that an option, with the given value, has been added
  25493. self.addOption = function(value, element) {
  25494. assertNotHasOwnProperty(value, '"option value"');
  25495. if (value === '') {
  25496. self.emptyOption = element;
  25497. }
  25498. var count = optionsMap.get(value) || 0;
  25499. optionsMap.put(value, count + 1);
  25500. };
  25501. // Tell the select control that an option, with the given value, has been removed
  25502. self.removeOption = function(value) {
  25503. var count = optionsMap.get(value);
  25504. if (count) {
  25505. if (count === 1) {
  25506. optionsMap.remove(value);
  25507. if (value === '') {
  25508. self.emptyOption = undefined;
  25509. }
  25510. } else {
  25511. optionsMap.put(value, count - 1);
  25512. }
  25513. }
  25514. };
  25515. // Check whether the select control has an option matching the given value
  25516. self.hasOption = function(value) {
  25517. return !!optionsMap.get(value);
  25518. };
  25519. }];
  25520. /**
  25521. * @ngdoc directive
  25522. * @name select
  25523. * @restrict E
  25524. *
  25525. * @description
  25526. * HTML `SELECT` element with angular data-binding.
  25527. *
  25528. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25529. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
  25530. * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
  25531. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25532. * comprehension expression.
  25533. *
  25534. * When an item in the `<select>` menu is selected, the array element or object property
  25535. * represented by the selected option will be bound to the model identified by the `ngModel`
  25536. * directive.
  25537. *
  25538. * If the viewValue contains a value that doesn't match any of the options then the control
  25539. * will automatically add an "unknown" option, which it then removes when this is resolved.
  25540. *
  25541. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25542. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25543. * option. See example below for demonstration.
  25544. *
  25545. * <div class="alert alert-info">
  25546. * The value of a `select` directive used without `ngOptions` is always a string.
  25547. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25548. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25549. * This is because an option element can only be bound to string values at present.
  25550. * </div>
  25551. *
  25552. * ### Example (binding `select` to a non-string value)
  25553. *
  25554. * <example name="select-with-non-string-options" module="nonStringSelect">
  25555. * <file name="index.html">
  25556. * <select ng-model="model.id" convert-to-number>
  25557. * <option value="0">Zero</option>
  25558. * <option value="1">One</option>
  25559. * <option value="2">Two</option>
  25560. * </select>
  25561. * {{ model }}
  25562. * </file>
  25563. * <file name="app.js">
  25564. * angular.module('nonStringSelect', [])
  25565. * .run(function($rootScope) {
  25566. * $rootScope.model = { id: 2 };
  25567. * })
  25568. * .directive('convertToNumber', function() {
  25569. * return {
  25570. * require: 'ngModel',
  25571. * link: function(scope, element, attrs, ngModel) {
  25572. * ngModel.$parsers.push(function(val) {
  25573. * return parseInt(val, 10);
  25574. * });
  25575. * ngModel.$formatters.push(function(val) {
  25576. * return '' + val;
  25577. * });
  25578. * }
  25579. * };
  25580. * });
  25581. * </file>
  25582. * <file name="protractor.js" type="protractor">
  25583. * it('should initialize to model', function() {
  25584. * var select = element(by.css('select'));
  25585. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25586. * });
  25587. * </file>
  25588. * </example>
  25589. *
  25590. */
  25591. var selectDirective = function() {
  25592. return {
  25593. restrict: 'E',
  25594. require: ['select', '?ngModel'],
  25595. controller: SelectController,
  25596. link: function(scope, element, attr, ctrls) {
  25597. // if ngModel is not defined, we don't need to do anything
  25598. var ngModelCtrl = ctrls[1];
  25599. if (!ngModelCtrl) return;
  25600. var selectCtrl = ctrls[0];
  25601. selectCtrl.ngModelCtrl = ngModelCtrl;
  25602. // We delegate rendering to the `writeValue` method, which can be changed
  25603. // if the select can have multiple selected values or if the options are being
  25604. // generated by `ngOptions`
  25605. ngModelCtrl.$render = function() {
  25606. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25607. };
  25608. // When the selected item(s) changes we delegate getting the value of the select control
  25609. // to the `readValue` method, which can be changed if the select can have multiple
  25610. // selected values or if the options are being generated by `ngOptions`
  25611. element.on('change', function() {
  25612. scope.$apply(function() {
  25613. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25614. });
  25615. });
  25616. // If the select allows multiple values then we need to modify how we read and write
  25617. // values from and to the control; also what it means for the value to be empty and
  25618. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25619. // doesn't trigger rendering if only an item in the array changes.
  25620. if (attr.multiple) {
  25621. // Read value now needs to check each option to see if it is selected
  25622. selectCtrl.readValue = function readMultipleValue() {
  25623. var array = [];
  25624. forEach(element.find('option'), function(option) {
  25625. if (option.selected) {
  25626. array.push(option.value);
  25627. }
  25628. });
  25629. return array;
  25630. };
  25631. // Write value now needs to set the selected property of each matching option
  25632. selectCtrl.writeValue = function writeMultipleValue(value) {
  25633. var items = new HashMap(value);
  25634. forEach(element.find('option'), function(option) {
  25635. option.selected = isDefined(items.get(option.value));
  25636. });
  25637. };
  25638. // we have to do it on each watch since ngModel watches reference, but
  25639. // we need to work of an array, so we need to see if anything was inserted/removed
  25640. var lastView, lastViewRef = NaN;
  25641. scope.$watch(function selectMultipleWatch() {
  25642. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  25643. lastView = shallowCopy(ngModelCtrl.$viewValue);
  25644. ngModelCtrl.$render();
  25645. }
  25646. lastViewRef = ngModelCtrl.$viewValue;
  25647. });
  25648. // If we are a multiple select then value is now a collection
  25649. // so the meaning of $isEmpty changes
  25650. ngModelCtrl.$isEmpty = function(value) {
  25651. return !value || value.length === 0;
  25652. };
  25653. }
  25654. }
  25655. };
  25656. };
  25657. // The option directive is purely designed to communicate the existence (or lack of)
  25658. // of dynamically created (and destroyed) option elements to their containing select
  25659. // directive via its controller.
  25660. var optionDirective = ['$interpolate', function($interpolate) {
  25661. function chromeHack(optionElement) {
  25662. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25663. // Adding an <option selected="selected"> element to a <select required="required"> should
  25664. // automatically select the new element
  25665. if (optionElement[0].hasAttribute('selected')) {
  25666. optionElement[0].selected = true;
  25667. }
  25668. }
  25669. return {
  25670. restrict: 'E',
  25671. priority: 100,
  25672. compile: function(element, attr) {
  25673. // If the value attribute is not defined then we fall back to the
  25674. // text content of the option element, which may be interpolated
  25675. if (isUndefined(attr.value)) {
  25676. var interpolateFn = $interpolate(element.text(), true);
  25677. if (!interpolateFn) {
  25678. attr.$set('value', element.text());
  25679. }
  25680. }
  25681. return function(scope, element, attr) {
  25682. // This is an optimization over using ^^ since we don't want to have to search
  25683. // all the way to the root of the DOM for every single option element
  25684. var selectCtrlName = '$selectController',
  25685. parent = element.parent(),
  25686. selectCtrl = parent.data(selectCtrlName) ||
  25687. parent.parent().data(selectCtrlName); // in case we are in optgroup
  25688. // Only update trigger option updates if this is an option within a `select`
  25689. // that also has `ngModel` attached
  25690. if (selectCtrl && selectCtrl.ngModelCtrl) {
  25691. if (interpolateFn) {
  25692. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  25693. attr.$set('value', newVal);
  25694. if (oldVal !== newVal) {
  25695. selectCtrl.removeOption(oldVal);
  25696. }
  25697. selectCtrl.addOption(newVal, element);
  25698. selectCtrl.ngModelCtrl.$render();
  25699. chromeHack(element);
  25700. });
  25701. } else {
  25702. selectCtrl.addOption(attr.value, element);
  25703. selectCtrl.ngModelCtrl.$render();
  25704. chromeHack(element);
  25705. }
  25706. element.on('$destroy', function() {
  25707. selectCtrl.removeOption(attr.value);
  25708. selectCtrl.ngModelCtrl.$render();
  25709. });
  25710. }
  25711. };
  25712. }
  25713. };
  25714. }];
  25715. var styleDirective = valueFn({
  25716. restrict: 'E',
  25717. terminal: false
  25718. });
  25719. var requiredDirective = function() {
  25720. return {
  25721. restrict: 'A',
  25722. require: '?ngModel',
  25723. link: function(scope, elm, attr, ctrl) {
  25724. if (!ctrl) return;
  25725. attr.required = true; // force truthy in case we are on non input element
  25726. ctrl.$validators.required = function(modelValue, viewValue) {
  25727. return !attr.required || !ctrl.$isEmpty(viewValue);
  25728. };
  25729. attr.$observe('required', function() {
  25730. ctrl.$validate();
  25731. });
  25732. }
  25733. };
  25734. };
  25735. var patternDirective = function() {
  25736. return {
  25737. restrict: 'A',
  25738. require: '?ngModel',
  25739. link: function(scope, elm, attr, ctrl) {
  25740. if (!ctrl) return;
  25741. var regexp, patternExp = attr.ngPattern || attr.pattern;
  25742. attr.$observe('pattern', function(regex) {
  25743. if (isString(regex) && regex.length > 0) {
  25744. regex = new RegExp('^' + regex + '$');
  25745. }
  25746. if (regex && !regex.test) {
  25747. throw minErr('ngPattern')('noregexp',
  25748. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  25749. regex, startingTag(elm));
  25750. }
  25751. regexp = regex || undefined;
  25752. ctrl.$validate();
  25753. });
  25754. ctrl.$validators.pattern = function(value) {
  25755. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  25756. };
  25757. }
  25758. };
  25759. };
  25760. var maxlengthDirective = function() {
  25761. return {
  25762. restrict: 'A',
  25763. require: '?ngModel',
  25764. link: function(scope, elm, attr, ctrl) {
  25765. if (!ctrl) return;
  25766. var maxlength = -1;
  25767. attr.$observe('maxlength', function(value) {
  25768. var intVal = toInt(value);
  25769. maxlength = isNaN(intVal) ? -1 : intVal;
  25770. ctrl.$validate();
  25771. });
  25772. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  25773. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  25774. };
  25775. }
  25776. };
  25777. };
  25778. var minlengthDirective = function() {
  25779. return {
  25780. restrict: 'A',
  25781. require: '?ngModel',
  25782. link: function(scope, elm, attr, ctrl) {
  25783. if (!ctrl) return;
  25784. var minlength = 0;
  25785. attr.$observe('minlength', function(value) {
  25786. minlength = toInt(value) || 0;
  25787. ctrl.$validate();
  25788. });
  25789. ctrl.$validators.minlength = function(modelValue, viewValue) {
  25790. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  25791. };
  25792. }
  25793. };
  25794. };
  25795. if (window.angular.bootstrap) {
  25796. //AngularJS is already loaded, so we can return here...
  25797. console.log('WARNING: Tried to load angular more than once.');
  25798. return;
  25799. }
  25800. //try to bind to jquery now so that one can write jqLite(document).ready()
  25801. //but we will rebind on bootstrap again.
  25802. bindJQuery();
  25803. publishExternalAPI(angular);
  25804. jqLite(document).ready(function() {
  25805. angularInit(document, bootstrap);
  25806. });
  25807. })(window, document);
  25808. !window.angular.$$csp() && window.angular.element(document).find('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>');