angular.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982
  1. /**
  2. * @license AngularJS v1.6.1
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.6.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 ESLint what variables are being exported */
  63. /* exported
  64. angular,
  65. msie,
  66. jqLite,
  67. jQuery,
  68. slice,
  69. splice,
  70. push,
  71. toString,
  72. ngMinErr,
  73. angularModule,
  74. uid,
  75. REGEX_STRING_REGEXP,
  76. VALIDITY_STATE_PROPERTY,
  77. lowercase,
  78. uppercase,
  79. manualLowercase,
  80. manualUppercase,
  81. nodeName_,
  82. isArrayLike,
  83. forEach,
  84. forEachSorted,
  85. reverseParams,
  86. nextUid,
  87. setHashKey,
  88. extend,
  89. toInt,
  90. inherit,
  91. merge,
  92. noop,
  93. identity,
  94. valueFn,
  95. isUndefined,
  96. isDefined,
  97. isObject,
  98. isBlankObject,
  99. isString,
  100. isNumber,
  101. isNumberNaN,
  102. isDate,
  103. isArray,
  104. isFunction,
  105. isRegExp,
  106. isWindow,
  107. isScope,
  108. isFile,
  109. isFormData,
  110. isBlob,
  111. isBoolean,
  112. isPromiseLike,
  113. trim,
  114. escapeForRegexp,
  115. isElement,
  116. makeMap,
  117. includes,
  118. arrayRemove,
  119. copy,
  120. equals,
  121. csp,
  122. jq,
  123. concat,
  124. sliceArgs,
  125. bind,
  126. toJsonReplacer,
  127. toJson,
  128. fromJson,
  129. convertTimezoneToLocal,
  130. timezoneToOffset,
  131. startingTag,
  132. tryDecodeURIComponent,
  133. parseKeyValue,
  134. toKeyValue,
  135. encodeUriSegment,
  136. encodeUriQuery,
  137. angularInit,
  138. bootstrap,
  139. getTestability,
  140. snake_case,
  141. bindJQuery,
  142. assertArg,
  143. assertArgFn,
  144. assertNotHasOwnProperty,
  145. getter,
  146. getBlockNodes,
  147. hasOwnProperty,
  148. createMap,
  149. stringify,
  150. NODE_TYPE_ELEMENT,
  151. NODE_TYPE_ATTRIBUTE,
  152. NODE_TYPE_TEXT,
  153. NODE_TYPE_COMMENT,
  154. NODE_TYPE_DOCUMENT,
  155. NODE_TYPE_DOCUMENT_FRAGMENT
  156. */
  157. ////////////////////////////////////
  158. /**
  159. * @ngdoc module
  160. * @name ng
  161. * @module ng
  162. * @installation
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  174. // The name of a form control's ValidityState property.
  175. // This is used so that it's possible for internal tests to create mock ValidityStates.
  176. var VALIDITY_STATE_PROPERTY = 'validity';
  177. var hasOwnProperty = Object.prototype.hasOwnProperty;
  178. /**
  179. * @ngdoc function
  180. * @name angular.lowercase
  181. * @module ng
  182. * @kind function
  183. *
  184. * @deprecated
  185. * sinceVersion="1.5.0"
  186. * removeVersion="1.7.0"
  187. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  188. *
  189. * @description Converts the specified string to lowercase.
  190. * @param {string} string String to be converted to lowercase.
  191. * @returns {string} Lowercased string.
  192. */
  193. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  194. /**
  195. * @ngdoc function
  196. * @name angular.uppercase
  197. * @module ng
  198. * @kind function
  199. *
  200. * @deprecated
  201. * sinceVersion="1.5.0"
  202. * removeVersion="1.7.0"
  203. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  204. *
  205. * @description Converts the specified string to uppercase.
  206. * @param {string} string String to be converted to uppercase.
  207. * @returns {string} Uppercased string.
  208. */
  209. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  210. var manualLowercase = function(s) {
  211. /* eslint-disable no-bitwise */
  212. return isString(s)
  213. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  214. : s;
  215. /* eslint-enable */
  216. };
  217. var manualUppercase = function(s) {
  218. /* eslint-disable no-bitwise */
  219. return isString(s)
  220. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  221. : s;
  222. /* eslint-enable */
  223. };
  224. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  225. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  226. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  227. if ('i' !== 'I'.toLowerCase()) {
  228. lowercase = manualLowercase;
  229. uppercase = manualUppercase;
  230. }
  231. var
  232. msie, // holds major version number for IE, or NaN if UA is not IE.
  233. jqLite, // delay binding since jQuery could be loaded after us.
  234. jQuery, // delay binding
  235. slice = [].slice,
  236. splice = [].splice,
  237. push = [].push,
  238. toString = Object.prototype.toString,
  239. getPrototypeOf = Object.getPrototypeOf,
  240. ngMinErr = minErr('ng'),
  241. /** @name angular */
  242. angular = window.angular || (window.angular = {}),
  243. angularModule,
  244. uid = 0;
  245. // Support: IE 9-11 only
  246. /**
  247. * documentMode is an IE-only property
  248. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  249. */
  250. msie = window.document.documentMode;
  251. /**
  252. * @private
  253. * @param {*} obj
  254. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  255. * String ...)
  256. */
  257. function isArrayLike(obj) {
  258. // `null`, `undefined` and `window` are not array-like
  259. if (obj == null || isWindow(obj)) return false;
  260. // arrays, strings and jQuery/jqLite objects are array like
  261. // * jqLite is either the jQuery or jqLite constructor function
  262. // * we have to check the existence of jqLite first as this method is called
  263. // via the forEach method when constructing the jqLite object in the first place
  264. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  265. // Support: iOS 8.2 (not reproducible in simulator)
  266. // "length" in obj used to prevent JIT error (gh-11508)
  267. var length = 'length' in Object(obj) && obj.length;
  268. // NodeList objects (with `item` method) and
  269. // other objects with suitable length characteristics are array-like
  270. return isNumber(length) &&
  271. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  272. }
  273. /**
  274. * @ngdoc function
  275. * @name angular.forEach
  276. * @module ng
  277. * @kind function
  278. *
  279. * @description
  280. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  281. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  282. * is the value of an object property or an array element, `key` is the object property key or
  283. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  284. *
  285. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  286. * using the `hasOwnProperty` method.
  287. *
  288. * Unlike ES262's
  289. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  290. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  291. * return the value provided.
  292. *
  293. ```js
  294. var values = {name: 'misko', gender: 'male'};
  295. var log = [];
  296. angular.forEach(values, function(value, key) {
  297. this.push(key + ': ' + value);
  298. }, log);
  299. expect(log).toEqual(['name: misko', 'gender: male']);
  300. ```
  301. *
  302. * @param {Object|Array} obj Object to iterate over.
  303. * @param {Function} iterator Iterator function.
  304. * @param {Object=} context Object to become context (`this`) for the iterator function.
  305. * @returns {Object|Array} Reference to `obj`.
  306. */
  307. function forEach(obj, iterator, context) {
  308. var key, length;
  309. if (obj) {
  310. if (isFunction(obj)) {
  311. for (key in obj) {
  312. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  313. iterator.call(context, obj[key], key, obj);
  314. }
  315. }
  316. } else if (isArray(obj) || isArrayLike(obj)) {
  317. var isPrimitive = typeof obj !== 'object';
  318. for (key = 0, length = obj.length; key < length; key++) {
  319. if (isPrimitive || key in obj) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. } else if (obj.forEach && obj.forEach !== forEach) {
  324. obj.forEach(iterator, context, obj);
  325. } else if (isBlankObject(obj)) {
  326. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  327. for (key in obj) {
  328. iterator.call(context, obj[key], key, obj);
  329. }
  330. } else if (typeof obj.hasOwnProperty === 'function') {
  331. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  332. for (key in obj) {
  333. if (obj.hasOwnProperty(key)) {
  334. iterator.call(context, obj[key], key, obj);
  335. }
  336. }
  337. } else {
  338. // Slow path for objects which do not have a method `hasOwnProperty`
  339. for (key in obj) {
  340. if (hasOwnProperty.call(obj, key)) {
  341. iterator.call(context, obj[key], key, obj);
  342. }
  343. }
  344. }
  345. }
  346. return obj;
  347. }
  348. function forEachSorted(obj, iterator, context) {
  349. var keys = Object.keys(obj).sort();
  350. for (var i = 0; i < keys.length; i++) {
  351. iterator.call(context, obj[keys[i]], keys[i]);
  352. }
  353. return keys;
  354. }
  355. /**
  356. * when using forEach the params are value, key, but it is often useful to have key, value.
  357. * @param {function(string, *)} iteratorFn
  358. * @returns {function(*, string)}
  359. */
  360. function reverseParams(iteratorFn) {
  361. return function(value, key) {iteratorFn(key, value);};
  362. }
  363. /**
  364. * A consistent way of creating unique IDs in angular.
  365. *
  366. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  367. * we hit number precision issues in JavaScript.
  368. *
  369. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  370. *
  371. * @returns {number} an unique alpha-numeric string
  372. */
  373. function nextUid() {
  374. return ++uid;
  375. }
  376. /**
  377. * Set or clear the hashkey for an object.
  378. * @param obj object
  379. * @param h the hashkey (!truthy to delete the hashkey)
  380. */
  381. function setHashKey(obj, h) {
  382. if (h) {
  383. obj.$$hashKey = h;
  384. } else {
  385. delete obj.$$hashKey;
  386. }
  387. }
  388. function baseExtend(dst, objs, deep) {
  389. var h = dst.$$hashKey;
  390. for (var i = 0, ii = objs.length; i < ii; ++i) {
  391. var obj = objs[i];
  392. if (!isObject(obj) && !isFunction(obj)) continue;
  393. var keys = Object.keys(obj);
  394. for (var j = 0, jj = keys.length; j < jj; j++) {
  395. var key = keys[j];
  396. var src = obj[key];
  397. if (deep && isObject(src)) {
  398. if (isDate(src)) {
  399. dst[key] = new Date(src.valueOf());
  400. } else if (isRegExp(src)) {
  401. dst[key] = new RegExp(src);
  402. } else if (src.nodeName) {
  403. dst[key] = src.cloneNode(true);
  404. } else if (isElement(src)) {
  405. dst[key] = src.clone();
  406. } else {
  407. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  408. baseExtend(dst[key], [src], true);
  409. }
  410. } else {
  411. dst[key] = src;
  412. }
  413. }
  414. }
  415. setHashKey(dst, h);
  416. return dst;
  417. }
  418. /**
  419. * @ngdoc function
  420. * @name angular.extend
  421. * @module ng
  422. * @kind function
  423. *
  424. * @description
  425. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  426. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  427. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  428. *
  429. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  430. * {@link angular.merge} for this.
  431. *
  432. * @param {Object} dst Destination object.
  433. * @param {...Object} src Source object(s).
  434. * @returns {Object} Reference to `dst`.
  435. */
  436. function extend(dst) {
  437. return baseExtend(dst, slice.call(arguments, 1), false);
  438. }
  439. /**
  440. * @ngdoc function
  441. * @name angular.merge
  442. * @module ng
  443. * @kind function
  444. *
  445. * @description
  446. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  447. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  448. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  449. *
  450. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  451. * objects, performing a deep copy.
  452. *
  453. * @param {Object} dst Destination object.
  454. * @param {...Object} src Source object(s).
  455. * @returns {Object} Reference to `dst`.
  456. */
  457. function merge(dst) {
  458. return baseExtend(dst, slice.call(arguments, 1), true);
  459. }
  460. function toInt(str) {
  461. return parseInt(str, 10);
  462. }
  463. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  464. // eslint-disable-next-line no-self-compare
  465. return num !== num;
  466. };
  467. function inherit(parent, extra) {
  468. return extend(Object.create(parent), extra);
  469. }
  470. /**
  471. * @ngdoc function
  472. * @name angular.noop
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * A function that performs no operations. This function can be useful when writing code in the
  478. * functional style.
  479. ```js
  480. function foo(callback) {
  481. var result = calculateResult();
  482. (callback || angular.noop)(result);
  483. }
  484. ```
  485. */
  486. function noop() {}
  487. noop.$inject = [];
  488. /**
  489. * @ngdoc function
  490. * @name angular.identity
  491. * @module ng
  492. * @kind function
  493. *
  494. * @description
  495. * A function that returns its first argument. This function is useful when writing code in the
  496. * functional style.
  497. *
  498. ```js
  499. function transformer(transformationFn, value) {
  500. return (transformationFn || angular.identity)(value);
  501. };
  502. // E.g.
  503. function getResult(fn, input) {
  504. return (fn || angular.identity)(input);
  505. };
  506. getResult(function(n) { return n * 2; }, 21); // returns 42
  507. getResult(null, 21); // returns 21
  508. getResult(undefined, 21); // returns 21
  509. ```
  510. *
  511. * @param {*} value to be returned.
  512. * @returns {*} the value passed in.
  513. */
  514. function identity($) {return $;}
  515. identity.$inject = [];
  516. function valueFn(value) {return function valueRef() {return value;};}
  517. function hasCustomToString(obj) {
  518. return isFunction(obj.toString) && obj.toString !== toString;
  519. }
  520. /**
  521. * @ngdoc function
  522. * @name angular.isUndefined
  523. * @module ng
  524. * @kind function
  525. *
  526. * @description
  527. * Determines if a reference is undefined.
  528. *
  529. * @param {*} value Reference to check.
  530. * @returns {boolean} True if `value` is undefined.
  531. */
  532. function isUndefined(value) {return typeof value === 'undefined';}
  533. /**
  534. * @ngdoc function
  535. * @name angular.isDefined
  536. * @module ng
  537. * @kind function
  538. *
  539. * @description
  540. * Determines if a reference is defined.
  541. *
  542. * @param {*} value Reference to check.
  543. * @returns {boolean} True if `value` is defined.
  544. */
  545. function isDefined(value) {return typeof value !== 'undefined';}
  546. /**
  547. * @ngdoc function
  548. * @name angular.isObject
  549. * @module ng
  550. * @kind function
  551. *
  552. * @description
  553. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  554. * considered to be objects. Note that JavaScript arrays are objects.
  555. *
  556. * @param {*} value Reference to check.
  557. * @returns {boolean} True if `value` is an `Object` but not `null`.
  558. */
  559. function isObject(value) {
  560. // http://jsperf.com/isobject4
  561. return value !== null && typeof value === 'object';
  562. }
  563. /**
  564. * Determine if a value is an object with a null prototype
  565. *
  566. * @returns {boolean} True if `value` is an `Object` with a null prototype
  567. */
  568. function isBlankObject(value) {
  569. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  570. }
  571. /**
  572. * @ngdoc function
  573. * @name angular.isString
  574. * @module ng
  575. * @kind function
  576. *
  577. * @description
  578. * Determines if a reference is a `String`.
  579. *
  580. * @param {*} value Reference to check.
  581. * @returns {boolean} True if `value` is a `String`.
  582. */
  583. function isString(value) {return typeof value === 'string';}
  584. /**
  585. * @ngdoc function
  586. * @name angular.isNumber
  587. * @module ng
  588. * @kind function
  589. *
  590. * @description
  591. * Determines if a reference is a `Number`.
  592. *
  593. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  594. *
  595. * If you wish to exclude these then you can use the native
  596. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  597. * method.
  598. *
  599. * @param {*} value Reference to check.
  600. * @returns {boolean} True if `value` is a `Number`.
  601. */
  602. function isNumber(value) {return typeof value === 'number';}
  603. /**
  604. * @ngdoc function
  605. * @name angular.isDate
  606. * @module ng
  607. * @kind function
  608. *
  609. * @description
  610. * Determines if a value is a date.
  611. *
  612. * @param {*} value Reference to check.
  613. * @returns {boolean} True if `value` is a `Date`.
  614. */
  615. function isDate(value) {
  616. return toString.call(value) === '[object Date]';
  617. }
  618. /**
  619. * @ngdoc function
  620. * @name angular.isArray
  621. * @module ng
  622. * @kind function
  623. *
  624. * @description
  625. * Determines if a reference is an `Array`. Alias of Array.isArray.
  626. *
  627. * @param {*} value Reference to check.
  628. * @returns {boolean} True if `value` is an `Array`.
  629. */
  630. var isArray = Array.isArray;
  631. /**
  632. * @ngdoc function
  633. * @name angular.isFunction
  634. * @module ng
  635. * @kind function
  636. *
  637. * @description
  638. * Determines if a reference is a `Function`.
  639. *
  640. * @param {*} value Reference to check.
  641. * @returns {boolean} True if `value` is a `Function`.
  642. */
  643. function isFunction(value) {return typeof value === 'function';}
  644. /**
  645. * Determines if a value is a regular expression object.
  646. *
  647. * @private
  648. * @param {*} value Reference to check.
  649. * @returns {boolean} True if `value` is a `RegExp`.
  650. */
  651. function isRegExp(value) {
  652. return toString.call(value) === '[object RegExp]';
  653. }
  654. /**
  655. * Checks if `obj` is a window object.
  656. *
  657. * @private
  658. * @param {*} obj Object to check
  659. * @returns {boolean} True if `obj` is a window obj.
  660. */
  661. function isWindow(obj) {
  662. return obj && obj.window === obj;
  663. }
  664. function isScope(obj) {
  665. return obj && obj.$evalAsync && obj.$watch;
  666. }
  667. function isFile(obj) {
  668. return toString.call(obj) === '[object File]';
  669. }
  670. function isFormData(obj) {
  671. return toString.call(obj) === '[object FormData]';
  672. }
  673. function isBlob(obj) {
  674. return toString.call(obj) === '[object Blob]';
  675. }
  676. function isBoolean(value) {
  677. return typeof value === 'boolean';
  678. }
  679. function isPromiseLike(obj) {
  680. return obj && isFunction(obj.then);
  681. }
  682. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  683. function isTypedArray(value) {
  684. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  685. }
  686. function isArrayBuffer(obj) {
  687. return toString.call(obj) === '[object ArrayBuffer]';
  688. }
  689. var trim = function(value) {
  690. return isString(value) ? value.trim() : value;
  691. };
  692. // Copied from:
  693. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  694. // Prereq: s is a string.
  695. var escapeForRegexp = function(s) {
  696. return s
  697. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  698. // eslint-disable-next-line no-control-regex
  699. .replace(/\x08/g, '\\x08');
  700. };
  701. /**
  702. * @ngdoc function
  703. * @name angular.isElement
  704. * @module ng
  705. * @kind function
  706. *
  707. * @description
  708. * Determines if a reference is a DOM element (or wrapped jQuery element).
  709. *
  710. * @param {*} value Reference to check.
  711. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  712. */
  713. function isElement(node) {
  714. return !!(node &&
  715. (node.nodeName // We are a direct element.
  716. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  717. }
  718. /**
  719. * @param str 'key1,key2,...'
  720. * @returns {object} in the form of {key1:true, key2:true, ...}
  721. */
  722. function makeMap(str) {
  723. var obj = {}, items = str.split(','), i;
  724. for (i = 0; i < items.length; i++) {
  725. obj[items[i]] = true;
  726. }
  727. return obj;
  728. }
  729. function nodeName_(element) {
  730. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  731. }
  732. function includes(array, obj) {
  733. return Array.prototype.indexOf.call(array, obj) !== -1;
  734. }
  735. function arrayRemove(array, value) {
  736. var index = array.indexOf(value);
  737. if (index >= 0) {
  738. array.splice(index, 1);
  739. }
  740. return index;
  741. }
  742. /**
  743. * @ngdoc function
  744. * @name angular.copy
  745. * @module ng
  746. * @kind function
  747. *
  748. * @description
  749. * Creates a deep copy of `source`, which should be an object or an array.
  750. *
  751. * * If no destination is supplied, a copy of the object or array is created.
  752. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  753. * are deleted and then all elements/properties from the source are copied to it.
  754. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  755. * * If `source` is identical to `destination` an exception will be thrown.
  756. *
  757. * <br />
  758. * <div class="alert alert-warning">
  759. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  760. * and on `destination`) will be ignored.
  761. * </div>
  762. *
  763. * @param {*} source The source that will be used to make a copy.
  764. * Can be any type, including primitives, `null`, and `undefined`.
  765. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  766. * provided, must be of the same type as `source`.
  767. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  768. *
  769. * @example
  770. <example module="copyExample" name="angular-copy">
  771. <file name="index.html">
  772. <div ng-controller="ExampleController">
  773. <form novalidate class="simple-form">
  774. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  775. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  776. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  777. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  778. <button ng-click="reset()">RESET</button>
  779. <button ng-click="update(user)">SAVE</button>
  780. </form>
  781. <pre>form = {{user | json}}</pre>
  782. <pre>master = {{master | json}}</pre>
  783. </div>
  784. </file>
  785. <file name="script.js">
  786. // Module: copyExample
  787. angular.
  788. module('copyExample', []).
  789. controller('ExampleController', ['$scope', function($scope) {
  790. $scope.master = {};
  791. $scope.reset = function() {
  792. // Example with 1 argument
  793. $scope.user = angular.copy($scope.master);
  794. };
  795. $scope.update = function(user) {
  796. // Example with 2 arguments
  797. angular.copy(user, $scope.master);
  798. };
  799. $scope.reset();
  800. }]);
  801. </file>
  802. </example>
  803. */
  804. function copy(source, destination) {
  805. var stackSource = [];
  806. var stackDest = [];
  807. if (destination) {
  808. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  809. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  810. }
  811. if (source === destination) {
  812. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  813. }
  814. // Empty the destination object
  815. if (isArray(destination)) {
  816. destination.length = 0;
  817. } else {
  818. forEach(destination, function(value, key) {
  819. if (key !== '$$hashKey') {
  820. delete destination[key];
  821. }
  822. });
  823. }
  824. stackSource.push(source);
  825. stackDest.push(destination);
  826. return copyRecurse(source, destination);
  827. }
  828. return copyElement(source);
  829. function copyRecurse(source, destination) {
  830. var h = destination.$$hashKey;
  831. var key;
  832. if (isArray(source)) {
  833. for (var i = 0, ii = source.length; i < ii; i++) {
  834. destination.push(copyElement(source[i]));
  835. }
  836. } else if (isBlankObject(source)) {
  837. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  838. for (key in source) {
  839. destination[key] = copyElement(source[key]);
  840. }
  841. } else if (source && typeof source.hasOwnProperty === 'function') {
  842. // Slow path, which must rely on hasOwnProperty
  843. for (key in source) {
  844. if (source.hasOwnProperty(key)) {
  845. destination[key] = copyElement(source[key]);
  846. }
  847. }
  848. } else {
  849. // Slowest path --- hasOwnProperty can't be called as a method
  850. for (key in source) {
  851. if (hasOwnProperty.call(source, key)) {
  852. destination[key] = copyElement(source[key]);
  853. }
  854. }
  855. }
  856. setHashKey(destination, h);
  857. return destination;
  858. }
  859. function copyElement(source) {
  860. // Simple values
  861. if (!isObject(source)) {
  862. return source;
  863. }
  864. // Already copied values
  865. var index = stackSource.indexOf(source);
  866. if (index !== -1) {
  867. return stackDest[index];
  868. }
  869. if (isWindow(source) || isScope(source)) {
  870. throw ngMinErr('cpws',
  871. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  872. }
  873. var needsRecurse = false;
  874. var destination = copyType(source);
  875. if (destination === undefined) {
  876. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  877. needsRecurse = true;
  878. }
  879. stackSource.push(source);
  880. stackDest.push(destination);
  881. return needsRecurse
  882. ? copyRecurse(source, destination)
  883. : destination;
  884. }
  885. function copyType(source) {
  886. switch (toString.call(source)) {
  887. case '[object Int8Array]':
  888. case '[object Int16Array]':
  889. case '[object Int32Array]':
  890. case '[object Float32Array]':
  891. case '[object Float64Array]':
  892. case '[object Uint8Array]':
  893. case '[object Uint8ClampedArray]':
  894. case '[object Uint16Array]':
  895. case '[object Uint32Array]':
  896. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  897. case '[object ArrayBuffer]':
  898. // Support: IE10
  899. if (!source.slice) {
  900. // If we're in this case we know the environment supports ArrayBuffer
  901. /* eslint-disable no-undef */
  902. var copied = new ArrayBuffer(source.byteLength);
  903. new Uint8Array(copied).set(new Uint8Array(source));
  904. /* eslint-enable */
  905. return copied;
  906. }
  907. return source.slice(0);
  908. case '[object Boolean]':
  909. case '[object Number]':
  910. case '[object String]':
  911. case '[object Date]':
  912. return new source.constructor(source.valueOf());
  913. case '[object RegExp]':
  914. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  915. re.lastIndex = source.lastIndex;
  916. return re;
  917. case '[object Blob]':
  918. return new source.constructor([source], {type: source.type});
  919. }
  920. if (isFunction(source.cloneNode)) {
  921. return source.cloneNode(true);
  922. }
  923. }
  924. }
  925. /**
  926. * @ngdoc function
  927. * @name angular.equals
  928. * @module ng
  929. * @kind function
  930. *
  931. * @description
  932. * Determines if two objects or two values are equivalent. Supports value types, regular
  933. * expressions, arrays and objects.
  934. *
  935. * Two objects or values are considered equivalent if at least one of the following is true:
  936. *
  937. * * Both objects or values pass `===` comparison.
  938. * * Both objects or values are of the same type and all of their properties are equal by
  939. * comparing them with `angular.equals`.
  940. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  941. * * Both values represent the same regular expression (In JavaScript,
  942. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  943. * representation matches).
  944. *
  945. * During a property comparison, properties of `function` type and properties with names
  946. * that begin with `$` are ignored.
  947. *
  948. * Scope and DOMWindow objects are being compared only by identify (`===`).
  949. *
  950. * @param {*} o1 Object or value to compare.
  951. * @param {*} o2 Object or value to compare.
  952. * @returns {boolean} True if arguments are equal.
  953. *
  954. * @example
  955. <example module="equalsExample" name="equalsExample">
  956. <file name="index.html">
  957. <div ng-controller="ExampleController">
  958. <form novalidate>
  959. <h3>User 1</h3>
  960. Name: <input type="text" ng-model="user1.name">
  961. Age: <input type="number" ng-model="user1.age">
  962. <h3>User 2</h3>
  963. Name: <input type="text" ng-model="user2.name">
  964. Age: <input type="number" ng-model="user2.age">
  965. <div>
  966. <br/>
  967. <input type="button" value="Compare" ng-click="compare()">
  968. </div>
  969. User 1: <pre>{{user1 | json}}</pre>
  970. User 2: <pre>{{user2 | json}}</pre>
  971. Equal: <pre>{{result}}</pre>
  972. </form>
  973. </div>
  974. </file>
  975. <file name="script.js">
  976. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  977. $scope.user1 = {};
  978. $scope.user2 = {};
  979. $scope.compare = function() {
  980. $scope.result = angular.equals($scope.user1, $scope.user2);
  981. };
  982. }]);
  983. </file>
  984. </example>
  985. */
  986. function equals(o1, o2) {
  987. if (o1 === o2) return true;
  988. if (o1 === null || o2 === null) return false;
  989. // eslint-disable-next-line no-self-compare
  990. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  991. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  992. if (t1 === t2 && t1 === 'object') {
  993. if (isArray(o1)) {
  994. if (!isArray(o2)) return false;
  995. if ((length = o1.length) === o2.length) {
  996. for (key = 0; key < length; key++) {
  997. if (!equals(o1[key], o2[key])) return false;
  998. }
  999. return true;
  1000. }
  1001. } else if (isDate(o1)) {
  1002. if (!isDate(o2)) return false;
  1003. return equals(o1.getTime(), o2.getTime());
  1004. } else if (isRegExp(o1)) {
  1005. if (!isRegExp(o2)) return false;
  1006. return o1.toString() === o2.toString();
  1007. } else {
  1008. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1009. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1010. keySet = createMap();
  1011. for (key in o1) {
  1012. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1013. if (!equals(o1[key], o2[key])) return false;
  1014. keySet[key] = true;
  1015. }
  1016. for (key in o2) {
  1017. if (!(key in keySet) &&
  1018. key.charAt(0) !== '$' &&
  1019. isDefined(o2[key]) &&
  1020. !isFunction(o2[key])) return false;
  1021. }
  1022. return true;
  1023. }
  1024. }
  1025. return false;
  1026. }
  1027. var csp = function() {
  1028. if (!isDefined(csp.rules)) {
  1029. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1030. window.document.querySelector('[data-ng-csp]'));
  1031. if (ngCspElement) {
  1032. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1033. ngCspElement.getAttribute('data-ng-csp');
  1034. csp.rules = {
  1035. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1036. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1037. };
  1038. } else {
  1039. csp.rules = {
  1040. noUnsafeEval: noUnsafeEval(),
  1041. noInlineStyle: false
  1042. };
  1043. }
  1044. }
  1045. return csp.rules;
  1046. function noUnsafeEval() {
  1047. try {
  1048. // eslint-disable-next-line no-new, no-new-func
  1049. new Function('');
  1050. return false;
  1051. } catch (e) {
  1052. return true;
  1053. }
  1054. }
  1055. };
  1056. /**
  1057. * @ngdoc directive
  1058. * @module ng
  1059. * @name ngJq
  1060. *
  1061. * @element ANY
  1062. * @param {string=} ngJq the name of the library available under `window`
  1063. * to be used for angular.element
  1064. * @description
  1065. * Use this directive to force the angular.element library. This should be
  1066. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1067. * the jquery variable under window (eg. jQuery).
  1068. *
  1069. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1070. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1071. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1072. * others ignored.
  1073. *
  1074. * @example
  1075. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1076. ```html
  1077. <!doctype html>
  1078. <html ng-app ng-jq>
  1079. ...
  1080. ...
  1081. </html>
  1082. ```
  1083. * @example
  1084. * This example shows how to use a jQuery based library of a different name.
  1085. * The library name must be available at the top most 'window'.
  1086. ```html
  1087. <!doctype html>
  1088. <html ng-app ng-jq="jQueryLib">
  1089. ...
  1090. ...
  1091. </html>
  1092. ```
  1093. */
  1094. var jq = function() {
  1095. if (isDefined(jq.name_)) return jq.name_;
  1096. var el;
  1097. var i, ii = ngAttrPrefixes.length, prefix, name;
  1098. for (i = 0; i < ii; ++i) {
  1099. prefix = ngAttrPrefixes[i];
  1100. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1101. if (el) {
  1102. name = el.getAttribute(prefix + 'jq');
  1103. break;
  1104. }
  1105. }
  1106. return (jq.name_ = name);
  1107. };
  1108. function concat(array1, array2, index) {
  1109. return array1.concat(slice.call(array2, index));
  1110. }
  1111. function sliceArgs(args, startIndex) {
  1112. return slice.call(args, startIndex || 0);
  1113. }
  1114. /**
  1115. * @ngdoc function
  1116. * @name angular.bind
  1117. * @module ng
  1118. * @kind function
  1119. *
  1120. * @description
  1121. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1122. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1123. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1124. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1125. *
  1126. * @param {Object} self Context which `fn` should be evaluated in.
  1127. * @param {function()} fn Function to be bound.
  1128. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1129. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1130. */
  1131. function bind(self, fn) {
  1132. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1133. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1134. return curryArgs.length
  1135. ? function() {
  1136. return arguments.length
  1137. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1138. : fn.apply(self, curryArgs);
  1139. }
  1140. : function() {
  1141. return arguments.length
  1142. ? fn.apply(self, arguments)
  1143. : fn.call(self);
  1144. };
  1145. } else {
  1146. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1147. return fn;
  1148. }
  1149. }
  1150. function toJsonReplacer(key, value) {
  1151. var val = value;
  1152. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1153. val = undefined;
  1154. } else if (isWindow(value)) {
  1155. val = '$WINDOW';
  1156. } else if (value && window.document === value) {
  1157. val = '$DOCUMENT';
  1158. } else if (isScope(value)) {
  1159. val = '$SCOPE';
  1160. }
  1161. return val;
  1162. }
  1163. /**
  1164. * @ngdoc function
  1165. * @name angular.toJson
  1166. * @module ng
  1167. * @kind function
  1168. *
  1169. * @description
  1170. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1171. * stripped since angular uses this notation internally.
  1172. *
  1173. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1174. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1175. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1176. * @returns {string|undefined} JSON-ified string representing `obj`.
  1177. * @knownIssue
  1178. *
  1179. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1180. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1181. * `Date.prototype.toJSON` method as follows:
  1182. *
  1183. * ```
  1184. * var _DatetoJSON = Date.prototype.toJSON;
  1185. * Date.prototype.toJSON = function() {
  1186. * try {
  1187. * return _DatetoJSON.call(this);
  1188. * } catch(e) {
  1189. * if (e instanceof RangeError) {
  1190. * return null;
  1191. * }
  1192. * throw e;
  1193. * }
  1194. * };
  1195. * ```
  1196. *
  1197. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1198. */
  1199. function toJson(obj, pretty) {
  1200. if (isUndefined(obj)) return undefined;
  1201. if (!isNumber(pretty)) {
  1202. pretty = pretty ? 2 : null;
  1203. }
  1204. return JSON.stringify(obj, toJsonReplacer, pretty);
  1205. }
  1206. /**
  1207. * @ngdoc function
  1208. * @name angular.fromJson
  1209. * @module ng
  1210. * @kind function
  1211. *
  1212. * @description
  1213. * Deserializes a JSON string.
  1214. *
  1215. * @param {string} json JSON string to deserialize.
  1216. * @returns {Object|Array|string|number} Deserialized JSON string.
  1217. */
  1218. function fromJson(json) {
  1219. return isString(json)
  1220. ? JSON.parse(json)
  1221. : json;
  1222. }
  1223. var ALL_COLONS = /:/g;
  1224. function timezoneToOffset(timezone, fallback) {
  1225. // Support: IE 9-11 only, Edge 13-14+
  1226. // IE/Edge do not "understand" colon (`:`) in timezone
  1227. timezone = timezone.replace(ALL_COLONS, '');
  1228. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1229. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1230. }
  1231. function addDateMinutes(date, minutes) {
  1232. date = new Date(date.getTime());
  1233. date.setMinutes(date.getMinutes() + minutes);
  1234. return date;
  1235. }
  1236. function convertTimezoneToLocal(date, timezone, reverse) {
  1237. reverse = reverse ? -1 : 1;
  1238. var dateTimezoneOffset = date.getTimezoneOffset();
  1239. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1240. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1241. }
  1242. /**
  1243. * @returns {string} Returns the string representation of the element.
  1244. */
  1245. function startingTag(element) {
  1246. element = jqLite(element).clone();
  1247. try {
  1248. // turns out IE does not let you set .html() on elements which
  1249. // are not allowed to have children. So we just ignore it.
  1250. element.empty();
  1251. } catch (e) { /* empty */ }
  1252. var elemHtml = jqLite('<div>').append(element).html();
  1253. try {
  1254. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1255. elemHtml.
  1256. match(/^(<[^>]+>)/)[1].
  1257. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1258. } catch (e) {
  1259. return lowercase(elemHtml);
  1260. }
  1261. }
  1262. /////////////////////////////////////////////////
  1263. /**
  1264. * Tries to decode the URI component without throwing an exception.
  1265. *
  1266. * @private
  1267. * @param str value potential URI component to check.
  1268. * @returns {boolean} True if `value` can be decoded
  1269. * with the decodeURIComponent function.
  1270. */
  1271. function tryDecodeURIComponent(value) {
  1272. try {
  1273. return decodeURIComponent(value);
  1274. } catch (e) {
  1275. // Ignore any invalid uri component.
  1276. }
  1277. }
  1278. /**
  1279. * Parses an escaped url query string into key-value pairs.
  1280. * @returns {Object.<string,boolean|Array>}
  1281. */
  1282. function parseKeyValue(/**string*/keyValue) {
  1283. var obj = {};
  1284. forEach((keyValue || '').split('&'), function(keyValue) {
  1285. var splitPoint, key, val;
  1286. if (keyValue) {
  1287. key = keyValue = keyValue.replace(/\+/g,'%20');
  1288. splitPoint = keyValue.indexOf('=');
  1289. if (splitPoint !== -1) {
  1290. key = keyValue.substring(0, splitPoint);
  1291. val = keyValue.substring(splitPoint + 1);
  1292. }
  1293. key = tryDecodeURIComponent(key);
  1294. if (isDefined(key)) {
  1295. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1296. if (!hasOwnProperty.call(obj, key)) {
  1297. obj[key] = val;
  1298. } else if (isArray(obj[key])) {
  1299. obj[key].push(val);
  1300. } else {
  1301. obj[key] = [obj[key],val];
  1302. }
  1303. }
  1304. }
  1305. });
  1306. return obj;
  1307. }
  1308. function toKeyValue(obj) {
  1309. var parts = [];
  1310. forEach(obj, function(value, key) {
  1311. if (isArray(value)) {
  1312. forEach(value, function(arrayValue) {
  1313. parts.push(encodeUriQuery(key, true) +
  1314. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1315. });
  1316. } else {
  1317. parts.push(encodeUriQuery(key, true) +
  1318. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1319. }
  1320. });
  1321. return parts.length ? parts.join('&') : '';
  1322. }
  1323. /**
  1324. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1325. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1326. * segments:
  1327. * segment = *pchar
  1328. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1329. * pct-encoded = "%" HEXDIG HEXDIG
  1330. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1331. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1332. * / "*" / "+" / "," / ";" / "="
  1333. */
  1334. function encodeUriSegment(val) {
  1335. return encodeUriQuery(val, true).
  1336. replace(/%26/gi, '&').
  1337. replace(/%3D/gi, '=').
  1338. replace(/%2B/gi, '+');
  1339. }
  1340. /**
  1341. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1342. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1343. * encoded per http://tools.ietf.org/html/rfc3986:
  1344. * query = *( pchar / "/" / "?" )
  1345. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1346. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1347. * pct-encoded = "%" HEXDIG HEXDIG
  1348. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1349. * / "*" / "+" / "," / ";" / "="
  1350. */
  1351. function encodeUriQuery(val, pctEncodeSpaces) {
  1352. return encodeURIComponent(val).
  1353. replace(/%40/gi, '@').
  1354. replace(/%3A/gi, ':').
  1355. replace(/%24/g, '$').
  1356. replace(/%2C/gi, ',').
  1357. replace(/%3B/gi, ';').
  1358. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1359. }
  1360. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1361. function getNgAttribute(element, ngAttr) {
  1362. var attr, i, ii = ngAttrPrefixes.length;
  1363. for (i = 0; i < ii; ++i) {
  1364. attr = ngAttrPrefixes[i] + ngAttr;
  1365. if (isString(attr = element.getAttribute(attr))) {
  1366. return attr;
  1367. }
  1368. }
  1369. return null;
  1370. }
  1371. function allowAutoBootstrap(document) {
  1372. if (!document.currentScript) {
  1373. return true;
  1374. }
  1375. var src = document.currentScript.getAttribute('src');
  1376. var link = document.createElement('a');
  1377. link.href = src;
  1378. if (document.location.origin === link.origin) {
  1379. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1380. return true;
  1381. }
  1382. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1383. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1384. // content security policy in web pages and other browser extensions.
  1385. switch (link.protocol) {
  1386. case 'http:':
  1387. case 'https:':
  1388. case 'ftp:':
  1389. case 'blob:':
  1390. case 'file:':
  1391. case 'data:':
  1392. return true;
  1393. default:
  1394. return false;
  1395. }
  1396. }
  1397. // Cached as it has to run during loading so that document.currentScript is available.
  1398. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1399. /**
  1400. * @ngdoc directive
  1401. * @name ngApp
  1402. * @module ng
  1403. *
  1404. * @element ANY
  1405. * @param {angular.Module} ngApp an optional application
  1406. * {@link angular.module module} name to load.
  1407. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1408. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1409. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1410. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1411. * tracking down the root of these bugs.
  1412. *
  1413. * @description
  1414. *
  1415. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1416. * designates the **root element** of the application and is typically placed near the root element
  1417. * of the page - e.g. on the `<body>` or `<html>` tags.
  1418. *
  1419. * There are a few things to keep in mind when using `ngApp`:
  1420. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1421. * found in the document will be used to define the root element to auto-bootstrap as an
  1422. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1423. * {@link angular.bootstrap} instead.
  1424. * - AngularJS applications cannot be nested within each other.
  1425. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1426. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1427. * {@link ngRoute.ngView `ngView`}.
  1428. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1429. * causing animations to stop working and making the injector inaccessible from outside the app.
  1430. *
  1431. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1432. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1433. * should contain the application code needed or have dependencies on other modules that will
  1434. * contain the code. See {@link angular.module} for more information.
  1435. *
  1436. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1437. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1438. * would not be resolved to `3`.
  1439. *
  1440. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1441. *
  1442. <example module="ngAppDemo" name="ng-app">
  1443. <file name="index.html">
  1444. <div ng-controller="ngAppDemoController">
  1445. I can add: {{a}} + {{b}} = {{ a+b }}
  1446. </div>
  1447. </file>
  1448. <file name="script.js">
  1449. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1450. $scope.a = 1;
  1451. $scope.b = 2;
  1452. });
  1453. </file>
  1454. </example>
  1455. *
  1456. * Using `ngStrictDi`, you would see something like this:
  1457. *
  1458. <example ng-app-included="true" name="strict-di">
  1459. <file name="index.html">
  1460. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1461. <div ng-controller="GoodController1">
  1462. I can add: {{a}} + {{b}} = {{ a+b }}
  1463. <p>This renders because the controller does not fail to
  1464. instantiate, by using explicit annotation style (see
  1465. script.js for details)
  1466. </p>
  1467. </div>
  1468. <div ng-controller="GoodController2">
  1469. Name: <input ng-model="name"><br />
  1470. Hello, {{name}}!
  1471. <p>This renders because the controller does not fail to
  1472. instantiate, by using explicit annotation style
  1473. (see script.js for details)
  1474. </p>
  1475. </div>
  1476. <div ng-controller="BadController">
  1477. I can add: {{a}} + {{b}} = {{ a+b }}
  1478. <p>The controller could not be instantiated, due to relying
  1479. on automatic function annotations (which are disabled in
  1480. strict mode). As such, the content of this section is not
  1481. interpolated, and there should be an error in your web console.
  1482. </p>
  1483. </div>
  1484. </div>
  1485. </file>
  1486. <file name="script.js">
  1487. angular.module('ngAppStrictDemo', [])
  1488. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1489. // rather than an explicit annotation
  1490. .controller('BadController', function($scope) {
  1491. $scope.a = 1;
  1492. $scope.b = 2;
  1493. })
  1494. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1495. // due to using explicit annotations using the array style and $inject property, respectively.
  1496. .controller('GoodController1', ['$scope', function($scope) {
  1497. $scope.a = 1;
  1498. $scope.b = 2;
  1499. }])
  1500. .controller('GoodController2', GoodController2);
  1501. function GoodController2($scope) {
  1502. $scope.name = 'World';
  1503. }
  1504. GoodController2.$inject = ['$scope'];
  1505. </file>
  1506. <file name="style.css">
  1507. div[ng-controller] {
  1508. margin-bottom: 1em;
  1509. -webkit-border-radius: 4px;
  1510. border-radius: 4px;
  1511. border: 1px solid;
  1512. padding: .5em;
  1513. }
  1514. div[ng-controller^=Good] {
  1515. border-color: #d6e9c6;
  1516. background-color: #dff0d8;
  1517. color: #3c763d;
  1518. }
  1519. div[ng-controller^=Bad] {
  1520. border-color: #ebccd1;
  1521. background-color: #f2dede;
  1522. color: #a94442;
  1523. margin-bottom: 0;
  1524. }
  1525. </file>
  1526. </example>
  1527. */
  1528. function angularInit(element, bootstrap) {
  1529. var appElement,
  1530. module,
  1531. config = {};
  1532. // The element `element` has priority over any other element.
  1533. forEach(ngAttrPrefixes, function(prefix) {
  1534. var name = prefix + 'app';
  1535. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1536. appElement = element;
  1537. module = element.getAttribute(name);
  1538. }
  1539. });
  1540. forEach(ngAttrPrefixes, function(prefix) {
  1541. var name = prefix + 'app';
  1542. var candidate;
  1543. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1544. appElement = candidate;
  1545. module = candidate.getAttribute(name);
  1546. }
  1547. });
  1548. if (appElement) {
  1549. if (!isAutoBootstrapAllowed) {
  1550. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1551. 'an extension, document.location.href does not match.');
  1552. return;
  1553. }
  1554. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1555. bootstrap(appElement, module ? [module] : [], config);
  1556. }
  1557. }
  1558. /**
  1559. * @ngdoc function
  1560. * @name angular.bootstrap
  1561. * @module ng
  1562. * @description
  1563. * Use this function to manually start up angular application.
  1564. *
  1565. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1566. *
  1567. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1568. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1569. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1570. * multiple instances of Angular try to work on the DOM.
  1571. *
  1572. * <div class="alert alert-warning">
  1573. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1574. * They must use {@link ng.directive:ngApp ngApp}.
  1575. * </div>
  1576. *
  1577. * <div class="alert alert-warning">
  1578. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1579. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1580. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1581. * causing animations to stop working and making the injector inaccessible from outside the app.
  1582. * </div>
  1583. *
  1584. * ```html
  1585. * <!doctype html>
  1586. * <html>
  1587. * <body>
  1588. * <div ng-controller="WelcomeController">
  1589. * {{greeting}}
  1590. * </div>
  1591. *
  1592. * <script src="angular.js"></script>
  1593. * <script>
  1594. * var app = angular.module('demo', [])
  1595. * .controller('WelcomeController', function($scope) {
  1596. * $scope.greeting = 'Welcome!';
  1597. * });
  1598. * angular.bootstrap(document, ['demo']);
  1599. * </script>
  1600. * </body>
  1601. * </html>
  1602. * ```
  1603. *
  1604. * @param {DOMElement} element DOM element which is the root of angular application.
  1605. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1606. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1607. * function that will be invoked by the injector as a `config` block.
  1608. * See: {@link angular.module modules}
  1609. * @param {Object=} config an object for defining configuration options for the application. The
  1610. * following keys are supported:
  1611. *
  1612. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1613. * assist in finding bugs which break minified code. Defaults to `false`.
  1614. *
  1615. * @returns {auto.$injector} Returns the newly created injector for this app.
  1616. */
  1617. function bootstrap(element, modules, config) {
  1618. if (!isObject(config)) config = {};
  1619. var defaultConfig = {
  1620. strictDi: false
  1621. };
  1622. config = extend(defaultConfig, config);
  1623. var doBootstrap = function() {
  1624. element = jqLite(element);
  1625. if (element.injector()) {
  1626. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1627. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1628. throw ngMinErr(
  1629. 'btstrpd',
  1630. 'App already bootstrapped with this element \'{0}\'',
  1631. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1632. }
  1633. modules = modules || [];
  1634. modules.unshift(['$provide', function($provide) {
  1635. $provide.value('$rootElement', element);
  1636. }]);
  1637. if (config.debugInfoEnabled) {
  1638. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1639. modules.push(['$compileProvider', function($compileProvider) {
  1640. $compileProvider.debugInfoEnabled(true);
  1641. }]);
  1642. }
  1643. modules.unshift('ng');
  1644. var injector = createInjector(modules, config.strictDi);
  1645. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1646. function bootstrapApply(scope, element, compile, injector) {
  1647. scope.$apply(function() {
  1648. element.data('$injector', injector);
  1649. compile(element)(scope);
  1650. });
  1651. }]
  1652. );
  1653. return injector;
  1654. };
  1655. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1656. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1657. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1658. config.debugInfoEnabled = true;
  1659. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1660. }
  1661. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1662. return doBootstrap();
  1663. }
  1664. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1665. angular.resumeBootstrap = function(extraModules) {
  1666. forEach(extraModules, function(module) {
  1667. modules.push(module);
  1668. });
  1669. return doBootstrap();
  1670. };
  1671. if (isFunction(angular.resumeDeferredBootstrap)) {
  1672. angular.resumeDeferredBootstrap();
  1673. }
  1674. }
  1675. /**
  1676. * @ngdoc function
  1677. * @name angular.reloadWithDebugInfo
  1678. * @module ng
  1679. * @description
  1680. * Use this function to reload the current application with debug information turned on.
  1681. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1682. *
  1683. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1684. */
  1685. function reloadWithDebugInfo() {
  1686. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1687. window.location.reload();
  1688. }
  1689. /**
  1690. * @name angular.getTestability
  1691. * @module ng
  1692. * @description
  1693. * Get the testability service for the instance of Angular on the given
  1694. * element.
  1695. * @param {DOMElement} element DOM element which is the root of angular application.
  1696. */
  1697. function getTestability(rootElement) {
  1698. var injector = angular.element(rootElement).injector();
  1699. if (!injector) {
  1700. throw ngMinErr('test',
  1701. 'no injector found for element argument to getTestability');
  1702. }
  1703. return injector.get('$$testability');
  1704. }
  1705. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1706. function snake_case(name, separator) {
  1707. separator = separator || '_';
  1708. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1709. return (pos ? separator : '') + letter.toLowerCase();
  1710. });
  1711. }
  1712. var bindJQueryFired = false;
  1713. function bindJQuery() {
  1714. var originalCleanData;
  1715. if (bindJQueryFired) {
  1716. return;
  1717. }
  1718. // bind to jQuery if present;
  1719. var jqName = jq();
  1720. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1721. !jqName ? undefined : // use jqLite
  1722. window[jqName]; // use jQuery specified by `ngJq`
  1723. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1724. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1725. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1726. // versions. It will not work for sure with jQuery <1.7, though.
  1727. if (jQuery && jQuery.fn.on) {
  1728. jqLite = jQuery;
  1729. extend(jQuery.fn, {
  1730. scope: JQLitePrototype.scope,
  1731. isolateScope: JQLitePrototype.isolateScope,
  1732. controller: JQLitePrototype.controller,
  1733. injector: JQLitePrototype.injector,
  1734. inheritedData: JQLitePrototype.inheritedData
  1735. });
  1736. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1737. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1738. // the $destroy event on all removed nodes.
  1739. originalCleanData = jQuery.cleanData;
  1740. jQuery.cleanData = function(elems) {
  1741. var events;
  1742. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1743. events = jQuery._data(elem, 'events');
  1744. if (events && events.$destroy) {
  1745. jQuery(elem).triggerHandler('$destroy');
  1746. }
  1747. }
  1748. originalCleanData(elems);
  1749. };
  1750. } else {
  1751. jqLite = JQLite;
  1752. }
  1753. angular.element = jqLite;
  1754. // Prevent double-proxying.
  1755. bindJQueryFired = true;
  1756. }
  1757. /**
  1758. * throw error if the argument is falsy.
  1759. */
  1760. function assertArg(arg, name, reason) {
  1761. if (!arg) {
  1762. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1763. }
  1764. return arg;
  1765. }
  1766. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1767. if (acceptArrayAnnotation && isArray(arg)) {
  1768. arg = arg[arg.length - 1];
  1769. }
  1770. assertArg(isFunction(arg), name, 'not a function, got ' +
  1771. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1772. return arg;
  1773. }
  1774. /**
  1775. * throw error if the name given is hasOwnProperty
  1776. * @param {String} name the name to test
  1777. * @param {String} context the context in which the name is used, such as module or directive
  1778. */
  1779. function assertNotHasOwnProperty(name, context) {
  1780. if (name === 'hasOwnProperty') {
  1781. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1782. }
  1783. }
  1784. /**
  1785. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1786. * @param {Object} obj starting object
  1787. * @param {String} path path to traverse
  1788. * @param {boolean} [bindFnToScope=true]
  1789. * @returns {Object} value as accessible by path
  1790. */
  1791. //TODO(misko): this function needs to be removed
  1792. function getter(obj, path, bindFnToScope) {
  1793. if (!path) return obj;
  1794. var keys = path.split('.');
  1795. var key;
  1796. var lastInstance = obj;
  1797. var len = keys.length;
  1798. for (var i = 0; i < len; i++) {
  1799. key = keys[i];
  1800. if (obj) {
  1801. obj = (lastInstance = obj)[key];
  1802. }
  1803. }
  1804. if (!bindFnToScope && isFunction(obj)) {
  1805. return bind(lastInstance, obj);
  1806. }
  1807. return obj;
  1808. }
  1809. /**
  1810. * Return the DOM siblings between the first and last node in the given array.
  1811. * @param {Array} array like object
  1812. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1813. */
  1814. function getBlockNodes(nodes) {
  1815. // TODO(perf): update `nodes` instead of creating a new object?
  1816. var node = nodes[0];
  1817. var endNode = nodes[nodes.length - 1];
  1818. var blockNodes;
  1819. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1820. if (blockNodes || nodes[i] !== node) {
  1821. if (!blockNodes) {
  1822. blockNodes = jqLite(slice.call(nodes, 0, i));
  1823. }
  1824. blockNodes.push(node);
  1825. }
  1826. }
  1827. return blockNodes || nodes;
  1828. }
  1829. /**
  1830. * Creates a new object without a prototype. This object is useful for lookup without having to
  1831. * guard against prototypically inherited properties via hasOwnProperty.
  1832. *
  1833. * Related micro-benchmarks:
  1834. * - http://jsperf.com/object-create2
  1835. * - http://jsperf.com/proto-map-lookup/2
  1836. * - http://jsperf.com/for-in-vs-object-keys2
  1837. *
  1838. * @returns {Object}
  1839. */
  1840. function createMap() {
  1841. return Object.create(null);
  1842. }
  1843. function stringify(value) {
  1844. if (value == null) { // null || undefined
  1845. return '';
  1846. }
  1847. switch (typeof value) {
  1848. case 'string':
  1849. break;
  1850. case 'number':
  1851. value = '' + value;
  1852. break;
  1853. default:
  1854. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1855. value = value.toString();
  1856. } else {
  1857. value = toJson(value);
  1858. }
  1859. }
  1860. return value;
  1861. }
  1862. var NODE_TYPE_ELEMENT = 1;
  1863. var NODE_TYPE_ATTRIBUTE = 2;
  1864. var NODE_TYPE_TEXT = 3;
  1865. var NODE_TYPE_COMMENT = 8;
  1866. var NODE_TYPE_DOCUMENT = 9;
  1867. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1868. /**
  1869. * @ngdoc type
  1870. * @name angular.Module
  1871. * @module ng
  1872. * @description
  1873. *
  1874. * Interface for configuring angular {@link angular.module modules}.
  1875. */
  1876. function setupModuleLoader(window) {
  1877. var $injectorMinErr = minErr('$injector');
  1878. var ngMinErr = minErr('ng');
  1879. function ensure(obj, name, factory) {
  1880. return obj[name] || (obj[name] = factory());
  1881. }
  1882. var angular = ensure(window, 'angular', Object);
  1883. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1884. angular.$$minErr = angular.$$minErr || minErr;
  1885. return ensure(angular, 'module', function() {
  1886. /** @type {Object.<string, angular.Module>} */
  1887. var modules = {};
  1888. /**
  1889. * @ngdoc function
  1890. * @name angular.module
  1891. * @module ng
  1892. * @description
  1893. *
  1894. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1895. * modules.
  1896. * All modules (angular core or 3rd party) that should be available to an application must be
  1897. * registered using this mechanism.
  1898. *
  1899. * Passing one argument retrieves an existing {@link angular.Module},
  1900. * whereas passing more than one argument creates a new {@link angular.Module}
  1901. *
  1902. *
  1903. * # Module
  1904. *
  1905. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1906. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1907. *
  1908. * ```js
  1909. * // Create a new module
  1910. * var myModule = angular.module('myModule', []);
  1911. *
  1912. * // register a new service
  1913. * myModule.value('appName', 'MyCoolApp');
  1914. *
  1915. * // configure existing services inside initialization blocks.
  1916. * myModule.config(['$locationProvider', function($locationProvider) {
  1917. * // Configure existing providers
  1918. * $locationProvider.hashPrefix('!');
  1919. * }]);
  1920. * ```
  1921. *
  1922. * Then you can create an injector and load your modules like this:
  1923. *
  1924. * ```js
  1925. * var injector = angular.injector(['ng', 'myModule'])
  1926. * ```
  1927. *
  1928. * However it's more likely that you'll just use
  1929. * {@link ng.directive:ngApp ngApp} or
  1930. * {@link angular.bootstrap} to simplify this process for you.
  1931. *
  1932. * @param {!string} name The name of the module to create or retrieve.
  1933. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1934. * unspecified then the module is being retrieved for further configuration.
  1935. * @param {Function=} configFn Optional configuration function for the module. Same as
  1936. * {@link angular.Module#config Module#config()}.
  1937. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1938. */
  1939. return function module(name, requires, configFn) {
  1940. var assertNotHasOwnProperty = function(name, context) {
  1941. if (name === 'hasOwnProperty') {
  1942. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1943. }
  1944. };
  1945. assertNotHasOwnProperty(name, 'module');
  1946. if (requires && modules.hasOwnProperty(name)) {
  1947. modules[name] = null;
  1948. }
  1949. return ensure(modules, name, function() {
  1950. if (!requires) {
  1951. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  1952. 'the module name or forgot to load it. If registering a module ensure that you ' +
  1953. 'specify the dependencies as the second argument.', name);
  1954. }
  1955. /** @type {!Array.<Array.<*>>} */
  1956. var invokeQueue = [];
  1957. /** @type {!Array.<Function>} */
  1958. var configBlocks = [];
  1959. /** @type {!Array.<Function>} */
  1960. var runBlocks = [];
  1961. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1962. /** @type {angular.Module} */
  1963. var moduleInstance = {
  1964. // Private state
  1965. _invokeQueue: invokeQueue,
  1966. _configBlocks: configBlocks,
  1967. _runBlocks: runBlocks,
  1968. /**
  1969. * @ngdoc property
  1970. * @name angular.Module#requires
  1971. * @module ng
  1972. *
  1973. * @description
  1974. * Holds the list of modules which the injector will load before the current module is
  1975. * loaded.
  1976. */
  1977. requires: requires,
  1978. /**
  1979. * @ngdoc property
  1980. * @name angular.Module#name
  1981. * @module ng
  1982. *
  1983. * @description
  1984. * Name of the module.
  1985. */
  1986. name: name,
  1987. /**
  1988. * @ngdoc method
  1989. * @name angular.Module#provider
  1990. * @module ng
  1991. * @param {string} name service name
  1992. * @param {Function} providerType Construction function for creating new instance of the
  1993. * service.
  1994. * @description
  1995. * See {@link auto.$provide#provider $provide.provider()}.
  1996. */
  1997. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1998. /**
  1999. * @ngdoc method
  2000. * @name angular.Module#factory
  2001. * @module ng
  2002. * @param {string} name service name
  2003. * @param {Function} providerFunction Function for creating new instance of the service.
  2004. * @description
  2005. * See {@link auto.$provide#factory $provide.factory()}.
  2006. */
  2007. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2008. /**
  2009. * @ngdoc method
  2010. * @name angular.Module#service
  2011. * @module ng
  2012. * @param {string} name service name
  2013. * @param {Function} constructor A constructor function that will be instantiated.
  2014. * @description
  2015. * See {@link auto.$provide#service $provide.service()}.
  2016. */
  2017. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2018. /**
  2019. * @ngdoc method
  2020. * @name angular.Module#value
  2021. * @module ng
  2022. * @param {string} name service name
  2023. * @param {*} object Service instance object.
  2024. * @description
  2025. * See {@link auto.$provide#value $provide.value()}.
  2026. */
  2027. value: invokeLater('$provide', 'value'),
  2028. /**
  2029. * @ngdoc method
  2030. * @name angular.Module#constant
  2031. * @module ng
  2032. * @param {string} name constant name
  2033. * @param {*} object Constant value.
  2034. * @description
  2035. * Because the constants are fixed, they get applied before other provide methods.
  2036. * See {@link auto.$provide#constant $provide.constant()}.
  2037. */
  2038. constant: invokeLater('$provide', 'constant', 'unshift'),
  2039. /**
  2040. * @ngdoc method
  2041. * @name angular.Module#decorator
  2042. * @module ng
  2043. * @param {string} name The name of the service to decorate.
  2044. * @param {Function} decorFn This function will be invoked when the service needs to be
  2045. * instantiated and should return the decorated service instance.
  2046. * @description
  2047. * See {@link auto.$provide#decorator $provide.decorator()}.
  2048. */
  2049. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2050. /**
  2051. * @ngdoc method
  2052. * @name angular.Module#animation
  2053. * @module ng
  2054. * @param {string} name animation name
  2055. * @param {Function} animationFactory Factory function for creating new instance of an
  2056. * animation.
  2057. * @description
  2058. *
  2059. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2060. *
  2061. *
  2062. * Defines an animation hook that can be later used with
  2063. * {@link $animate $animate} service and directives that use this service.
  2064. *
  2065. * ```js
  2066. * module.animation('.animation-name', function($inject1, $inject2) {
  2067. * return {
  2068. * eventName : function(element, done) {
  2069. * //code to run the animation
  2070. * //once complete, then run done()
  2071. * return function cancellationFunction(element) {
  2072. * //code to cancel the animation
  2073. * }
  2074. * }
  2075. * }
  2076. * })
  2077. * ```
  2078. *
  2079. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2080. * {@link ngAnimate ngAnimate module} for more information.
  2081. */
  2082. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2083. /**
  2084. * @ngdoc method
  2085. * @name angular.Module#filter
  2086. * @module ng
  2087. * @param {string} name Filter name - this must be a valid angular expression identifier
  2088. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2089. * @description
  2090. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2091. *
  2092. * <div class="alert alert-warning">
  2093. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2094. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2095. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2096. * (`myapp_subsection_filterx`).
  2097. * </div>
  2098. */
  2099. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2100. /**
  2101. * @ngdoc method
  2102. * @name angular.Module#controller
  2103. * @module ng
  2104. * @param {string|Object} name Controller name, or an object map of controllers where the
  2105. * keys are the names and the values are the constructors.
  2106. * @param {Function} constructor Controller constructor function.
  2107. * @description
  2108. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2109. */
  2110. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2111. /**
  2112. * @ngdoc method
  2113. * @name angular.Module#directive
  2114. * @module ng
  2115. * @param {string|Object} name Directive name, or an object map of directives where the
  2116. * keys are the names and the values are the factories.
  2117. * @param {Function} directiveFactory Factory function for creating new instance of
  2118. * directives.
  2119. * @description
  2120. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2121. */
  2122. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2123. /**
  2124. * @ngdoc method
  2125. * @name angular.Module#component
  2126. * @module ng
  2127. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2128. * @param {Object} options Component definition object (a simplified
  2129. * {@link ng.$compile#directive-definition-object directive definition object})
  2130. *
  2131. * @description
  2132. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2133. */
  2134. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2135. /**
  2136. * @ngdoc method
  2137. * @name angular.Module#config
  2138. * @module ng
  2139. * @param {Function} configFn Execute this function on module load. Useful for service
  2140. * configuration.
  2141. * @description
  2142. * Use this method to register work which needs to be performed on module loading.
  2143. * For more about how to configure services, see
  2144. * {@link providers#provider-recipe Provider Recipe}.
  2145. */
  2146. config: config,
  2147. /**
  2148. * @ngdoc method
  2149. * @name angular.Module#run
  2150. * @module ng
  2151. * @param {Function} initializationFn Execute this function after injector creation.
  2152. * Useful for application initialization.
  2153. * @description
  2154. * Use this method to register work which should be performed when the injector is done
  2155. * loading all modules.
  2156. */
  2157. run: function(block) {
  2158. runBlocks.push(block);
  2159. return this;
  2160. }
  2161. };
  2162. if (configFn) {
  2163. config(configFn);
  2164. }
  2165. return moduleInstance;
  2166. /**
  2167. * @param {string} provider
  2168. * @param {string} method
  2169. * @param {String=} insertMethod
  2170. * @returns {angular.Module}
  2171. */
  2172. function invokeLater(provider, method, insertMethod, queue) {
  2173. if (!queue) queue = invokeQueue;
  2174. return function() {
  2175. queue[insertMethod || 'push']([provider, method, arguments]);
  2176. return moduleInstance;
  2177. };
  2178. }
  2179. /**
  2180. * @param {string} provider
  2181. * @param {string} method
  2182. * @returns {angular.Module}
  2183. */
  2184. function invokeLaterAndSetModuleName(provider, method, queue) {
  2185. if (!queue) queue = invokeQueue;
  2186. return function(recipeName, factoryFunction) {
  2187. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2188. queue.push([provider, method, arguments]);
  2189. return moduleInstance;
  2190. };
  2191. }
  2192. });
  2193. };
  2194. });
  2195. }
  2196. /* global shallowCopy: true */
  2197. /**
  2198. * Creates a shallow copy of an object, an array or a primitive.
  2199. *
  2200. * Assumes that there are no proto properties for objects.
  2201. */
  2202. function shallowCopy(src, dst) {
  2203. if (isArray(src)) {
  2204. dst = dst || [];
  2205. for (var i = 0, ii = src.length; i < ii; i++) {
  2206. dst[i] = src[i];
  2207. }
  2208. } else if (isObject(src)) {
  2209. dst = dst || {};
  2210. for (var key in src) {
  2211. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2212. dst[key] = src[key];
  2213. }
  2214. }
  2215. }
  2216. return dst || src;
  2217. }
  2218. /* global toDebugString: true */
  2219. function serializeObject(obj) {
  2220. var seen = [];
  2221. return JSON.stringify(obj, function(key, val) {
  2222. val = toJsonReplacer(key, val);
  2223. if (isObject(val)) {
  2224. if (seen.indexOf(val) >= 0) return '...';
  2225. seen.push(val);
  2226. }
  2227. return val;
  2228. });
  2229. }
  2230. function toDebugString(obj) {
  2231. if (typeof obj === 'function') {
  2232. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2233. } else if (isUndefined(obj)) {
  2234. return 'undefined';
  2235. } else if (typeof obj !== 'string') {
  2236. return serializeObject(obj);
  2237. }
  2238. return obj;
  2239. }
  2240. /* global angularModule: true,
  2241. version: true,
  2242. $CompileProvider,
  2243. htmlAnchorDirective,
  2244. inputDirective,
  2245. inputDirective,
  2246. formDirective,
  2247. scriptDirective,
  2248. selectDirective,
  2249. optionDirective,
  2250. ngBindDirective,
  2251. ngBindHtmlDirective,
  2252. ngBindTemplateDirective,
  2253. ngClassDirective,
  2254. ngClassEvenDirective,
  2255. ngClassOddDirective,
  2256. ngCloakDirective,
  2257. ngControllerDirective,
  2258. ngFormDirective,
  2259. ngHideDirective,
  2260. ngIfDirective,
  2261. ngIncludeDirective,
  2262. ngIncludeFillContentDirective,
  2263. ngInitDirective,
  2264. ngNonBindableDirective,
  2265. ngPluralizeDirective,
  2266. ngRepeatDirective,
  2267. ngShowDirective,
  2268. ngStyleDirective,
  2269. ngSwitchDirective,
  2270. ngSwitchWhenDirective,
  2271. ngSwitchDefaultDirective,
  2272. ngOptionsDirective,
  2273. ngTranscludeDirective,
  2274. ngModelDirective,
  2275. ngListDirective,
  2276. ngChangeDirective,
  2277. patternDirective,
  2278. patternDirective,
  2279. requiredDirective,
  2280. requiredDirective,
  2281. minlengthDirective,
  2282. minlengthDirective,
  2283. maxlengthDirective,
  2284. maxlengthDirective,
  2285. ngValueDirective,
  2286. ngModelOptionsDirective,
  2287. ngAttributeAliasDirectives,
  2288. ngEventDirectives,
  2289. $AnchorScrollProvider,
  2290. $AnimateProvider,
  2291. $CoreAnimateCssProvider,
  2292. $$CoreAnimateJsProvider,
  2293. $$CoreAnimateQueueProvider,
  2294. $$AnimateRunnerFactoryProvider,
  2295. $$AnimateAsyncRunFactoryProvider,
  2296. $BrowserProvider,
  2297. $CacheFactoryProvider,
  2298. $ControllerProvider,
  2299. $DateProvider,
  2300. $DocumentProvider,
  2301. $$IsDocumentHiddenProvider,
  2302. $ExceptionHandlerProvider,
  2303. $FilterProvider,
  2304. $$ForceReflowProvider,
  2305. $InterpolateProvider,
  2306. $IntervalProvider,
  2307. $$HashMapProvider,
  2308. $HttpProvider,
  2309. $HttpParamSerializerProvider,
  2310. $HttpParamSerializerJQLikeProvider,
  2311. $HttpBackendProvider,
  2312. $xhrFactoryProvider,
  2313. $jsonpCallbacksProvider,
  2314. $LocationProvider,
  2315. $LogProvider,
  2316. $ParseProvider,
  2317. $RootScopeProvider,
  2318. $QProvider,
  2319. $$QProvider,
  2320. $$SanitizeUriProvider,
  2321. $SceProvider,
  2322. $SceDelegateProvider,
  2323. $SnifferProvider,
  2324. $TemplateCacheProvider,
  2325. $TemplateRequestProvider,
  2326. $$TestabilityProvider,
  2327. $TimeoutProvider,
  2328. $$RAFProvider,
  2329. $WindowProvider,
  2330. $$jqLiteProvider,
  2331. $$CookieReaderProvider
  2332. */
  2333. /**
  2334. * @ngdoc object
  2335. * @name angular.version
  2336. * @module ng
  2337. * @description
  2338. * An object that contains information about the current AngularJS version.
  2339. *
  2340. * This object has the following properties:
  2341. *
  2342. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2343. * - `major` – `{number}` – Major version number, such as "0".
  2344. * - `minor` – `{number}` – Minor version number, such as "9".
  2345. * - `dot` – `{number}` – Dot version number, such as "18".
  2346. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2347. */
  2348. var version = {
  2349. // These placeholder strings will be replaced by grunt's `build` task.
  2350. // They need to be double- or single-quoted.
  2351. full: '1.6.1',
  2352. major: 1,
  2353. minor: 6,
  2354. dot: 1,
  2355. codeName: 'promise-rectification'
  2356. };
  2357. function publishExternalAPI(angular) {
  2358. extend(angular, {
  2359. 'bootstrap': bootstrap,
  2360. 'copy': copy,
  2361. 'extend': extend,
  2362. 'merge': merge,
  2363. 'equals': equals,
  2364. 'element': jqLite,
  2365. 'forEach': forEach,
  2366. 'injector': createInjector,
  2367. 'noop': noop,
  2368. 'bind': bind,
  2369. 'toJson': toJson,
  2370. 'fromJson': fromJson,
  2371. 'identity': identity,
  2372. 'isUndefined': isUndefined,
  2373. 'isDefined': isDefined,
  2374. 'isString': isString,
  2375. 'isFunction': isFunction,
  2376. 'isObject': isObject,
  2377. 'isNumber': isNumber,
  2378. 'isElement': isElement,
  2379. 'isArray': isArray,
  2380. 'version': version,
  2381. 'isDate': isDate,
  2382. 'lowercase': lowercase,
  2383. 'uppercase': uppercase,
  2384. 'callbacks': {$$counter: 0},
  2385. 'getTestability': getTestability,
  2386. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2387. '$$minErr': minErr,
  2388. '$$csp': csp,
  2389. '$$encodeUriSegment': encodeUriSegment,
  2390. '$$encodeUriQuery': encodeUriQuery,
  2391. '$$stringify': stringify
  2392. });
  2393. angularModule = setupModuleLoader(window);
  2394. angularModule('ng', ['ngLocale'], ['$provide',
  2395. function ngModule($provide) {
  2396. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2397. $provide.provider({
  2398. $$sanitizeUri: $$SanitizeUriProvider
  2399. });
  2400. $provide.provider('$compile', $CompileProvider).
  2401. directive({
  2402. a: htmlAnchorDirective,
  2403. input: inputDirective,
  2404. textarea: inputDirective,
  2405. form: formDirective,
  2406. script: scriptDirective,
  2407. select: selectDirective,
  2408. option: optionDirective,
  2409. ngBind: ngBindDirective,
  2410. ngBindHtml: ngBindHtmlDirective,
  2411. ngBindTemplate: ngBindTemplateDirective,
  2412. ngClass: ngClassDirective,
  2413. ngClassEven: ngClassEvenDirective,
  2414. ngClassOdd: ngClassOddDirective,
  2415. ngCloak: ngCloakDirective,
  2416. ngController: ngControllerDirective,
  2417. ngForm: ngFormDirective,
  2418. ngHide: ngHideDirective,
  2419. ngIf: ngIfDirective,
  2420. ngInclude: ngIncludeDirective,
  2421. ngInit: ngInitDirective,
  2422. ngNonBindable: ngNonBindableDirective,
  2423. ngPluralize: ngPluralizeDirective,
  2424. ngRepeat: ngRepeatDirective,
  2425. ngShow: ngShowDirective,
  2426. ngStyle: ngStyleDirective,
  2427. ngSwitch: ngSwitchDirective,
  2428. ngSwitchWhen: ngSwitchWhenDirective,
  2429. ngSwitchDefault: ngSwitchDefaultDirective,
  2430. ngOptions: ngOptionsDirective,
  2431. ngTransclude: ngTranscludeDirective,
  2432. ngModel: ngModelDirective,
  2433. ngList: ngListDirective,
  2434. ngChange: ngChangeDirective,
  2435. pattern: patternDirective,
  2436. ngPattern: patternDirective,
  2437. required: requiredDirective,
  2438. ngRequired: requiredDirective,
  2439. minlength: minlengthDirective,
  2440. ngMinlength: minlengthDirective,
  2441. maxlength: maxlengthDirective,
  2442. ngMaxlength: maxlengthDirective,
  2443. ngValue: ngValueDirective,
  2444. ngModelOptions: ngModelOptionsDirective
  2445. }).
  2446. directive({
  2447. ngInclude: ngIncludeFillContentDirective
  2448. }).
  2449. directive(ngAttributeAliasDirectives).
  2450. directive(ngEventDirectives);
  2451. $provide.provider({
  2452. $anchorScroll: $AnchorScrollProvider,
  2453. $animate: $AnimateProvider,
  2454. $animateCss: $CoreAnimateCssProvider,
  2455. $$animateJs: $$CoreAnimateJsProvider,
  2456. $$animateQueue: $$CoreAnimateQueueProvider,
  2457. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2458. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2459. $browser: $BrowserProvider,
  2460. $cacheFactory: $CacheFactoryProvider,
  2461. $controller: $ControllerProvider,
  2462. $document: $DocumentProvider,
  2463. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2464. $exceptionHandler: $ExceptionHandlerProvider,
  2465. $filter: $FilterProvider,
  2466. $$forceReflow: $$ForceReflowProvider,
  2467. $interpolate: $InterpolateProvider,
  2468. $interval: $IntervalProvider,
  2469. $http: $HttpProvider,
  2470. $httpParamSerializer: $HttpParamSerializerProvider,
  2471. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2472. $httpBackend: $HttpBackendProvider,
  2473. $xhrFactory: $xhrFactoryProvider,
  2474. $jsonpCallbacks: $jsonpCallbacksProvider,
  2475. $location: $LocationProvider,
  2476. $log: $LogProvider,
  2477. $parse: $ParseProvider,
  2478. $rootScope: $RootScopeProvider,
  2479. $q: $QProvider,
  2480. $$q: $$QProvider,
  2481. $sce: $SceProvider,
  2482. $sceDelegate: $SceDelegateProvider,
  2483. $sniffer: $SnifferProvider,
  2484. $templateCache: $TemplateCacheProvider,
  2485. $templateRequest: $TemplateRequestProvider,
  2486. $$testability: $$TestabilityProvider,
  2487. $timeout: $TimeoutProvider,
  2488. $window: $WindowProvider,
  2489. $$rAF: $$RAFProvider,
  2490. $$jqLite: $$jqLiteProvider,
  2491. $$HashMap: $$HashMapProvider,
  2492. $$cookieReader: $$CookieReaderProvider
  2493. });
  2494. }
  2495. ]);
  2496. }
  2497. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2498. * Any commits to this file should be reviewed with security in mind. *
  2499. * Changes to this file can potentially create security vulnerabilities. *
  2500. * An approval from 2 Core members with history of modifying *
  2501. * this file is required. *
  2502. * *
  2503. * Does the change somehow allow for arbitrary javascript to be executed? *
  2504. * Or allows for someone to change the prototype of built-in objects? *
  2505. * Or gives undesired access to variables likes document or window? *
  2506. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2507. /* global
  2508. JQLitePrototype: true,
  2509. BOOLEAN_ATTR: true,
  2510. ALIASED_ATTR: true
  2511. */
  2512. //////////////////////////////////
  2513. //JQLite
  2514. //////////////////////////////////
  2515. /**
  2516. * @ngdoc function
  2517. * @name angular.element
  2518. * @module ng
  2519. * @kind function
  2520. *
  2521. * @description
  2522. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2523. *
  2524. * If jQuery is available, `angular.element` is an alias for the
  2525. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2526. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2527. *
  2528. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2529. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2530. * commonly needed functionality with the goal of having a very small footprint.
  2531. *
  2532. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2533. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2534. * specific version of jQuery if multiple versions exist on the page.
  2535. *
  2536. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2537. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2538. *
  2539. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2540. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2541. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2542. *
  2543. * ## Angular's jqLite
  2544. * jqLite provides only the following jQuery methods:
  2545. *
  2546. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2547. * - [`after()`](http://api.jquery.com/after/)
  2548. * - [`append()`](http://api.jquery.com/append/)
  2549. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2550. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2551. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2552. * - [`clone()`](http://api.jquery.com/clone/)
  2553. * - [`contents()`](http://api.jquery.com/contents/)
  2554. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2555. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2556. * - [`data()`](http://api.jquery.com/data/)
  2557. * - [`detach()`](http://api.jquery.com/detach/)
  2558. * - [`empty()`](http://api.jquery.com/empty/)
  2559. * - [`eq()`](http://api.jquery.com/eq/)
  2560. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2561. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2562. * - [`html()`](http://api.jquery.com/html/)
  2563. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2564. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2565. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2566. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2567. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2568. * - [`prepend()`](http://api.jquery.com/prepend/)
  2569. * - [`prop()`](http://api.jquery.com/prop/)
  2570. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2571. * - [`remove()`](http://api.jquery.com/remove/)
  2572. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2573. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2574. * - [`removeData()`](http://api.jquery.com/removeData/)
  2575. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2576. * - [`text()`](http://api.jquery.com/text/)
  2577. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2578. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2579. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2580. * - [`val()`](http://api.jquery.com/val/)
  2581. * - [`wrap()`](http://api.jquery.com/wrap/)
  2582. *
  2583. * ## jQuery/jqLite Extras
  2584. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2585. *
  2586. * ### Events
  2587. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2588. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2589. * element before it is removed.
  2590. *
  2591. * ### Methods
  2592. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2593. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2594. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2595. * `'ngModel'`).
  2596. * - `injector()` - retrieves the injector of the current element or its parent.
  2597. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2598. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2599. * be enabled.
  2600. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2601. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2602. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2603. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2604. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2605. * parent element is reached.
  2606. *
  2607. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2608. * https://github.com/angular/angular.js/issues/14251 for more information.
  2609. *
  2610. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2611. * @returns {Object} jQuery object.
  2612. */
  2613. JQLite.expando = 'ng339';
  2614. var jqCache = JQLite.cache = {},
  2615. jqId = 1;
  2616. /*
  2617. * !!! This is an undocumented "private" function !!!
  2618. */
  2619. JQLite._data = function(node) {
  2620. //jQuery always returns an object on cache miss
  2621. return this.cache[node[this.expando]] || {};
  2622. };
  2623. function jqNextId() { return ++jqId; }
  2624. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2625. var MS_HACK_REGEXP = /^-ms-/;
  2626. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2627. var jqLiteMinErr = minErr('jqLite');
  2628. /**
  2629. * Converts kebab-case to camelCase.
  2630. * There is also a special case for the ms prefix starting with a lowercase letter.
  2631. * @param name Name to normalize
  2632. */
  2633. function cssKebabToCamel(name) {
  2634. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2635. }
  2636. function fnCamelCaseReplace(all, letter) {
  2637. return letter.toUpperCase();
  2638. }
  2639. /**
  2640. * Converts kebab-case to camelCase.
  2641. * @param name Name to normalize
  2642. */
  2643. function kebabToCamel(name) {
  2644. return name
  2645. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2646. }
  2647. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2648. var HTML_REGEXP = /<|&#?\w+;/;
  2649. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2650. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2651. var wrapMap = {
  2652. 'option': [1, '<select multiple="multiple">', '</select>'],
  2653. 'thead': [1, '<table>', '</table>'],
  2654. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2655. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2656. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2657. '_default': [0, '', '']
  2658. };
  2659. wrapMap.optgroup = wrapMap.option;
  2660. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2661. wrapMap.th = wrapMap.td;
  2662. function jqLiteIsTextNode(html) {
  2663. return !HTML_REGEXP.test(html);
  2664. }
  2665. function jqLiteAcceptsData(node) {
  2666. // The window object can accept data but has no nodeType
  2667. // Otherwise we are only interested in elements (1) and documents (9)
  2668. var nodeType = node.nodeType;
  2669. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2670. }
  2671. function jqLiteHasData(node) {
  2672. for (var key in jqCache[node.ng339]) {
  2673. return true;
  2674. }
  2675. return false;
  2676. }
  2677. function jqLiteCleanData(nodes) {
  2678. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2679. jqLiteRemoveData(nodes[i]);
  2680. }
  2681. }
  2682. function jqLiteBuildFragment(html, context) {
  2683. var tmp, tag, wrap,
  2684. fragment = context.createDocumentFragment(),
  2685. nodes = [], i;
  2686. if (jqLiteIsTextNode(html)) {
  2687. // Convert non-html into a text node
  2688. nodes.push(context.createTextNode(html));
  2689. } else {
  2690. // Convert html into DOM nodes
  2691. tmp = fragment.appendChild(context.createElement('div'));
  2692. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2693. wrap = wrapMap[tag] || wrapMap._default;
  2694. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2695. // Descend through wrappers to the right content
  2696. i = wrap[0];
  2697. while (i--) {
  2698. tmp = tmp.lastChild;
  2699. }
  2700. nodes = concat(nodes, tmp.childNodes);
  2701. tmp = fragment.firstChild;
  2702. tmp.textContent = '';
  2703. }
  2704. // Remove wrapper from fragment
  2705. fragment.textContent = '';
  2706. fragment.innerHTML = ''; // Clear inner HTML
  2707. forEach(nodes, function(node) {
  2708. fragment.appendChild(node);
  2709. });
  2710. return fragment;
  2711. }
  2712. function jqLiteParseHTML(html, context) {
  2713. context = context || window.document;
  2714. var parsed;
  2715. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2716. return [context.createElement(parsed[1])];
  2717. }
  2718. if ((parsed = jqLiteBuildFragment(html, context))) {
  2719. return parsed.childNodes;
  2720. }
  2721. return [];
  2722. }
  2723. function jqLiteWrapNode(node, wrapper) {
  2724. var parent = node.parentNode;
  2725. if (parent) {
  2726. parent.replaceChild(wrapper, node);
  2727. }
  2728. wrapper.appendChild(node);
  2729. }
  2730. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2731. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2732. // eslint-disable-next-line no-bitwise
  2733. return !!(this.compareDocumentPosition(arg) & 16);
  2734. };
  2735. /////////////////////////////////////////////
  2736. function JQLite(element) {
  2737. if (element instanceof JQLite) {
  2738. return element;
  2739. }
  2740. var argIsString;
  2741. if (isString(element)) {
  2742. element = trim(element);
  2743. argIsString = true;
  2744. }
  2745. if (!(this instanceof JQLite)) {
  2746. if (argIsString && element.charAt(0) !== '<') {
  2747. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2748. }
  2749. return new JQLite(element);
  2750. }
  2751. if (argIsString) {
  2752. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2753. } else if (isFunction(element)) {
  2754. jqLiteReady(element);
  2755. } else {
  2756. jqLiteAddNodes(this, element);
  2757. }
  2758. }
  2759. function jqLiteClone(element) {
  2760. return element.cloneNode(true);
  2761. }
  2762. function jqLiteDealoc(element, onlyDescendants) {
  2763. if (!onlyDescendants) jqLiteRemoveData(element);
  2764. if (element.querySelectorAll) {
  2765. var descendants = element.querySelectorAll('*');
  2766. for (var i = 0, l = descendants.length; i < l; i++) {
  2767. jqLiteRemoveData(descendants[i]);
  2768. }
  2769. }
  2770. }
  2771. function jqLiteOff(element, type, fn, unsupported) {
  2772. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2773. var expandoStore = jqLiteExpandoStore(element);
  2774. var events = expandoStore && expandoStore.events;
  2775. var handle = expandoStore && expandoStore.handle;
  2776. if (!handle) return; //no listeners registered
  2777. if (!type) {
  2778. for (type in events) {
  2779. if (type !== '$destroy') {
  2780. element.removeEventListener(type, handle);
  2781. }
  2782. delete events[type];
  2783. }
  2784. } else {
  2785. var removeHandler = function(type) {
  2786. var listenerFns = events[type];
  2787. if (isDefined(fn)) {
  2788. arrayRemove(listenerFns || [], fn);
  2789. }
  2790. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2791. element.removeEventListener(type, handle);
  2792. delete events[type];
  2793. }
  2794. };
  2795. forEach(type.split(' '), function(type) {
  2796. removeHandler(type);
  2797. if (MOUSE_EVENT_MAP[type]) {
  2798. removeHandler(MOUSE_EVENT_MAP[type]);
  2799. }
  2800. });
  2801. }
  2802. }
  2803. function jqLiteRemoveData(element, name) {
  2804. var expandoId = element.ng339;
  2805. var expandoStore = expandoId && jqCache[expandoId];
  2806. if (expandoStore) {
  2807. if (name) {
  2808. delete expandoStore.data[name];
  2809. return;
  2810. }
  2811. if (expandoStore.handle) {
  2812. if (expandoStore.events.$destroy) {
  2813. expandoStore.handle({}, '$destroy');
  2814. }
  2815. jqLiteOff(element);
  2816. }
  2817. delete jqCache[expandoId];
  2818. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2819. }
  2820. }
  2821. function jqLiteExpandoStore(element, createIfNecessary) {
  2822. var expandoId = element.ng339,
  2823. expandoStore = expandoId && jqCache[expandoId];
  2824. if (createIfNecessary && !expandoStore) {
  2825. element.ng339 = expandoId = jqNextId();
  2826. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2827. }
  2828. return expandoStore;
  2829. }
  2830. function jqLiteData(element, key, value) {
  2831. if (jqLiteAcceptsData(element)) {
  2832. var prop;
  2833. var isSimpleSetter = isDefined(value);
  2834. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2835. var massGetter = !key;
  2836. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2837. var data = expandoStore && expandoStore.data;
  2838. if (isSimpleSetter) { // data('key', value)
  2839. data[kebabToCamel(key)] = value;
  2840. } else {
  2841. if (massGetter) { // data()
  2842. return data;
  2843. } else {
  2844. if (isSimpleGetter) { // data('key')
  2845. // don't force creation of expandoStore if it doesn't exist yet
  2846. return data && data[kebabToCamel(key)];
  2847. } else { // mass-setter: data({key1: val1, key2: val2})
  2848. for (prop in key) {
  2849. data[kebabToCamel(prop)] = key[prop];
  2850. }
  2851. }
  2852. }
  2853. }
  2854. }
  2855. }
  2856. function jqLiteHasClass(element, selector) {
  2857. if (!element.getAttribute) return false;
  2858. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2859. indexOf(' ' + selector + ' ') > -1);
  2860. }
  2861. function jqLiteRemoveClass(element, cssClasses) {
  2862. if (cssClasses && element.setAttribute) {
  2863. forEach(cssClasses.split(' '), function(cssClass) {
  2864. element.setAttribute('class', trim(
  2865. (' ' + (element.getAttribute('class') || '') + ' ')
  2866. .replace(/[\n\t]/g, ' ')
  2867. .replace(' ' + trim(cssClass) + ' ', ' '))
  2868. );
  2869. });
  2870. }
  2871. }
  2872. function jqLiteAddClass(element, cssClasses) {
  2873. if (cssClasses && element.setAttribute) {
  2874. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2875. .replace(/[\n\t]/g, ' ');
  2876. forEach(cssClasses.split(' '), function(cssClass) {
  2877. cssClass = trim(cssClass);
  2878. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2879. existingClasses += cssClass + ' ';
  2880. }
  2881. });
  2882. element.setAttribute('class', trim(existingClasses));
  2883. }
  2884. }
  2885. function jqLiteAddNodes(root, elements) {
  2886. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2887. if (elements) {
  2888. // if a Node (the most common case)
  2889. if (elements.nodeType) {
  2890. root[root.length++] = elements;
  2891. } else {
  2892. var length = elements.length;
  2893. // if an Array or NodeList and not a Window
  2894. if (typeof length === 'number' && elements.window !== elements) {
  2895. if (length) {
  2896. for (var i = 0; i < length; i++) {
  2897. root[root.length++] = elements[i];
  2898. }
  2899. }
  2900. } else {
  2901. root[root.length++] = elements;
  2902. }
  2903. }
  2904. }
  2905. }
  2906. function jqLiteController(element, name) {
  2907. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2908. }
  2909. function jqLiteInheritedData(element, name, value) {
  2910. // if element is the document object work with the html element instead
  2911. // this makes $(document).scope() possible
  2912. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  2913. element = element.documentElement;
  2914. }
  2915. var names = isArray(name) ? name : [name];
  2916. while (element) {
  2917. for (var i = 0, ii = names.length; i < ii; i++) {
  2918. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2919. }
  2920. // If dealing with a document fragment node with a host element, and no parent, use the host
  2921. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2922. // to lookup parent controllers.
  2923. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2924. }
  2925. }
  2926. function jqLiteEmpty(element) {
  2927. jqLiteDealoc(element, true);
  2928. while (element.firstChild) {
  2929. element.removeChild(element.firstChild);
  2930. }
  2931. }
  2932. function jqLiteRemove(element, keepData) {
  2933. if (!keepData) jqLiteDealoc(element);
  2934. var parent = element.parentNode;
  2935. if (parent) parent.removeChild(element);
  2936. }
  2937. function jqLiteDocumentLoaded(action, win) {
  2938. win = win || window;
  2939. if (win.document.readyState === 'complete') {
  2940. // Force the action to be run async for consistent behavior
  2941. // from the action's point of view
  2942. // i.e. it will definitely not be in a $apply
  2943. win.setTimeout(action);
  2944. } else {
  2945. // No need to unbind this handler as load is only ever called once
  2946. jqLite(win).on('load', action);
  2947. }
  2948. }
  2949. function jqLiteReady(fn) {
  2950. function trigger() {
  2951. window.document.removeEventListener('DOMContentLoaded', trigger);
  2952. window.removeEventListener('load', trigger);
  2953. fn();
  2954. }
  2955. // check if document is already loaded
  2956. if (window.document.readyState === 'complete') {
  2957. window.setTimeout(fn);
  2958. } else {
  2959. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  2960. // Works for modern browsers and IE9
  2961. window.document.addEventListener('DOMContentLoaded', trigger);
  2962. // Fallback to window.onload for others
  2963. window.addEventListener('load', trigger);
  2964. }
  2965. }
  2966. //////////////////////////////////////////
  2967. // Functions which are declared directly.
  2968. //////////////////////////////////////////
  2969. var JQLitePrototype = JQLite.prototype = {
  2970. ready: jqLiteReady,
  2971. toString: function() {
  2972. var value = [];
  2973. forEach(this, function(e) { value.push('' + e);});
  2974. return '[' + value.join(', ') + ']';
  2975. },
  2976. eq: function(index) {
  2977. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2978. },
  2979. length: 0,
  2980. push: push,
  2981. sort: [].sort,
  2982. splice: [].splice
  2983. };
  2984. //////////////////////////////////////////
  2985. // Functions iterating getter/setters.
  2986. // these functions return self on setter and
  2987. // value on get.
  2988. //////////////////////////////////////////
  2989. var BOOLEAN_ATTR = {};
  2990. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2991. BOOLEAN_ATTR[lowercase(value)] = value;
  2992. });
  2993. var BOOLEAN_ELEMENTS = {};
  2994. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2995. BOOLEAN_ELEMENTS[value] = true;
  2996. });
  2997. var ALIASED_ATTR = {
  2998. 'ngMinlength': 'minlength',
  2999. 'ngMaxlength': 'maxlength',
  3000. 'ngMin': 'min',
  3001. 'ngMax': 'max',
  3002. 'ngPattern': 'pattern',
  3003. 'ngStep': 'step'
  3004. };
  3005. function getBooleanAttrName(element, name) {
  3006. // check dom last since we will most likely fail on name
  3007. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3008. // booleanAttr is here twice to minimize DOM access
  3009. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3010. }
  3011. function getAliasedAttrName(name) {
  3012. return ALIASED_ATTR[name];
  3013. }
  3014. forEach({
  3015. data: jqLiteData,
  3016. removeData: jqLiteRemoveData,
  3017. hasData: jqLiteHasData,
  3018. cleanData: jqLiteCleanData
  3019. }, function(fn, name) {
  3020. JQLite[name] = fn;
  3021. });
  3022. forEach({
  3023. data: jqLiteData,
  3024. inheritedData: jqLiteInheritedData,
  3025. scope: function(element) {
  3026. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3027. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3028. },
  3029. isolateScope: function(element) {
  3030. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3031. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3032. },
  3033. controller: jqLiteController,
  3034. injector: function(element) {
  3035. return jqLiteInheritedData(element, '$injector');
  3036. },
  3037. removeAttr: function(element, name) {
  3038. element.removeAttribute(name);
  3039. },
  3040. hasClass: jqLiteHasClass,
  3041. css: function(element, name, value) {
  3042. name = cssKebabToCamel(name);
  3043. if (isDefined(value)) {
  3044. element.style[name] = value;
  3045. } else {
  3046. return element.style[name];
  3047. }
  3048. },
  3049. attr: function(element, name, value) {
  3050. var ret;
  3051. var nodeType = element.nodeType;
  3052. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3053. !element.getAttribute) {
  3054. return;
  3055. }
  3056. var lowercasedName = lowercase(name);
  3057. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3058. if (isDefined(value)) {
  3059. // setter
  3060. if (value === null || (value === false && isBooleanAttr)) {
  3061. element.removeAttribute(name);
  3062. } else {
  3063. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3064. }
  3065. } else {
  3066. // getter
  3067. ret = element.getAttribute(name);
  3068. if (isBooleanAttr && ret !== null) {
  3069. ret = lowercasedName;
  3070. }
  3071. // Normalize non-existing attributes to undefined (as jQuery).
  3072. return ret === null ? undefined : ret;
  3073. }
  3074. },
  3075. prop: function(element, name, value) {
  3076. if (isDefined(value)) {
  3077. element[name] = value;
  3078. } else {
  3079. return element[name];
  3080. }
  3081. },
  3082. text: (function() {
  3083. getText.$dv = '';
  3084. return getText;
  3085. function getText(element, value) {
  3086. if (isUndefined(value)) {
  3087. var nodeType = element.nodeType;
  3088. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3089. }
  3090. element.textContent = value;
  3091. }
  3092. })(),
  3093. val: function(element, value) {
  3094. if (isUndefined(value)) {
  3095. if (element.multiple && nodeName_(element) === 'select') {
  3096. var result = [];
  3097. forEach(element.options, function(option) {
  3098. if (option.selected) {
  3099. result.push(option.value || option.text);
  3100. }
  3101. });
  3102. return result;
  3103. }
  3104. return element.value;
  3105. }
  3106. element.value = value;
  3107. },
  3108. html: function(element, value) {
  3109. if (isUndefined(value)) {
  3110. return element.innerHTML;
  3111. }
  3112. jqLiteDealoc(element, true);
  3113. element.innerHTML = value;
  3114. },
  3115. empty: jqLiteEmpty
  3116. }, function(fn, name) {
  3117. /**
  3118. * Properties: writes return selection, reads return first value
  3119. */
  3120. JQLite.prototype[name] = function(arg1, arg2) {
  3121. var i, key;
  3122. var nodeCount = this.length;
  3123. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3124. // in a way that survives minification.
  3125. // jqLiteEmpty takes no arguments but is a setter.
  3126. if (fn !== jqLiteEmpty &&
  3127. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3128. if (isObject(arg1)) {
  3129. // we are a write, but the object properties are the key/values
  3130. for (i = 0; i < nodeCount; i++) {
  3131. if (fn === jqLiteData) {
  3132. // data() takes the whole object in jQuery
  3133. fn(this[i], arg1);
  3134. } else {
  3135. for (key in arg1) {
  3136. fn(this[i], key, arg1[key]);
  3137. }
  3138. }
  3139. }
  3140. // return self for chaining
  3141. return this;
  3142. } else {
  3143. // we are a read, so read the first child.
  3144. // TODO: do we still need this?
  3145. var value = fn.$dv;
  3146. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3147. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3148. for (var j = 0; j < jj; j++) {
  3149. var nodeValue = fn(this[j], arg1, arg2);
  3150. value = value ? value + nodeValue : nodeValue;
  3151. }
  3152. return value;
  3153. }
  3154. } else {
  3155. // we are a write, so apply to all children
  3156. for (i = 0; i < nodeCount; i++) {
  3157. fn(this[i], arg1, arg2);
  3158. }
  3159. // return self for chaining
  3160. return this;
  3161. }
  3162. };
  3163. });
  3164. function createEventHandler(element, events) {
  3165. var eventHandler = function(event, type) {
  3166. // jQuery specific api
  3167. event.isDefaultPrevented = function() {
  3168. return event.defaultPrevented;
  3169. };
  3170. var eventFns = events[type || event.type];
  3171. var eventFnsLength = eventFns ? eventFns.length : 0;
  3172. if (!eventFnsLength) return;
  3173. if (isUndefined(event.immediatePropagationStopped)) {
  3174. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3175. event.stopImmediatePropagation = function() {
  3176. event.immediatePropagationStopped = true;
  3177. if (event.stopPropagation) {
  3178. event.stopPropagation();
  3179. }
  3180. if (originalStopImmediatePropagation) {
  3181. originalStopImmediatePropagation.call(event);
  3182. }
  3183. };
  3184. }
  3185. event.isImmediatePropagationStopped = function() {
  3186. return event.immediatePropagationStopped === true;
  3187. };
  3188. // Some events have special handlers that wrap the real handler
  3189. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3190. // Copy event handlers in case event handlers array is modified during execution.
  3191. if ((eventFnsLength > 1)) {
  3192. eventFns = shallowCopy(eventFns);
  3193. }
  3194. for (var i = 0; i < eventFnsLength; i++) {
  3195. if (!event.isImmediatePropagationStopped()) {
  3196. handlerWrapper(element, event, eventFns[i]);
  3197. }
  3198. }
  3199. };
  3200. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3201. // events on `element`
  3202. eventHandler.elem = element;
  3203. return eventHandler;
  3204. }
  3205. function defaultHandlerWrapper(element, event, handler) {
  3206. handler.call(element, event);
  3207. }
  3208. function specialMouseHandlerWrapper(target, event, handler) {
  3209. // Refer to jQuery's implementation of mouseenter & mouseleave
  3210. // Read about mouseenter and mouseleave:
  3211. // http://www.quirksmode.org/js/events_mouse.html#link8
  3212. var related = event.relatedTarget;
  3213. // For mousenter/leave call the handler if related is outside the target.
  3214. // NB: No relatedTarget if the mouse left/entered the browser window
  3215. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3216. handler.call(target, event);
  3217. }
  3218. }
  3219. //////////////////////////////////////////
  3220. // Functions iterating traversal.
  3221. // These functions chain results into a single
  3222. // selector.
  3223. //////////////////////////////////////////
  3224. forEach({
  3225. removeData: jqLiteRemoveData,
  3226. on: function jqLiteOn(element, type, fn, unsupported) {
  3227. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3228. // Do not add event handlers to non-elements because they will not be cleaned up.
  3229. if (!jqLiteAcceptsData(element)) {
  3230. return;
  3231. }
  3232. var expandoStore = jqLiteExpandoStore(element, true);
  3233. var events = expandoStore.events;
  3234. var handle = expandoStore.handle;
  3235. if (!handle) {
  3236. handle = expandoStore.handle = createEventHandler(element, events);
  3237. }
  3238. // http://jsperf.com/string-indexof-vs-split
  3239. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3240. var i = types.length;
  3241. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3242. var eventFns = events[type];
  3243. if (!eventFns) {
  3244. eventFns = events[type] = [];
  3245. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3246. if (type !== '$destroy' && !noEventListener) {
  3247. element.addEventListener(type, handle);
  3248. }
  3249. }
  3250. eventFns.push(fn);
  3251. };
  3252. while (i--) {
  3253. type = types[i];
  3254. if (MOUSE_EVENT_MAP[type]) {
  3255. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3256. addHandler(type, undefined, true);
  3257. } else {
  3258. addHandler(type);
  3259. }
  3260. }
  3261. },
  3262. off: jqLiteOff,
  3263. one: function(element, type, fn) {
  3264. element = jqLite(element);
  3265. //add the listener twice so that when it is called
  3266. //you can remove the original function and still be
  3267. //able to call element.off(ev, fn) normally
  3268. element.on(type, function onFn() {
  3269. element.off(type, fn);
  3270. element.off(type, onFn);
  3271. });
  3272. element.on(type, fn);
  3273. },
  3274. replaceWith: function(element, replaceNode) {
  3275. var index, parent = element.parentNode;
  3276. jqLiteDealoc(element);
  3277. forEach(new JQLite(replaceNode), function(node) {
  3278. if (index) {
  3279. parent.insertBefore(node, index.nextSibling);
  3280. } else {
  3281. parent.replaceChild(node, element);
  3282. }
  3283. index = node;
  3284. });
  3285. },
  3286. children: function(element) {
  3287. var children = [];
  3288. forEach(element.childNodes, function(element) {
  3289. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3290. children.push(element);
  3291. }
  3292. });
  3293. return children;
  3294. },
  3295. contents: function(element) {
  3296. return element.contentDocument || element.childNodes || [];
  3297. },
  3298. append: function(element, node) {
  3299. var nodeType = element.nodeType;
  3300. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3301. node = new JQLite(node);
  3302. for (var i = 0, ii = node.length; i < ii; i++) {
  3303. var child = node[i];
  3304. element.appendChild(child);
  3305. }
  3306. },
  3307. prepend: function(element, node) {
  3308. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3309. var index = element.firstChild;
  3310. forEach(new JQLite(node), function(child) {
  3311. element.insertBefore(child, index);
  3312. });
  3313. }
  3314. },
  3315. wrap: function(element, wrapNode) {
  3316. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3317. },
  3318. remove: jqLiteRemove,
  3319. detach: function(element) {
  3320. jqLiteRemove(element, true);
  3321. },
  3322. after: function(element, newElement) {
  3323. var index = element, parent = element.parentNode;
  3324. if (parent) {
  3325. newElement = new JQLite(newElement);
  3326. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3327. var node = newElement[i];
  3328. parent.insertBefore(node, index.nextSibling);
  3329. index = node;
  3330. }
  3331. }
  3332. },
  3333. addClass: jqLiteAddClass,
  3334. removeClass: jqLiteRemoveClass,
  3335. toggleClass: function(element, selector, condition) {
  3336. if (selector) {
  3337. forEach(selector.split(' '), function(className) {
  3338. var classCondition = condition;
  3339. if (isUndefined(classCondition)) {
  3340. classCondition = !jqLiteHasClass(element, className);
  3341. }
  3342. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3343. });
  3344. }
  3345. },
  3346. parent: function(element) {
  3347. var parent = element.parentNode;
  3348. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3349. },
  3350. next: function(element) {
  3351. return element.nextElementSibling;
  3352. },
  3353. find: function(element, selector) {
  3354. if (element.getElementsByTagName) {
  3355. return element.getElementsByTagName(selector);
  3356. } else {
  3357. return [];
  3358. }
  3359. },
  3360. clone: jqLiteClone,
  3361. triggerHandler: function(element, event, extraParameters) {
  3362. var dummyEvent, eventFnsCopy, handlerArgs;
  3363. var eventName = event.type || event;
  3364. var expandoStore = jqLiteExpandoStore(element);
  3365. var events = expandoStore && expandoStore.events;
  3366. var eventFns = events && events[eventName];
  3367. if (eventFns) {
  3368. // Create a dummy event to pass to the handlers
  3369. dummyEvent = {
  3370. preventDefault: function() { this.defaultPrevented = true; },
  3371. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3372. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3373. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3374. stopPropagation: noop,
  3375. type: eventName,
  3376. target: element
  3377. };
  3378. // If a custom event was provided then extend our dummy event with it
  3379. if (event.type) {
  3380. dummyEvent = extend(dummyEvent, event);
  3381. }
  3382. // Copy event handlers in case event handlers array is modified during execution.
  3383. eventFnsCopy = shallowCopy(eventFns);
  3384. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3385. forEach(eventFnsCopy, function(fn) {
  3386. if (!dummyEvent.isImmediatePropagationStopped()) {
  3387. fn.apply(element, handlerArgs);
  3388. }
  3389. });
  3390. }
  3391. }
  3392. }, function(fn, name) {
  3393. /**
  3394. * chaining functions
  3395. */
  3396. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3397. var value;
  3398. for (var i = 0, ii = this.length; i < ii; i++) {
  3399. if (isUndefined(value)) {
  3400. value = fn(this[i], arg1, arg2, arg3);
  3401. if (isDefined(value)) {
  3402. // any function which returns a value needs to be wrapped
  3403. value = jqLite(value);
  3404. }
  3405. } else {
  3406. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3407. }
  3408. }
  3409. return isDefined(value) ? value : this;
  3410. };
  3411. });
  3412. // bind legacy bind/unbind to on/off
  3413. JQLite.prototype.bind = JQLite.prototype.on;
  3414. JQLite.prototype.unbind = JQLite.prototype.off;
  3415. // Provider for private $$jqLite service
  3416. /** @this */
  3417. function $$jqLiteProvider() {
  3418. this.$get = function $$jqLite() {
  3419. return extend(JQLite, {
  3420. hasClass: function(node, classes) {
  3421. if (node.attr) node = node[0];
  3422. return jqLiteHasClass(node, classes);
  3423. },
  3424. addClass: function(node, classes) {
  3425. if (node.attr) node = node[0];
  3426. return jqLiteAddClass(node, classes);
  3427. },
  3428. removeClass: function(node, classes) {
  3429. if (node.attr) node = node[0];
  3430. return jqLiteRemoveClass(node, classes);
  3431. }
  3432. });
  3433. };
  3434. }
  3435. /**
  3436. * Computes a hash of an 'obj'.
  3437. * Hash of a:
  3438. * string is string
  3439. * number is number as string
  3440. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3441. * that is also assigned to the $$hashKey property of the object.
  3442. *
  3443. * @param obj
  3444. * @returns {string} hash string such that the same input will have the same hash string.
  3445. * The resulting string key is in 'type:hashKey' format.
  3446. */
  3447. function hashKey(obj, nextUidFn) {
  3448. var key = obj && obj.$$hashKey;
  3449. if (key) {
  3450. if (typeof key === 'function') {
  3451. key = obj.$$hashKey();
  3452. }
  3453. return key;
  3454. }
  3455. var objType = typeof obj;
  3456. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3457. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3458. } else {
  3459. key = objType + ':' + obj;
  3460. }
  3461. return key;
  3462. }
  3463. /**
  3464. * HashMap which can use objects as keys
  3465. */
  3466. function HashMap(array, isolatedUid) {
  3467. if (isolatedUid) {
  3468. var uid = 0;
  3469. this.nextUid = function() {
  3470. return ++uid;
  3471. };
  3472. }
  3473. forEach(array, this.put, this);
  3474. }
  3475. HashMap.prototype = {
  3476. /**
  3477. * Store key value pair
  3478. * @param key key to store can be any type
  3479. * @param value value to store can be any type
  3480. */
  3481. put: function(key, value) {
  3482. this[hashKey(key, this.nextUid)] = value;
  3483. },
  3484. /**
  3485. * @param key
  3486. * @returns {Object} the value for the key
  3487. */
  3488. get: function(key) {
  3489. return this[hashKey(key, this.nextUid)];
  3490. },
  3491. /**
  3492. * Remove the key/value pair
  3493. * @param key
  3494. */
  3495. remove: function(key) {
  3496. var value = this[key = hashKey(key, this.nextUid)];
  3497. delete this[key];
  3498. return value;
  3499. }
  3500. };
  3501. var $$HashMapProvider = [/** @this */function() {
  3502. this.$get = [function() {
  3503. return HashMap;
  3504. }];
  3505. }];
  3506. /**
  3507. * @ngdoc function
  3508. * @module ng
  3509. * @name angular.injector
  3510. * @kind function
  3511. *
  3512. * @description
  3513. * Creates an injector object that can be used for retrieving services as well as for
  3514. * dependency injection (see {@link guide/di dependency injection}).
  3515. *
  3516. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3517. * {@link angular.module}. The `ng` module must be explicitly added.
  3518. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3519. * disallows argument name annotation inference.
  3520. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3521. *
  3522. * @example
  3523. * Typical usage
  3524. * ```js
  3525. * // create an injector
  3526. * var $injector = angular.injector(['ng']);
  3527. *
  3528. * // use the injector to kick off your application
  3529. * // use the type inference to auto inject arguments, or use implicit injection
  3530. * $injector.invoke(function($rootScope, $compile, $document) {
  3531. * $compile($document)($rootScope);
  3532. * $rootScope.$digest();
  3533. * });
  3534. * ```
  3535. *
  3536. * Sometimes you want to get access to the injector of a currently running Angular app
  3537. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3538. * application has been bootstrapped. You can do this using the extra `injector()` added
  3539. * to JQuery/jqLite elements. See {@link angular.element}.
  3540. *
  3541. * *This is fairly rare but could be the case if a third party library is injecting the
  3542. * markup.*
  3543. *
  3544. * In the following example a new block of HTML containing a `ng-controller`
  3545. * directive is added to the end of the document body by JQuery. We then compile and link
  3546. * it into the current AngularJS scope.
  3547. *
  3548. * ```js
  3549. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3550. * $(document.body).append($div);
  3551. *
  3552. * angular.element(document).injector().invoke(function($compile) {
  3553. * var scope = angular.element($div).scope();
  3554. * $compile($div)(scope);
  3555. * });
  3556. * ```
  3557. */
  3558. /**
  3559. * @ngdoc module
  3560. * @name auto
  3561. * @installation
  3562. * @description
  3563. *
  3564. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3565. */
  3566. var ARROW_ARG = /^([^(]+?)=>/;
  3567. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3568. var FN_ARG_SPLIT = /,/;
  3569. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3570. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3571. var $injectorMinErr = minErr('$injector');
  3572. function stringifyFn(fn) {
  3573. // Support: Chrome 50-51 only
  3574. // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
  3575. // (See https://github.com/angular/angular.js/issues/14487.)
  3576. // TODO (gkalpak): Remove workaround when Chrome v52 is released
  3577. return Function.prototype.toString.call(fn) + ' ';
  3578. }
  3579. function extractArgs(fn) {
  3580. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3581. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3582. return args;
  3583. }
  3584. function anonFn(fn) {
  3585. // For anonymous functions, showing at the very least the function signature can help in
  3586. // debugging.
  3587. var args = extractArgs(fn);
  3588. if (args) {
  3589. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3590. }
  3591. return 'fn';
  3592. }
  3593. function annotate(fn, strictDi, name) {
  3594. var $inject,
  3595. argDecl,
  3596. last;
  3597. if (typeof fn === 'function') {
  3598. if (!($inject = fn.$inject)) {
  3599. $inject = [];
  3600. if (fn.length) {
  3601. if (strictDi) {
  3602. if (!isString(name) || !name) {
  3603. name = fn.name || anonFn(fn);
  3604. }
  3605. throw $injectorMinErr('strictdi',
  3606. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3607. }
  3608. argDecl = extractArgs(fn);
  3609. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3610. arg.replace(FN_ARG, function(all, underscore, name) {
  3611. $inject.push(name);
  3612. });
  3613. });
  3614. }
  3615. fn.$inject = $inject;
  3616. }
  3617. } else if (isArray(fn)) {
  3618. last = fn.length - 1;
  3619. assertArgFn(fn[last], 'fn');
  3620. $inject = fn.slice(0, last);
  3621. } else {
  3622. assertArgFn(fn, 'fn', true);
  3623. }
  3624. return $inject;
  3625. }
  3626. ///////////////////////////////////////
  3627. /**
  3628. * @ngdoc service
  3629. * @name $injector
  3630. *
  3631. * @description
  3632. *
  3633. * `$injector` is used to retrieve object instances as defined by
  3634. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3635. * and load modules.
  3636. *
  3637. * The following always holds true:
  3638. *
  3639. * ```js
  3640. * var $injector = angular.injector();
  3641. * expect($injector.get('$injector')).toBe($injector);
  3642. * expect($injector.invoke(function($injector) {
  3643. * return $injector;
  3644. * })).toBe($injector);
  3645. * ```
  3646. *
  3647. * # Injection Function Annotation
  3648. *
  3649. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3650. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3651. *
  3652. * ```js
  3653. * // inferred (only works if code not minified/obfuscated)
  3654. * $injector.invoke(function(serviceA){});
  3655. *
  3656. * // annotated
  3657. * function explicit(serviceA) {};
  3658. * explicit.$inject = ['serviceA'];
  3659. * $injector.invoke(explicit);
  3660. *
  3661. * // inline
  3662. * $injector.invoke(['serviceA', function(serviceA){}]);
  3663. * ```
  3664. *
  3665. * ## Inference
  3666. *
  3667. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3668. * can then be parsed and the function arguments can be extracted. This method of discovering
  3669. * annotations is disallowed when the injector is in strict mode.
  3670. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3671. * argument names.
  3672. *
  3673. * ## `$inject` Annotation
  3674. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3675. *
  3676. * ## Inline
  3677. * As an array of injection names, where the last item in the array is the function to call.
  3678. */
  3679. /**
  3680. * @ngdoc method
  3681. * @name $injector#get
  3682. *
  3683. * @description
  3684. * Return an instance of the service.
  3685. *
  3686. * @param {string} name The name of the instance to retrieve.
  3687. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3688. * @return {*} The instance.
  3689. */
  3690. /**
  3691. * @ngdoc method
  3692. * @name $injector#invoke
  3693. *
  3694. * @description
  3695. * Invoke the method and supply the method arguments from the `$injector`.
  3696. *
  3697. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3698. * injected according to the {@link guide/di $inject Annotation} rules.
  3699. * @param {Object=} self The `this` for the invoked method.
  3700. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3701. * object first, before the `$injector` is consulted.
  3702. * @returns {*} the value returned by the invoked `fn` function.
  3703. */
  3704. /**
  3705. * @ngdoc method
  3706. * @name $injector#has
  3707. *
  3708. * @description
  3709. * Allows the user to query if the particular service exists.
  3710. *
  3711. * @param {string} name Name of the service to query.
  3712. * @returns {boolean} `true` if injector has given service.
  3713. */
  3714. /**
  3715. * @ngdoc method
  3716. * @name $injector#instantiate
  3717. * @description
  3718. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3719. * operator, and supplies all of the arguments to the constructor function as specified by the
  3720. * constructor annotation.
  3721. *
  3722. * @param {Function} Type Annotated constructor function.
  3723. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3724. * object first, before the `$injector` is consulted.
  3725. * @returns {Object} new instance of `Type`.
  3726. */
  3727. /**
  3728. * @ngdoc method
  3729. * @name $injector#annotate
  3730. *
  3731. * @description
  3732. * Returns an array of service names which the function is requesting for injection. This API is
  3733. * used by the injector to determine which services need to be injected into the function when the
  3734. * function is invoked. There are three ways in which the function can be annotated with the needed
  3735. * dependencies.
  3736. *
  3737. * # Argument names
  3738. *
  3739. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3740. * by converting the function into a string using `toString()` method and extracting the argument
  3741. * names.
  3742. * ```js
  3743. * // Given
  3744. * function MyController($scope, $route) {
  3745. * // ...
  3746. * }
  3747. *
  3748. * // Then
  3749. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3750. * ```
  3751. *
  3752. * You can disallow this method by using strict injection mode.
  3753. *
  3754. * This method does not work with code minification / obfuscation. For this reason the following
  3755. * annotation strategies are supported.
  3756. *
  3757. * # The `$inject` property
  3758. *
  3759. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3760. * represent names of services to be injected into the function.
  3761. * ```js
  3762. * // Given
  3763. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3764. * // ...
  3765. * }
  3766. * // Define function dependencies
  3767. * MyController['$inject'] = ['$scope', '$route'];
  3768. *
  3769. * // Then
  3770. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3771. * ```
  3772. *
  3773. * # The array notation
  3774. *
  3775. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3776. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3777. * a way that survives minification is a better choice:
  3778. *
  3779. * ```js
  3780. * // We wish to write this (not minification / obfuscation safe)
  3781. * injector.invoke(function($compile, $rootScope) {
  3782. * // ...
  3783. * });
  3784. *
  3785. * // We are forced to write break inlining
  3786. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3787. * // ...
  3788. * };
  3789. * tmpFn.$inject = ['$compile', '$rootScope'];
  3790. * injector.invoke(tmpFn);
  3791. *
  3792. * // To better support inline function the inline annotation is supported
  3793. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3794. * // ...
  3795. * }]);
  3796. *
  3797. * // Therefore
  3798. * expect(injector.annotate(
  3799. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3800. * ).toEqual(['$compile', '$rootScope']);
  3801. * ```
  3802. *
  3803. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3804. * be retrieved as described above.
  3805. *
  3806. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3807. *
  3808. * @returns {Array.<string>} The names of the services which the function requires.
  3809. */
  3810. /**
  3811. * @ngdoc service
  3812. * @name $provide
  3813. *
  3814. * @description
  3815. *
  3816. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3817. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3818. * {@link angular.Module}.
  3819. *
  3820. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3821. * factories** are functions which, in turn, are created by a **service provider**.
  3822. * The **service providers** are constructor functions. When instantiated they must contain a
  3823. * property called `$get`, which holds the **service factory** function.
  3824. *
  3825. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3826. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3827. * function to get the instance of the **service**.
  3828. *
  3829. * Often services have no configuration options and there is no need to add methods to the service
  3830. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3831. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3832. * services without specifying a provider.
  3833. *
  3834. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3835. * {@link auto.$injector $injector}
  3836. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3837. * providers and services.
  3838. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3839. * services, not providers.
  3840. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3841. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3842. * given factory function.
  3843. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3844. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3845. * a new object using the given constructor function.
  3846. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3847. * will be able to modify or replace the implementation of another service.
  3848. *
  3849. * See the individual methods for more information and examples.
  3850. */
  3851. /**
  3852. * @ngdoc method
  3853. * @name $provide#provider
  3854. * @description
  3855. *
  3856. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3857. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3858. * service.
  3859. *
  3860. * Service provider names start with the name of the service they provide followed by `Provider`.
  3861. * For example, the {@link ng.$log $log} service has a provider called
  3862. * {@link ng.$logProvider $logProvider}.
  3863. *
  3864. * Service provider objects can have additional methods which allow configuration of the provider
  3865. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3866. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3867. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3868. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3869. * console or not.
  3870. *
  3871. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3872. 'Provider'` key.
  3873. * @param {(Object|function())} provider If the provider is:
  3874. *
  3875. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3876. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3877. * - `Constructor`: a new instance of the provider will be created using
  3878. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3879. *
  3880. * @returns {Object} registered provider instance
  3881. * @example
  3882. *
  3883. * The following example shows how to create a simple event tracking service and register it using
  3884. * {@link auto.$provide#provider $provide.provider()}.
  3885. *
  3886. * ```js
  3887. * // Define the eventTracker provider
  3888. * function EventTrackerProvider() {
  3889. * var trackingUrl = '/track';
  3890. *
  3891. * // A provider method for configuring where the tracked events should been saved
  3892. * this.setTrackingUrl = function(url) {
  3893. * trackingUrl = url;
  3894. * };
  3895. *
  3896. * // The service factory function
  3897. * this.$get = ['$http', function($http) {
  3898. * var trackedEvents = {};
  3899. * return {
  3900. * // Call this to track an event
  3901. * event: function(event) {
  3902. * var count = trackedEvents[event] || 0;
  3903. * count += 1;
  3904. * trackedEvents[event] = count;
  3905. * return count;
  3906. * },
  3907. * // Call this to save the tracked events to the trackingUrl
  3908. * save: function() {
  3909. * $http.post(trackingUrl, trackedEvents);
  3910. * }
  3911. * };
  3912. * }];
  3913. * }
  3914. *
  3915. * describe('eventTracker', function() {
  3916. * var postSpy;
  3917. *
  3918. * beforeEach(module(function($provide) {
  3919. * // Register the eventTracker provider
  3920. * $provide.provider('eventTracker', EventTrackerProvider);
  3921. * }));
  3922. *
  3923. * beforeEach(module(function(eventTrackerProvider) {
  3924. * // Configure eventTracker provider
  3925. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3926. * }));
  3927. *
  3928. * it('tracks events', inject(function(eventTracker) {
  3929. * expect(eventTracker.event('login')).toEqual(1);
  3930. * expect(eventTracker.event('login')).toEqual(2);
  3931. * }));
  3932. *
  3933. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3934. * postSpy = spyOn($http, 'post');
  3935. * eventTracker.event('login');
  3936. * eventTracker.save();
  3937. * expect(postSpy).toHaveBeenCalled();
  3938. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3939. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3940. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3941. * }));
  3942. * });
  3943. * ```
  3944. */
  3945. /**
  3946. * @ngdoc method
  3947. * @name $provide#factory
  3948. * @description
  3949. *
  3950. * Register a **service factory**, which will be called to return the service instance.
  3951. * This is short for registering a service where its provider consists of only a `$get` property,
  3952. * which is the given service factory function.
  3953. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3954. * configure your service in a provider.
  3955. *
  3956. * @param {string} name The name of the instance.
  3957. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3958. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3959. * @returns {Object} registered provider instance
  3960. *
  3961. * @example
  3962. * Here is an example of registering a service
  3963. * ```js
  3964. * $provide.factory('ping', ['$http', function($http) {
  3965. * return function ping() {
  3966. * return $http.send('/ping');
  3967. * };
  3968. * }]);
  3969. * ```
  3970. * You would then inject and use this service like this:
  3971. * ```js
  3972. * someModule.controller('Ctrl', ['ping', function(ping) {
  3973. * ping();
  3974. * }]);
  3975. * ```
  3976. */
  3977. /**
  3978. * @ngdoc method
  3979. * @name $provide#service
  3980. * @description
  3981. *
  3982. * Register a **service constructor**, which will be invoked with `new` to create the service
  3983. * instance.
  3984. * This is short for registering a service where its provider's `$get` property is a factory
  3985. * function that returns an instance instantiated by the injector from the service constructor
  3986. * function.
  3987. *
  3988. * Internally it looks a bit like this:
  3989. *
  3990. * ```
  3991. * {
  3992. * $get: function() {
  3993. * return $injector.instantiate(constructor);
  3994. * }
  3995. * }
  3996. * ```
  3997. *
  3998. *
  3999. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4000. * as a type/class.
  4001. *
  4002. * @param {string} name The name of the instance.
  4003. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4004. * that will be instantiated.
  4005. * @returns {Object} registered provider instance
  4006. *
  4007. * @example
  4008. * Here is an example of registering a service using
  4009. * {@link auto.$provide#service $provide.service(class)}.
  4010. * ```js
  4011. * var Ping = function($http) {
  4012. * this.$http = $http;
  4013. * };
  4014. *
  4015. * Ping.$inject = ['$http'];
  4016. *
  4017. * Ping.prototype.send = function() {
  4018. * return this.$http.get('/ping');
  4019. * };
  4020. * $provide.service('ping', Ping);
  4021. * ```
  4022. * You would then inject and use this service like this:
  4023. * ```js
  4024. * someModule.controller('Ctrl', ['ping', function(ping) {
  4025. * ping.send();
  4026. * }]);
  4027. * ```
  4028. */
  4029. /**
  4030. * @ngdoc method
  4031. * @name $provide#value
  4032. * @description
  4033. *
  4034. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4035. * number, an array, an object or a function. This is short for registering a service where its
  4036. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4037. * service**. That also means it is not possible to inject other services into a value service.
  4038. *
  4039. * Value services are similar to constant services, except that they cannot be injected into a
  4040. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4041. * an Angular {@link auto.$provide#decorator decorator}.
  4042. *
  4043. * @param {string} name The name of the instance.
  4044. * @param {*} value The value.
  4045. * @returns {Object} registered provider instance
  4046. *
  4047. * @example
  4048. * Here are some examples of creating value services.
  4049. * ```js
  4050. * $provide.value('ADMIN_USER', 'admin');
  4051. *
  4052. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4053. *
  4054. * $provide.value('halfOf', function(value) {
  4055. * return value / 2;
  4056. * });
  4057. * ```
  4058. */
  4059. /**
  4060. * @ngdoc method
  4061. * @name $provide#constant
  4062. * @description
  4063. *
  4064. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4065. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4066. * possible to inject other services into a constant.
  4067. *
  4068. * But unlike {@link auto.$provide#value value}, a constant can be
  4069. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4070. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4071. *
  4072. * @param {string} name The name of the constant.
  4073. * @param {*} value The constant value.
  4074. * @returns {Object} registered instance
  4075. *
  4076. * @example
  4077. * Here a some examples of creating constants:
  4078. * ```js
  4079. * $provide.constant('SHARD_HEIGHT', 306);
  4080. *
  4081. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4082. *
  4083. * $provide.constant('double', function(value) {
  4084. * return value * 2;
  4085. * });
  4086. * ```
  4087. */
  4088. /**
  4089. * @ngdoc method
  4090. * @name $provide#decorator
  4091. * @description
  4092. *
  4093. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4094. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4095. * service. The return value of the decorator function may be the original service, or a new service
  4096. * that replaces (or wraps and delegates to) the original service.
  4097. *
  4098. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4099. *
  4100. * @param {string} name The name of the service to decorate.
  4101. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4102. * provided and should return the decorated service instance. The function is called using
  4103. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4104. * Local injection arguments:
  4105. *
  4106. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4107. * decorated or delegated to.
  4108. *
  4109. * @example
  4110. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4111. * calls to {@link ng.$log#error $log.warn()}.
  4112. * ```js
  4113. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4114. * $delegate.warn = $delegate.error;
  4115. * return $delegate;
  4116. * }]);
  4117. * ```
  4118. */
  4119. function createInjector(modulesToLoad, strictDi) {
  4120. strictDi = (strictDi === true);
  4121. var INSTANTIATING = {},
  4122. providerSuffix = 'Provider',
  4123. path = [],
  4124. loadedModules = new HashMap([], true),
  4125. providerCache = {
  4126. $provide: {
  4127. provider: supportObject(provider),
  4128. factory: supportObject(factory),
  4129. service: supportObject(service),
  4130. value: supportObject(value),
  4131. constant: supportObject(constant),
  4132. decorator: decorator
  4133. }
  4134. },
  4135. providerInjector = (providerCache.$injector =
  4136. createInternalInjector(providerCache, function(serviceName, caller) {
  4137. if (angular.isString(caller)) {
  4138. path.push(caller);
  4139. }
  4140. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4141. })),
  4142. instanceCache = {},
  4143. protoInstanceInjector =
  4144. createInternalInjector(instanceCache, function(serviceName, caller) {
  4145. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4146. return instanceInjector.invoke(
  4147. provider.$get, provider, undefined, serviceName);
  4148. }),
  4149. instanceInjector = protoInstanceInjector;
  4150. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4151. var runBlocks = loadModules(modulesToLoad);
  4152. instanceInjector = protoInstanceInjector.get('$injector');
  4153. instanceInjector.strictDi = strictDi;
  4154. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4155. return instanceInjector;
  4156. ////////////////////////////////////
  4157. // $provider
  4158. ////////////////////////////////////
  4159. function supportObject(delegate) {
  4160. return function(key, value) {
  4161. if (isObject(key)) {
  4162. forEach(key, reverseParams(delegate));
  4163. } else {
  4164. return delegate(key, value);
  4165. }
  4166. };
  4167. }
  4168. function provider(name, provider_) {
  4169. assertNotHasOwnProperty(name, 'service');
  4170. if (isFunction(provider_) || isArray(provider_)) {
  4171. provider_ = providerInjector.instantiate(provider_);
  4172. }
  4173. if (!provider_.$get) {
  4174. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4175. }
  4176. return (providerCache[name + providerSuffix] = provider_);
  4177. }
  4178. function enforceReturnValue(name, factory) {
  4179. return /** @this */ function enforcedReturnValue() {
  4180. var result = instanceInjector.invoke(factory, this);
  4181. if (isUndefined(result)) {
  4182. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4183. }
  4184. return result;
  4185. };
  4186. }
  4187. function factory(name, factoryFn, enforce) {
  4188. return provider(name, {
  4189. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4190. });
  4191. }
  4192. function service(name, constructor) {
  4193. return factory(name, ['$injector', function($injector) {
  4194. return $injector.instantiate(constructor);
  4195. }]);
  4196. }
  4197. function value(name, val) { return factory(name, valueFn(val), false); }
  4198. function constant(name, value) {
  4199. assertNotHasOwnProperty(name, 'constant');
  4200. providerCache[name] = value;
  4201. instanceCache[name] = value;
  4202. }
  4203. function decorator(serviceName, decorFn) {
  4204. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4205. orig$get = origProvider.$get;
  4206. origProvider.$get = function() {
  4207. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4208. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4209. };
  4210. }
  4211. ////////////////////////////////////
  4212. // Module Loading
  4213. ////////////////////////////////////
  4214. function loadModules(modulesToLoad) {
  4215. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4216. var runBlocks = [], moduleFn;
  4217. forEach(modulesToLoad, function(module) {
  4218. if (loadedModules.get(module)) return;
  4219. loadedModules.put(module, true);
  4220. function runInvokeQueue(queue) {
  4221. var i, ii;
  4222. for (i = 0, ii = queue.length; i < ii; i++) {
  4223. var invokeArgs = queue[i],
  4224. provider = providerInjector.get(invokeArgs[0]);
  4225. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4226. }
  4227. }
  4228. try {
  4229. if (isString(module)) {
  4230. moduleFn = angularModule(module);
  4231. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4232. runInvokeQueue(moduleFn._invokeQueue);
  4233. runInvokeQueue(moduleFn._configBlocks);
  4234. } else if (isFunction(module)) {
  4235. runBlocks.push(providerInjector.invoke(module));
  4236. } else if (isArray(module)) {
  4237. runBlocks.push(providerInjector.invoke(module));
  4238. } else {
  4239. assertArgFn(module, 'module');
  4240. }
  4241. } catch (e) {
  4242. if (isArray(module)) {
  4243. module = module[module.length - 1];
  4244. }
  4245. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4246. // Safari & FF's stack traces don't contain error.message content
  4247. // unlike those of Chrome and IE
  4248. // So if stack doesn't contain message, we create a new string that contains both.
  4249. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4250. // eslint-disable-next-line no-ex-assign
  4251. e = e.message + '\n' + e.stack;
  4252. }
  4253. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4254. module, e.stack || e.message || e);
  4255. }
  4256. });
  4257. return runBlocks;
  4258. }
  4259. ////////////////////////////////////
  4260. // internal Injector
  4261. ////////////////////////////////////
  4262. function createInternalInjector(cache, factory) {
  4263. function getService(serviceName, caller) {
  4264. if (cache.hasOwnProperty(serviceName)) {
  4265. if (cache[serviceName] === INSTANTIATING) {
  4266. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4267. serviceName + ' <- ' + path.join(' <- '));
  4268. }
  4269. return cache[serviceName];
  4270. } else {
  4271. try {
  4272. path.unshift(serviceName);
  4273. cache[serviceName] = INSTANTIATING;
  4274. cache[serviceName] = factory(serviceName, caller);
  4275. return cache[serviceName];
  4276. } catch (err) {
  4277. if (cache[serviceName] === INSTANTIATING) {
  4278. delete cache[serviceName];
  4279. }
  4280. throw err;
  4281. } finally {
  4282. path.shift();
  4283. }
  4284. }
  4285. }
  4286. function injectionArgs(fn, locals, serviceName) {
  4287. var args = [],
  4288. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4289. for (var i = 0, length = $inject.length; i < length; i++) {
  4290. var key = $inject[i];
  4291. if (typeof key !== 'string') {
  4292. throw $injectorMinErr('itkn',
  4293. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4294. }
  4295. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4296. getService(key, serviceName));
  4297. }
  4298. return args;
  4299. }
  4300. function isClass(func) {
  4301. // Support: IE 9-11 only
  4302. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4303. if (msie || typeof func !== 'function') {
  4304. return false;
  4305. }
  4306. var result = func.$$ngIsClass;
  4307. if (!isBoolean(result)) {
  4308. // Support: Edge 12-13 only
  4309. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4310. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4311. }
  4312. return result;
  4313. }
  4314. function invoke(fn, self, locals, serviceName) {
  4315. if (typeof locals === 'string') {
  4316. serviceName = locals;
  4317. locals = null;
  4318. }
  4319. var args = injectionArgs(fn, locals, serviceName);
  4320. if (isArray(fn)) {
  4321. fn = fn[fn.length - 1];
  4322. }
  4323. if (!isClass(fn)) {
  4324. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4325. // #5388
  4326. return fn.apply(self, args);
  4327. } else {
  4328. args.unshift(null);
  4329. return new (Function.prototype.bind.apply(fn, args))();
  4330. }
  4331. }
  4332. function instantiate(Type, locals, serviceName) {
  4333. // Check if Type is annotated and use just the given function at n-1 as parameter
  4334. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4335. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4336. var args = injectionArgs(Type, locals, serviceName);
  4337. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4338. args.unshift(null);
  4339. return new (Function.prototype.bind.apply(ctor, args))();
  4340. }
  4341. return {
  4342. invoke: invoke,
  4343. instantiate: instantiate,
  4344. get: getService,
  4345. annotate: createInjector.$$annotate,
  4346. has: function(name) {
  4347. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4348. }
  4349. };
  4350. }
  4351. }
  4352. createInjector.$$annotate = annotate;
  4353. /**
  4354. * @ngdoc provider
  4355. * @name $anchorScrollProvider
  4356. * @this
  4357. *
  4358. * @description
  4359. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4360. * {@link ng.$location#hash $location.hash()} changes.
  4361. */
  4362. function $AnchorScrollProvider() {
  4363. var autoScrollingEnabled = true;
  4364. /**
  4365. * @ngdoc method
  4366. * @name $anchorScrollProvider#disableAutoScrolling
  4367. *
  4368. * @description
  4369. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4370. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4371. * Use this method to disable automatic scrolling.
  4372. *
  4373. * If automatic scrolling is disabled, one must explicitly call
  4374. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4375. * current hash.
  4376. */
  4377. this.disableAutoScrolling = function() {
  4378. autoScrollingEnabled = false;
  4379. };
  4380. /**
  4381. * @ngdoc service
  4382. * @name $anchorScroll
  4383. * @kind function
  4384. * @requires $window
  4385. * @requires $location
  4386. * @requires $rootScope
  4387. *
  4388. * @description
  4389. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4390. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4391. * in the
  4392. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4393. *
  4394. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4395. * match any anchor whenever it changes. This can be disabled by calling
  4396. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4397. *
  4398. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4399. * vertical scroll-offset (either fixed or dynamic).
  4400. *
  4401. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4402. * {@link ng.$location#hash $location.hash()} will be used.
  4403. *
  4404. * @property {(number|function|jqLite)} yOffset
  4405. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4406. * positioned elements at the top of the page, such as navbars, headers etc.
  4407. *
  4408. * `yOffset` can be specified in various ways:
  4409. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4410. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4411. * a number representing the offset (in pixels).<br /><br />
  4412. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4413. * the top of the page to the element's bottom will be used as offset.<br />
  4414. * **Note**: The element will be taken into account only as long as its `position` is set to
  4415. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4416. * their height and/or positioning according to the viewport's size.
  4417. *
  4418. * <br />
  4419. * <div class="alert alert-warning">
  4420. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4421. * not some child element.
  4422. * </div>
  4423. *
  4424. * @example
  4425. <example module="anchorScrollExample" name="anchor-scroll">
  4426. <file name="index.html">
  4427. <div id="scrollArea" ng-controller="ScrollController">
  4428. <a ng-click="gotoBottom()">Go to bottom</a>
  4429. <a id="bottom"></a> You're at the bottom!
  4430. </div>
  4431. </file>
  4432. <file name="script.js">
  4433. angular.module('anchorScrollExample', [])
  4434. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4435. function($scope, $location, $anchorScroll) {
  4436. $scope.gotoBottom = function() {
  4437. // set the location.hash to the id of
  4438. // the element you wish to scroll to.
  4439. $location.hash('bottom');
  4440. // call $anchorScroll()
  4441. $anchorScroll();
  4442. };
  4443. }]);
  4444. </file>
  4445. <file name="style.css">
  4446. #scrollArea {
  4447. height: 280px;
  4448. overflow: auto;
  4449. }
  4450. #bottom {
  4451. display: block;
  4452. margin-top: 2000px;
  4453. }
  4454. </file>
  4455. </example>
  4456. *
  4457. * <hr />
  4458. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4459. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4460. *
  4461. * @example
  4462. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4463. <file name="index.html">
  4464. <div class="fixed-header" ng-controller="headerCtrl">
  4465. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4466. Go to anchor {{x}}
  4467. </a>
  4468. </div>
  4469. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4470. Anchor {{x}} of 5
  4471. </div>
  4472. </file>
  4473. <file name="script.js">
  4474. angular.module('anchorScrollOffsetExample', [])
  4475. .run(['$anchorScroll', function($anchorScroll) {
  4476. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4477. }])
  4478. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4479. function($anchorScroll, $location, $scope) {
  4480. $scope.gotoAnchor = function(x) {
  4481. var newHash = 'anchor' + x;
  4482. if ($location.hash() !== newHash) {
  4483. // set the $location.hash to `newHash` and
  4484. // $anchorScroll will automatically scroll to it
  4485. $location.hash('anchor' + x);
  4486. } else {
  4487. // call $anchorScroll() explicitly,
  4488. // since $location.hash hasn't changed
  4489. $anchorScroll();
  4490. }
  4491. };
  4492. }
  4493. ]);
  4494. </file>
  4495. <file name="style.css">
  4496. body {
  4497. padding-top: 50px;
  4498. }
  4499. .anchor {
  4500. border: 2px dashed DarkOrchid;
  4501. padding: 10px 10px 200px 10px;
  4502. }
  4503. .fixed-header {
  4504. background-color: rgba(0, 0, 0, 0.2);
  4505. height: 50px;
  4506. position: fixed;
  4507. top: 0; left: 0; right: 0;
  4508. }
  4509. .fixed-header > a {
  4510. display: inline-block;
  4511. margin: 5px 15px;
  4512. }
  4513. </file>
  4514. </example>
  4515. */
  4516. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4517. var document = $window.document;
  4518. // Helper function to get first anchor from a NodeList
  4519. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4520. // and working in all supported browsers.)
  4521. function getFirstAnchor(list) {
  4522. var result = null;
  4523. Array.prototype.some.call(list, function(element) {
  4524. if (nodeName_(element) === 'a') {
  4525. result = element;
  4526. return true;
  4527. }
  4528. });
  4529. return result;
  4530. }
  4531. function getYOffset() {
  4532. var offset = scroll.yOffset;
  4533. if (isFunction(offset)) {
  4534. offset = offset();
  4535. } else if (isElement(offset)) {
  4536. var elem = offset[0];
  4537. var style = $window.getComputedStyle(elem);
  4538. if (style.position !== 'fixed') {
  4539. offset = 0;
  4540. } else {
  4541. offset = elem.getBoundingClientRect().bottom;
  4542. }
  4543. } else if (!isNumber(offset)) {
  4544. offset = 0;
  4545. }
  4546. return offset;
  4547. }
  4548. function scrollTo(elem) {
  4549. if (elem) {
  4550. elem.scrollIntoView();
  4551. var offset = getYOffset();
  4552. if (offset) {
  4553. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4554. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4555. // top of the viewport.
  4556. //
  4557. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4558. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4559. // way down the page.
  4560. //
  4561. // This is often the case for elements near the bottom of the page.
  4562. //
  4563. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4564. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4565. // desired position.
  4566. var elemTop = elem.getBoundingClientRect().top;
  4567. $window.scrollBy(0, elemTop - offset);
  4568. }
  4569. } else {
  4570. $window.scrollTo(0, 0);
  4571. }
  4572. }
  4573. function scroll(hash) {
  4574. // Allow numeric hashes
  4575. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4576. var elm;
  4577. // empty hash, scroll to the top of the page
  4578. if (!hash) scrollTo(null);
  4579. // element with given id
  4580. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4581. // first anchor with given name :-D
  4582. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4583. // no element and hash === 'top', scroll to the top of the page
  4584. else if (hash === 'top') scrollTo(null);
  4585. }
  4586. // does not scroll when user clicks on anchor link that is currently on
  4587. // (no url change, no $location.hash() change), browser native does scroll
  4588. if (autoScrollingEnabled) {
  4589. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4590. function autoScrollWatchAction(newVal, oldVal) {
  4591. // skip the initial scroll if $location.hash is empty
  4592. if (newVal === oldVal && newVal === '') return;
  4593. jqLiteDocumentLoaded(function() {
  4594. $rootScope.$evalAsync(scroll);
  4595. });
  4596. });
  4597. }
  4598. return scroll;
  4599. }];
  4600. }
  4601. var $animateMinErr = minErr('$animate');
  4602. var ELEMENT_NODE = 1;
  4603. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4604. function mergeClasses(a,b) {
  4605. if (!a && !b) return '';
  4606. if (!a) return b;
  4607. if (!b) return a;
  4608. if (isArray(a)) a = a.join(' ');
  4609. if (isArray(b)) b = b.join(' ');
  4610. return a + ' ' + b;
  4611. }
  4612. function extractElementNode(element) {
  4613. for (var i = 0; i < element.length; i++) {
  4614. var elm = element[i];
  4615. if (elm.nodeType === ELEMENT_NODE) {
  4616. return elm;
  4617. }
  4618. }
  4619. }
  4620. function splitClasses(classes) {
  4621. if (isString(classes)) {
  4622. classes = classes.split(' ');
  4623. }
  4624. // Use createMap() to prevent class assumptions involving property names in
  4625. // Object.prototype
  4626. var obj = createMap();
  4627. forEach(classes, function(klass) {
  4628. // sometimes the split leaves empty string values
  4629. // incase extra spaces were applied to the options
  4630. if (klass.length) {
  4631. obj[klass] = true;
  4632. }
  4633. });
  4634. return obj;
  4635. }
  4636. // if any other type of options value besides an Object value is
  4637. // passed into the $animate.method() animation then this helper code
  4638. // will be run which will ignore it. While this patch is not the
  4639. // greatest solution to this, a lot of existing plugins depend on
  4640. // $animate to either call the callback (< 1.2) or return a promise
  4641. // that can be changed. This helper function ensures that the options
  4642. // are wiped clean incase a callback function is provided.
  4643. function prepareAnimateOptions(options) {
  4644. return isObject(options)
  4645. ? options
  4646. : {};
  4647. }
  4648. var $$CoreAnimateJsProvider = /** @this */ function() {
  4649. this.$get = noop;
  4650. };
  4651. // this is prefixed with Core since it conflicts with
  4652. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4653. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4654. var postDigestQueue = new HashMap();
  4655. var postDigestElements = [];
  4656. this.$get = ['$$AnimateRunner', '$rootScope',
  4657. function($$AnimateRunner, $rootScope) {
  4658. return {
  4659. enabled: noop,
  4660. on: noop,
  4661. off: noop,
  4662. pin: noop,
  4663. push: function(element, event, options, domOperation) {
  4664. if (domOperation) {
  4665. domOperation();
  4666. }
  4667. options = options || {};
  4668. if (options.from) {
  4669. element.css(options.from);
  4670. }
  4671. if (options.to) {
  4672. element.css(options.to);
  4673. }
  4674. if (options.addClass || options.removeClass) {
  4675. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4676. }
  4677. var runner = new $$AnimateRunner();
  4678. // since there are no animations to run the runner needs to be
  4679. // notified that the animation call is complete.
  4680. runner.complete();
  4681. return runner;
  4682. }
  4683. };
  4684. function updateData(data, classes, value) {
  4685. var changed = false;
  4686. if (classes) {
  4687. classes = isString(classes) ? classes.split(' ') :
  4688. isArray(classes) ? classes : [];
  4689. forEach(classes, function(className) {
  4690. if (className) {
  4691. changed = true;
  4692. data[className] = value;
  4693. }
  4694. });
  4695. }
  4696. return changed;
  4697. }
  4698. function handleCSSClassChanges() {
  4699. forEach(postDigestElements, function(element) {
  4700. var data = postDigestQueue.get(element);
  4701. if (data) {
  4702. var existing = splitClasses(element.attr('class'));
  4703. var toAdd = '';
  4704. var toRemove = '';
  4705. forEach(data, function(status, className) {
  4706. var hasClass = !!existing[className];
  4707. if (status !== hasClass) {
  4708. if (status) {
  4709. toAdd += (toAdd.length ? ' ' : '') + className;
  4710. } else {
  4711. toRemove += (toRemove.length ? ' ' : '') + className;
  4712. }
  4713. }
  4714. });
  4715. forEach(element, function(elm) {
  4716. if (toAdd) {
  4717. jqLiteAddClass(elm, toAdd);
  4718. }
  4719. if (toRemove) {
  4720. jqLiteRemoveClass(elm, toRemove);
  4721. }
  4722. });
  4723. postDigestQueue.remove(element);
  4724. }
  4725. });
  4726. postDigestElements.length = 0;
  4727. }
  4728. function addRemoveClassesPostDigest(element, add, remove) {
  4729. var data = postDigestQueue.get(element) || {};
  4730. var classesAdded = updateData(data, add, true);
  4731. var classesRemoved = updateData(data, remove, false);
  4732. if (classesAdded || classesRemoved) {
  4733. postDigestQueue.put(element, data);
  4734. postDigestElements.push(element);
  4735. if (postDigestElements.length === 1) {
  4736. $rootScope.$$postDigest(handleCSSClassChanges);
  4737. }
  4738. }
  4739. }
  4740. }];
  4741. };
  4742. /**
  4743. * @ngdoc provider
  4744. * @name $animateProvider
  4745. *
  4746. * @description
  4747. * Default implementation of $animate that doesn't perform any animations, instead just
  4748. * synchronously performs DOM updates and resolves the returned runner promise.
  4749. *
  4750. * In order to enable animations the `ngAnimate` module has to be loaded.
  4751. *
  4752. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4753. */
  4754. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4755. var provider = this;
  4756. this.$$registeredAnimations = Object.create(null);
  4757. /**
  4758. * @ngdoc method
  4759. * @name $animateProvider#register
  4760. *
  4761. * @description
  4762. * Registers a new injectable animation factory function. The factory function produces the
  4763. * animation object which contains callback functions for each event that is expected to be
  4764. * animated.
  4765. *
  4766. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4767. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4768. * on the type of animation additional arguments will be injected into the animation function. The
  4769. * list below explains the function signatures for the different animation methods:
  4770. *
  4771. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4772. * - addClass: function(element, addedClasses, doneFunction, options)
  4773. * - removeClass: function(element, removedClasses, doneFunction, options)
  4774. * - enter, leave, move: function(element, doneFunction, options)
  4775. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4776. *
  4777. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4778. *
  4779. * ```js
  4780. * return {
  4781. * //enter, leave, move signature
  4782. * eventFn : function(element, done, options) {
  4783. * //code to run the animation
  4784. * //once complete, then run done()
  4785. * return function endFunction(wasCancelled) {
  4786. * //code to cancel the animation
  4787. * }
  4788. * }
  4789. * }
  4790. * ```
  4791. *
  4792. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4793. * @param {Function} factory The factory function that will be executed to return the animation
  4794. * object.
  4795. */
  4796. this.register = function(name, factory) {
  4797. if (name && name.charAt(0) !== '.') {
  4798. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4799. }
  4800. var key = name + '-animation';
  4801. provider.$$registeredAnimations[name.substr(1)] = key;
  4802. $provide.factory(key, factory);
  4803. };
  4804. /**
  4805. * @ngdoc method
  4806. * @name $animateProvider#classNameFilter
  4807. *
  4808. * @description
  4809. * Sets and/or returns the CSS class regular expression that is checked when performing
  4810. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4811. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4812. * When setting the `classNameFilter` value, animations will only be performed on elements
  4813. * that successfully match the filter expression. This in turn can boost performance
  4814. * for low-powered devices as well as applications containing a lot of structural operations.
  4815. * @param {RegExp=} expression The className expression which will be checked against all animations
  4816. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4817. */
  4818. this.classNameFilter = function(expression) {
  4819. if (arguments.length === 1) {
  4820. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4821. if (this.$$classNameFilter) {
  4822. var reservedRegex = new RegExp('(\\s+|\\/)' + NG_ANIMATE_CLASSNAME + '(\\s+|\\/)');
  4823. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4824. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4825. }
  4826. }
  4827. }
  4828. return this.$$classNameFilter;
  4829. };
  4830. this.$get = ['$$animateQueue', function($$animateQueue) {
  4831. function domInsert(element, parentElement, afterElement) {
  4832. // if for some reason the previous element was removed
  4833. // from the dom sometime before this code runs then let's
  4834. // just stick to using the parent element as the anchor
  4835. if (afterElement) {
  4836. var afterNode = extractElementNode(afterElement);
  4837. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4838. afterElement = null;
  4839. }
  4840. }
  4841. if (afterElement) {
  4842. afterElement.after(element);
  4843. } else {
  4844. parentElement.prepend(element);
  4845. }
  4846. }
  4847. /**
  4848. * @ngdoc service
  4849. * @name $animate
  4850. * @description The $animate service exposes a series of DOM utility methods that provide support
  4851. * for animation hooks. The default behavior is the application of DOM operations, however,
  4852. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4853. * to ensure that animation runs with the triggered DOM operation.
  4854. *
  4855. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4856. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4857. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4858. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4859. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4860. *
  4861. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4862. *
  4863. * To learn more about enabling animation support, click here to visit the
  4864. * {@link ngAnimate ngAnimate module page}.
  4865. */
  4866. return {
  4867. // we don't call it directly since non-existant arguments may
  4868. // be interpreted as null within the sub enabled function
  4869. /**
  4870. *
  4871. * @ngdoc method
  4872. * @name $animate#on
  4873. * @kind function
  4874. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4875. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4876. * is fired with the following params:
  4877. *
  4878. * ```js
  4879. * $animate.on('enter', container,
  4880. * function callback(element, phase) {
  4881. * // cool we detected an enter animation within the container
  4882. * }
  4883. * );
  4884. * ```
  4885. *
  4886. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4887. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4888. * as well as among its children
  4889. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4890. *
  4891. * The arguments present in the callback function are:
  4892. * * `element` - The captured DOM element that the animation was fired on.
  4893. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4894. */
  4895. on: $$animateQueue.on,
  4896. /**
  4897. *
  4898. * @ngdoc method
  4899. * @name $animate#off
  4900. * @kind function
  4901. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4902. * can be used in three different ways depending on the arguments:
  4903. *
  4904. * ```js
  4905. * // remove all the animation event listeners listening for `enter`
  4906. * $animate.off('enter');
  4907. *
  4908. * // remove listeners for all animation events from the container element
  4909. * $animate.off(container);
  4910. *
  4911. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4912. * $animate.off('enter', container);
  4913. *
  4914. * // remove the event listener function provided by `callback` that is set
  4915. * // to listen for `enter` on the given `container` as well as its children
  4916. * $animate.off('enter', container, callback);
  4917. * ```
  4918. *
  4919. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  4920. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  4921. * arguments are ignored.
  4922. * @param {DOMElement=} container the container element the event listener was placed on
  4923. * @param {Function=} callback the callback function that was registered as the listener
  4924. */
  4925. off: $$animateQueue.off,
  4926. /**
  4927. * @ngdoc method
  4928. * @name $animate#pin
  4929. * @kind function
  4930. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4931. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4932. * element despite being outside the realm of the application or within another application. Say for example if the application
  4933. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4934. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4935. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4936. *
  4937. * Note that this feature is only active when the `ngAnimate` module is used.
  4938. *
  4939. * @param {DOMElement} element the external element that will be pinned
  4940. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4941. */
  4942. pin: $$animateQueue.pin,
  4943. /**
  4944. *
  4945. * @ngdoc method
  4946. * @name $animate#enabled
  4947. * @kind function
  4948. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4949. * function can be called in four ways:
  4950. *
  4951. * ```js
  4952. * // returns true or false
  4953. * $animate.enabled();
  4954. *
  4955. * // changes the enabled state for all animations
  4956. * $animate.enabled(false);
  4957. * $animate.enabled(true);
  4958. *
  4959. * // returns true or false if animations are enabled for an element
  4960. * $animate.enabled(element);
  4961. *
  4962. * // changes the enabled state for an element and its children
  4963. * $animate.enabled(element, true);
  4964. * $animate.enabled(element, false);
  4965. * ```
  4966. *
  4967. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4968. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4969. *
  4970. * @return {boolean} whether or not animations are enabled
  4971. */
  4972. enabled: $$animateQueue.enabled,
  4973. /**
  4974. * @ngdoc method
  4975. * @name $animate#cancel
  4976. * @kind function
  4977. * @description Cancels the provided animation.
  4978. *
  4979. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4980. */
  4981. cancel: function(runner) {
  4982. if (runner.end) {
  4983. runner.end();
  4984. }
  4985. },
  4986. /**
  4987. *
  4988. * @ngdoc method
  4989. * @name $animate#enter
  4990. * @kind function
  4991. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4992. * as the first child within the `parent` element and then triggers an animation.
  4993. * A promise is returned that will be resolved during the next digest once the animation
  4994. * has completed.
  4995. *
  4996. * @param {DOMElement} element the element which will be inserted into the DOM
  4997. * @param {DOMElement} parent the parent element which will append the element as
  4998. * a child (so long as the after element is not present)
  4999. * @param {DOMElement=} after the sibling element after which the element will be appended
  5000. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5001. * The object can have the following properties:
  5002. *
  5003. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5004. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5005. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5006. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5007. *
  5008. * @return {Promise} the animation callback promise
  5009. */
  5010. enter: function(element, parent, after, options) {
  5011. parent = parent && jqLite(parent);
  5012. after = after && jqLite(after);
  5013. parent = parent || after.parent();
  5014. domInsert(element, parent, after);
  5015. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5016. },
  5017. /**
  5018. *
  5019. * @ngdoc method
  5020. * @name $animate#move
  5021. * @kind function
  5022. * @description Inserts (moves) the element into its new position in the DOM either after
  5023. * the `after` element (if provided) or as the first child within the `parent` element
  5024. * and then triggers an animation. A promise is returned that will be resolved
  5025. * during the next digest once the animation has completed.
  5026. *
  5027. * @param {DOMElement} element the element which will be moved into the new DOM position
  5028. * @param {DOMElement} parent the parent element which will append the element as
  5029. * a child (so long as the after element is not present)
  5030. * @param {DOMElement=} after the sibling element after which the element will be appended
  5031. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5032. * The object can have the following properties:
  5033. *
  5034. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5035. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5036. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5037. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5038. *
  5039. * @return {Promise} the animation callback promise
  5040. */
  5041. move: function(element, parent, after, options) {
  5042. parent = parent && jqLite(parent);
  5043. after = after && jqLite(after);
  5044. parent = parent || after.parent();
  5045. domInsert(element, parent, after);
  5046. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5047. },
  5048. /**
  5049. * @ngdoc method
  5050. * @name $animate#leave
  5051. * @kind function
  5052. * @description Triggers an animation and then removes the element from the DOM.
  5053. * When the function is called a promise is returned that will be resolved during the next
  5054. * digest once the animation has completed.
  5055. *
  5056. * @param {DOMElement} element the element which will be removed from the DOM
  5057. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5058. * The object can have the following properties:
  5059. *
  5060. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5061. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5062. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5063. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5064. *
  5065. * @return {Promise} the animation callback promise
  5066. */
  5067. leave: function(element, options) {
  5068. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5069. element.remove();
  5070. });
  5071. },
  5072. /**
  5073. * @ngdoc method
  5074. * @name $animate#addClass
  5075. * @kind function
  5076. *
  5077. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5078. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5079. * animation if element already contains the CSS class or if the class is removed at a later step.
  5080. * Note that class-based animations are treated differently compared to structural animations
  5081. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5082. * depending if CSS or JavaScript animations are used.
  5083. *
  5084. * @param {DOMElement} element the element which the CSS classes will be applied to
  5085. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5086. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5087. * The object can have the following properties:
  5088. *
  5089. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5090. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5091. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5092. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5093. *
  5094. * @return {Promise} the animation callback promise
  5095. */
  5096. addClass: function(element, className, options) {
  5097. options = prepareAnimateOptions(options);
  5098. options.addClass = mergeClasses(options.addclass, className);
  5099. return $$animateQueue.push(element, 'addClass', options);
  5100. },
  5101. /**
  5102. * @ngdoc method
  5103. * @name $animate#removeClass
  5104. * @kind function
  5105. *
  5106. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5107. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5108. * animation if element does not contain the CSS class or if the class is added at a later step.
  5109. * Note that class-based animations are treated differently compared to structural animations
  5110. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5111. * depending if CSS or JavaScript animations are used.
  5112. *
  5113. * @param {DOMElement} element the element which the CSS classes will be applied to
  5114. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5115. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5116. * The object can have the following properties:
  5117. *
  5118. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5119. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5120. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5121. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5122. *
  5123. * @return {Promise} the animation callback promise
  5124. */
  5125. removeClass: function(element, className, options) {
  5126. options = prepareAnimateOptions(options);
  5127. options.removeClass = mergeClasses(options.removeClass, className);
  5128. return $$animateQueue.push(element, 'removeClass', options);
  5129. },
  5130. /**
  5131. * @ngdoc method
  5132. * @name $animate#setClass
  5133. * @kind function
  5134. *
  5135. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5136. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5137. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5138. * passed. Note that class-based animations are treated differently compared to structural animations
  5139. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5140. * depending if CSS or JavaScript animations are used.
  5141. *
  5142. * @param {DOMElement} element the element which the CSS classes will be applied to
  5143. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5144. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5145. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5146. * The object can have the following properties:
  5147. *
  5148. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5149. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5150. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5151. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5152. *
  5153. * @return {Promise} the animation callback promise
  5154. */
  5155. setClass: function(element, add, remove, options) {
  5156. options = prepareAnimateOptions(options);
  5157. options.addClass = mergeClasses(options.addClass, add);
  5158. options.removeClass = mergeClasses(options.removeClass, remove);
  5159. return $$animateQueue.push(element, 'setClass', options);
  5160. },
  5161. /**
  5162. * @ngdoc method
  5163. * @name $animate#animate
  5164. * @kind function
  5165. *
  5166. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5167. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5168. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5169. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5170. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5171. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5172. * method (or as part of the `options` parameter):
  5173. *
  5174. * ```js
  5175. * ngModule.animation('.my-inline-animation', function() {
  5176. * return {
  5177. * animate : function(element, from, to, done, options) {
  5178. * //animation
  5179. * done();
  5180. * }
  5181. * }
  5182. * });
  5183. * ```
  5184. *
  5185. * @param {DOMElement} element the element which the CSS styles will be applied to
  5186. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5187. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5188. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5189. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5190. * (Note that if no animation is detected then this value will not be applied to the element.)
  5191. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5192. * The object can have the following properties:
  5193. *
  5194. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5195. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5196. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5197. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5198. *
  5199. * @return {Promise} the animation callback promise
  5200. */
  5201. animate: function(element, from, to, className, options) {
  5202. options = prepareAnimateOptions(options);
  5203. options.from = options.from ? extend(options.from, from) : from;
  5204. options.to = options.to ? extend(options.to, to) : to;
  5205. className = className || 'ng-inline-animate';
  5206. options.tempClasses = mergeClasses(options.tempClasses, className);
  5207. return $$animateQueue.push(element, 'animate', options);
  5208. }
  5209. };
  5210. }];
  5211. }];
  5212. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5213. this.$get = ['$$rAF', function($$rAF) {
  5214. var waitQueue = [];
  5215. function waitForTick(fn) {
  5216. waitQueue.push(fn);
  5217. if (waitQueue.length > 1) return;
  5218. $$rAF(function() {
  5219. for (var i = 0; i < waitQueue.length; i++) {
  5220. waitQueue[i]();
  5221. }
  5222. waitQueue = [];
  5223. });
  5224. }
  5225. return function() {
  5226. var passed = false;
  5227. waitForTick(function() {
  5228. passed = true;
  5229. });
  5230. return function(callback) {
  5231. if (passed) {
  5232. callback();
  5233. } else {
  5234. waitForTick(callback);
  5235. }
  5236. };
  5237. };
  5238. }];
  5239. };
  5240. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5241. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5242. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5243. var INITIAL_STATE = 0;
  5244. var DONE_PENDING_STATE = 1;
  5245. var DONE_COMPLETE_STATE = 2;
  5246. AnimateRunner.chain = function(chain, callback) {
  5247. var index = 0;
  5248. next();
  5249. function next() {
  5250. if (index === chain.length) {
  5251. callback(true);
  5252. return;
  5253. }
  5254. chain[index](function(response) {
  5255. if (response === false) {
  5256. callback(false);
  5257. return;
  5258. }
  5259. index++;
  5260. next();
  5261. });
  5262. }
  5263. };
  5264. AnimateRunner.all = function(runners, callback) {
  5265. var count = 0;
  5266. var status = true;
  5267. forEach(runners, function(runner) {
  5268. runner.done(onProgress);
  5269. });
  5270. function onProgress(response) {
  5271. status = status && response;
  5272. if (++count === runners.length) {
  5273. callback(status);
  5274. }
  5275. }
  5276. };
  5277. function AnimateRunner(host) {
  5278. this.setHost(host);
  5279. var rafTick = $$animateAsyncRun();
  5280. var timeoutTick = function(fn) {
  5281. $timeout(fn, 0, false);
  5282. };
  5283. this._doneCallbacks = [];
  5284. this._tick = function(fn) {
  5285. if ($$isDocumentHidden()) {
  5286. timeoutTick(fn);
  5287. } else {
  5288. rafTick(fn);
  5289. }
  5290. };
  5291. this._state = 0;
  5292. }
  5293. AnimateRunner.prototype = {
  5294. setHost: function(host) {
  5295. this.host = host || {};
  5296. },
  5297. done: function(fn) {
  5298. if (this._state === DONE_COMPLETE_STATE) {
  5299. fn();
  5300. } else {
  5301. this._doneCallbacks.push(fn);
  5302. }
  5303. },
  5304. progress: noop,
  5305. getPromise: function() {
  5306. if (!this.promise) {
  5307. var self = this;
  5308. this.promise = $q(function(resolve, reject) {
  5309. self.done(function(status) {
  5310. if (status === false) {
  5311. reject();
  5312. } else {
  5313. resolve();
  5314. }
  5315. });
  5316. });
  5317. }
  5318. return this.promise;
  5319. },
  5320. then: function(resolveHandler, rejectHandler) {
  5321. return this.getPromise().then(resolveHandler, rejectHandler);
  5322. },
  5323. 'catch': function(handler) {
  5324. return this.getPromise()['catch'](handler);
  5325. },
  5326. 'finally': function(handler) {
  5327. return this.getPromise()['finally'](handler);
  5328. },
  5329. pause: function() {
  5330. if (this.host.pause) {
  5331. this.host.pause();
  5332. }
  5333. },
  5334. resume: function() {
  5335. if (this.host.resume) {
  5336. this.host.resume();
  5337. }
  5338. },
  5339. end: function() {
  5340. if (this.host.end) {
  5341. this.host.end();
  5342. }
  5343. this._resolve(true);
  5344. },
  5345. cancel: function() {
  5346. if (this.host.cancel) {
  5347. this.host.cancel();
  5348. }
  5349. this._resolve(false);
  5350. },
  5351. complete: function(response) {
  5352. var self = this;
  5353. if (self._state === INITIAL_STATE) {
  5354. self._state = DONE_PENDING_STATE;
  5355. self._tick(function() {
  5356. self._resolve(response);
  5357. });
  5358. }
  5359. },
  5360. _resolve: function(response) {
  5361. if (this._state !== DONE_COMPLETE_STATE) {
  5362. forEach(this._doneCallbacks, function(fn) {
  5363. fn(response);
  5364. });
  5365. this._doneCallbacks.length = 0;
  5366. this._state = DONE_COMPLETE_STATE;
  5367. }
  5368. }
  5369. };
  5370. return AnimateRunner;
  5371. }];
  5372. };
  5373. /* exported $CoreAnimateCssProvider */
  5374. /**
  5375. * @ngdoc service
  5376. * @name $animateCss
  5377. * @kind object
  5378. * @this
  5379. *
  5380. * @description
  5381. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5382. * then the `$animateCss` service will actually perform animations.
  5383. *
  5384. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5385. */
  5386. var $CoreAnimateCssProvider = function() {
  5387. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5388. return function(element, initialOptions) {
  5389. // all of the animation functions should create
  5390. // a copy of the options data, however, if a
  5391. // parent service has already created a copy then
  5392. // we should stick to using that
  5393. var options = initialOptions || {};
  5394. if (!options.$$prepared) {
  5395. options = copy(options);
  5396. }
  5397. // there is no point in applying the styles since
  5398. // there is no animation that goes on at all in
  5399. // this version of $animateCss.
  5400. if (options.cleanupStyles) {
  5401. options.from = options.to = null;
  5402. }
  5403. if (options.from) {
  5404. element.css(options.from);
  5405. options.from = null;
  5406. }
  5407. var closed, runner = new $$AnimateRunner();
  5408. return {
  5409. start: run,
  5410. end: run
  5411. };
  5412. function run() {
  5413. $$rAF(function() {
  5414. applyAnimationContents();
  5415. if (!closed) {
  5416. runner.complete();
  5417. }
  5418. closed = true;
  5419. });
  5420. return runner;
  5421. }
  5422. function applyAnimationContents() {
  5423. if (options.addClass) {
  5424. element.addClass(options.addClass);
  5425. options.addClass = null;
  5426. }
  5427. if (options.removeClass) {
  5428. element.removeClass(options.removeClass);
  5429. options.removeClass = null;
  5430. }
  5431. if (options.to) {
  5432. element.css(options.to);
  5433. options.to = null;
  5434. }
  5435. }
  5436. };
  5437. }];
  5438. };
  5439. /* global stripHash: true */
  5440. /**
  5441. * ! This is a private undocumented service !
  5442. *
  5443. * @name $browser
  5444. * @requires $log
  5445. * @description
  5446. * This object has two goals:
  5447. *
  5448. * - hide all the global state in the browser caused by the window object
  5449. * - abstract away all the browser specific features and inconsistencies
  5450. *
  5451. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5452. * service, which can be used for convenient testing of the application without the interaction with
  5453. * the real browser apis.
  5454. */
  5455. /**
  5456. * @param {object} window The global window object.
  5457. * @param {object} document jQuery wrapped document.
  5458. * @param {object} $log window.console or an object with the same interface.
  5459. * @param {object} $sniffer $sniffer service
  5460. */
  5461. function Browser(window, document, $log, $sniffer) {
  5462. var self = this,
  5463. location = window.location,
  5464. history = window.history,
  5465. setTimeout = window.setTimeout,
  5466. clearTimeout = window.clearTimeout,
  5467. pendingDeferIds = {};
  5468. self.isMock = false;
  5469. var outstandingRequestCount = 0;
  5470. var outstandingRequestCallbacks = [];
  5471. // TODO(vojta): remove this temporary api
  5472. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5473. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5474. /**
  5475. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5476. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5477. */
  5478. function completeOutstandingRequest(fn) {
  5479. try {
  5480. fn.apply(null, sliceArgs(arguments, 1));
  5481. } finally {
  5482. outstandingRequestCount--;
  5483. if (outstandingRequestCount === 0) {
  5484. while (outstandingRequestCallbacks.length) {
  5485. try {
  5486. outstandingRequestCallbacks.pop()();
  5487. } catch (e) {
  5488. $log.error(e);
  5489. }
  5490. }
  5491. }
  5492. }
  5493. }
  5494. function getHash(url) {
  5495. var index = url.indexOf('#');
  5496. return index === -1 ? '' : url.substr(index);
  5497. }
  5498. /**
  5499. * @private
  5500. * Note: this method is used only by scenario runner
  5501. * TODO(vojta): prefix this method with $$ ?
  5502. * @param {function()} callback Function that will be called when no outstanding request
  5503. */
  5504. self.notifyWhenNoOutstandingRequests = function(callback) {
  5505. if (outstandingRequestCount === 0) {
  5506. callback();
  5507. } else {
  5508. outstandingRequestCallbacks.push(callback);
  5509. }
  5510. };
  5511. //////////////////////////////////////////////////////////////
  5512. // URL API
  5513. //////////////////////////////////////////////////////////////
  5514. var cachedState, lastHistoryState,
  5515. lastBrowserUrl = location.href,
  5516. baseElement = document.find('base'),
  5517. pendingLocation = null,
  5518. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5519. try {
  5520. return history.state;
  5521. } catch (e) {
  5522. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5523. }
  5524. };
  5525. cacheState();
  5526. lastHistoryState = cachedState;
  5527. /**
  5528. * @name $browser#url
  5529. *
  5530. * @description
  5531. * GETTER:
  5532. * Without any argument, this method just returns current value of location.href.
  5533. *
  5534. * SETTER:
  5535. * With at least one argument, this method sets url to new value.
  5536. * If html5 history api supported, pushState/replaceState is used, otherwise
  5537. * location.href/location.replace is used.
  5538. * Returns its own instance to allow chaining
  5539. *
  5540. * NOTE: this api is intended for use only by the $location service. Please use the
  5541. * {@link ng.$location $location service} to change url.
  5542. *
  5543. * @param {string} url New url (when used as setter)
  5544. * @param {boolean=} replace Should new url replace current history record?
  5545. * @param {object=} state object to use with pushState/replaceState
  5546. */
  5547. self.url = function(url, replace, state) {
  5548. // In modern browsers `history.state` is `null` by default; treating it separately
  5549. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5550. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5551. if (isUndefined(state)) {
  5552. state = null;
  5553. }
  5554. // Android Browser BFCache causes location, history reference to become stale.
  5555. if (location !== window.location) location = window.location;
  5556. if (history !== window.history) history = window.history;
  5557. // setter
  5558. if (url) {
  5559. var sameState = lastHistoryState === state;
  5560. // Don't change anything if previous and current URLs and states match. This also prevents
  5561. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5562. // See https://github.com/angular/angular.js/commit/ffb2701
  5563. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5564. return self;
  5565. }
  5566. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5567. lastBrowserUrl = url;
  5568. lastHistoryState = state;
  5569. // Don't use history API if only the hash changed
  5570. // due to a bug in IE10/IE11 which leads
  5571. // to not firing a `hashchange` nor `popstate` event
  5572. // in some cases (see #9143).
  5573. if ($sniffer.history && (!sameBase || !sameState)) {
  5574. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5575. cacheState();
  5576. // Do the assignment again so that those two variables are referentially identical.
  5577. lastHistoryState = cachedState;
  5578. } else {
  5579. if (!sameBase) {
  5580. pendingLocation = url;
  5581. }
  5582. if (replace) {
  5583. location.replace(url);
  5584. } else if (!sameBase) {
  5585. location.href = url;
  5586. } else {
  5587. location.hash = getHash(url);
  5588. }
  5589. if (location.href !== url) {
  5590. pendingLocation = url;
  5591. }
  5592. }
  5593. if (pendingLocation) {
  5594. pendingLocation = url;
  5595. }
  5596. return self;
  5597. // getter
  5598. } else {
  5599. // - pendingLocation is needed as browsers don't allow to read out
  5600. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5601. // https://openradar.appspot.com/22186109).
  5602. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5603. return pendingLocation || location.href.replace(/%27/g,'\'');
  5604. }
  5605. };
  5606. /**
  5607. * @name $browser#state
  5608. *
  5609. * @description
  5610. * This method is a getter.
  5611. *
  5612. * Return history.state or null if history.state is undefined.
  5613. *
  5614. * @returns {object} state
  5615. */
  5616. self.state = function() {
  5617. return cachedState;
  5618. };
  5619. var urlChangeListeners = [],
  5620. urlChangeInit = false;
  5621. function cacheStateAndFireUrlChange() {
  5622. pendingLocation = null;
  5623. cacheState();
  5624. fireUrlChange();
  5625. }
  5626. // This variable should be used *only* inside the cacheState function.
  5627. var lastCachedState = null;
  5628. function cacheState() {
  5629. // This should be the only place in $browser where `history.state` is read.
  5630. cachedState = getCurrentState();
  5631. cachedState = isUndefined(cachedState) ? null : cachedState;
  5632. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5633. if (equals(cachedState, lastCachedState)) {
  5634. cachedState = lastCachedState;
  5635. }
  5636. lastCachedState = cachedState;
  5637. }
  5638. function fireUrlChange() {
  5639. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5640. return;
  5641. }
  5642. lastBrowserUrl = self.url();
  5643. lastHistoryState = cachedState;
  5644. forEach(urlChangeListeners, function(listener) {
  5645. listener(self.url(), cachedState);
  5646. });
  5647. }
  5648. /**
  5649. * @name $browser#onUrlChange
  5650. *
  5651. * @description
  5652. * Register callback function that will be called, when url changes.
  5653. *
  5654. * It's only called when the url is changed from outside of angular:
  5655. * - user types different url into address bar
  5656. * - user clicks on history (forward/back) button
  5657. * - user clicks on a link
  5658. *
  5659. * It's not called when url is changed by $browser.url() method
  5660. *
  5661. * The listener gets called with new url as parameter.
  5662. *
  5663. * NOTE: this api is intended for use only by the $location service. Please use the
  5664. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5665. *
  5666. * @param {function(string)} listener Listener function to be called when url changes.
  5667. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5668. */
  5669. self.onUrlChange = function(callback) {
  5670. // TODO(vojta): refactor to use node's syntax for events
  5671. if (!urlChangeInit) {
  5672. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5673. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5674. // changed by push/replaceState
  5675. // html5 history api - popstate event
  5676. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5677. // hashchange event
  5678. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5679. urlChangeInit = true;
  5680. }
  5681. urlChangeListeners.push(callback);
  5682. return callback;
  5683. };
  5684. /**
  5685. * @private
  5686. * Remove popstate and hashchange handler from window.
  5687. *
  5688. * NOTE: this api is intended for use only by $rootScope.
  5689. */
  5690. self.$$applicationDestroyed = function() {
  5691. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5692. };
  5693. /**
  5694. * Checks whether the url has changed outside of Angular.
  5695. * Needs to be exported to be able to check for changes that have been done in sync,
  5696. * as hashchange/popstate events fire in async.
  5697. */
  5698. self.$$checkUrlChange = fireUrlChange;
  5699. //////////////////////////////////////////////////////////////
  5700. // Misc API
  5701. //////////////////////////////////////////////////////////////
  5702. /**
  5703. * @name $browser#baseHref
  5704. *
  5705. * @description
  5706. * Returns current <base href>
  5707. * (always relative - without domain)
  5708. *
  5709. * @returns {string} The current base href
  5710. */
  5711. self.baseHref = function() {
  5712. var href = baseElement.attr('href');
  5713. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  5714. };
  5715. /**
  5716. * @name $browser#defer
  5717. * @param {function()} fn A function, who's execution should be deferred.
  5718. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5719. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5720. *
  5721. * @description
  5722. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5723. *
  5724. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5725. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5726. * via `$browser.defer.flush()`.
  5727. *
  5728. */
  5729. self.defer = function(fn, delay) {
  5730. var timeoutId;
  5731. outstandingRequestCount++;
  5732. timeoutId = setTimeout(function() {
  5733. delete pendingDeferIds[timeoutId];
  5734. completeOutstandingRequest(fn);
  5735. }, delay || 0);
  5736. pendingDeferIds[timeoutId] = true;
  5737. return timeoutId;
  5738. };
  5739. /**
  5740. * @name $browser#defer.cancel
  5741. *
  5742. * @description
  5743. * Cancels a deferred task identified with `deferId`.
  5744. *
  5745. * @param {*} deferId Token returned by the `$browser.defer` function.
  5746. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5747. * canceled.
  5748. */
  5749. self.defer.cancel = function(deferId) {
  5750. if (pendingDeferIds[deferId]) {
  5751. delete pendingDeferIds[deferId];
  5752. clearTimeout(deferId);
  5753. completeOutstandingRequest(noop);
  5754. return true;
  5755. }
  5756. return false;
  5757. };
  5758. }
  5759. /** @this */
  5760. function $BrowserProvider() {
  5761. this.$get = ['$window', '$log', '$sniffer', '$document',
  5762. function($window, $log, $sniffer, $document) {
  5763. return new Browser($window, $document, $log, $sniffer);
  5764. }];
  5765. }
  5766. /**
  5767. * @ngdoc service
  5768. * @name $cacheFactory
  5769. * @this
  5770. *
  5771. * @description
  5772. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5773. * them.
  5774. *
  5775. * ```js
  5776. *
  5777. * var cache = $cacheFactory('cacheId');
  5778. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5779. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5780. *
  5781. * cache.put("key", "value");
  5782. * cache.put("another key", "another value");
  5783. *
  5784. * // We've specified no options on creation
  5785. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5786. *
  5787. * ```
  5788. *
  5789. *
  5790. * @param {string} cacheId Name or id of the newly created cache.
  5791. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5792. *
  5793. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5794. *
  5795. * @returns {object} Newly created cache object with the following set of methods:
  5796. *
  5797. * - `{object}` `info()` — Returns id, size, and options of cache.
  5798. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5799. * it.
  5800. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5801. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5802. * - `{void}` `removeAll()` — Removes all cached values.
  5803. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5804. *
  5805. * @example
  5806. <example module="cacheExampleApp" name="cache-factory">
  5807. <file name="index.html">
  5808. <div ng-controller="CacheController">
  5809. <input ng-model="newCacheKey" placeholder="Key">
  5810. <input ng-model="newCacheValue" placeholder="Value">
  5811. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5812. <p ng-if="keys.length">Cached Values</p>
  5813. <div ng-repeat="key in keys">
  5814. <span ng-bind="key"></span>
  5815. <span>: </span>
  5816. <b ng-bind="cache.get(key)"></b>
  5817. </div>
  5818. <p>Cache Info</p>
  5819. <div ng-repeat="(key, value) in cache.info()">
  5820. <span ng-bind="key"></span>
  5821. <span>: </span>
  5822. <b ng-bind="value"></b>
  5823. </div>
  5824. </div>
  5825. </file>
  5826. <file name="script.js">
  5827. angular.module('cacheExampleApp', []).
  5828. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5829. $scope.keys = [];
  5830. $scope.cache = $cacheFactory('cacheId');
  5831. $scope.put = function(key, value) {
  5832. if (angular.isUndefined($scope.cache.get(key))) {
  5833. $scope.keys.push(key);
  5834. }
  5835. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5836. };
  5837. }]);
  5838. </file>
  5839. <file name="style.css">
  5840. p {
  5841. margin: 10px 0 3px;
  5842. }
  5843. </file>
  5844. </example>
  5845. */
  5846. function $CacheFactoryProvider() {
  5847. this.$get = function() {
  5848. var caches = {};
  5849. function cacheFactory(cacheId, options) {
  5850. if (cacheId in caches) {
  5851. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  5852. }
  5853. var size = 0,
  5854. stats = extend({}, options, {id: cacheId}),
  5855. data = createMap(),
  5856. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5857. lruHash = createMap(),
  5858. freshEnd = null,
  5859. staleEnd = null;
  5860. /**
  5861. * @ngdoc type
  5862. * @name $cacheFactory.Cache
  5863. *
  5864. * @description
  5865. * A cache object used to store and retrieve data, primarily used by
  5866. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5867. * templates and other data.
  5868. *
  5869. * ```js
  5870. * angular.module('superCache')
  5871. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5872. * return $cacheFactory('super-cache');
  5873. * }]);
  5874. * ```
  5875. *
  5876. * Example test:
  5877. *
  5878. * ```js
  5879. * it('should behave like a cache', inject(function(superCache) {
  5880. * superCache.put('key', 'value');
  5881. * superCache.put('another key', 'another value');
  5882. *
  5883. * expect(superCache.info()).toEqual({
  5884. * id: 'super-cache',
  5885. * size: 2
  5886. * });
  5887. *
  5888. * superCache.remove('another key');
  5889. * expect(superCache.get('another key')).toBeUndefined();
  5890. *
  5891. * superCache.removeAll();
  5892. * expect(superCache.info()).toEqual({
  5893. * id: 'super-cache',
  5894. * size: 0
  5895. * });
  5896. * }));
  5897. * ```
  5898. */
  5899. return (caches[cacheId] = {
  5900. /**
  5901. * @ngdoc method
  5902. * @name $cacheFactory.Cache#put
  5903. * @kind function
  5904. *
  5905. * @description
  5906. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5907. * retrieved later, and incrementing the size of the cache if the key was not already
  5908. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5909. * entries from the set.
  5910. *
  5911. * It will not insert undefined values into the cache.
  5912. *
  5913. * @param {string} key the key under which the cached data is stored.
  5914. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5915. * will not be stored.
  5916. * @returns {*} the value stored.
  5917. */
  5918. put: function(key, value) {
  5919. if (isUndefined(value)) return;
  5920. if (capacity < Number.MAX_VALUE) {
  5921. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5922. refresh(lruEntry);
  5923. }
  5924. if (!(key in data)) size++;
  5925. data[key] = value;
  5926. if (size > capacity) {
  5927. this.remove(staleEnd.key);
  5928. }
  5929. return value;
  5930. },
  5931. /**
  5932. * @ngdoc method
  5933. * @name $cacheFactory.Cache#get
  5934. * @kind function
  5935. *
  5936. * @description
  5937. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5938. *
  5939. * @param {string} key the key of the data to be retrieved
  5940. * @returns {*} the value stored.
  5941. */
  5942. get: function(key) {
  5943. if (capacity < Number.MAX_VALUE) {
  5944. var lruEntry = lruHash[key];
  5945. if (!lruEntry) return;
  5946. refresh(lruEntry);
  5947. }
  5948. return data[key];
  5949. },
  5950. /**
  5951. * @ngdoc method
  5952. * @name $cacheFactory.Cache#remove
  5953. * @kind function
  5954. *
  5955. * @description
  5956. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5957. *
  5958. * @param {string} key the key of the entry to be removed
  5959. */
  5960. remove: function(key) {
  5961. if (capacity < Number.MAX_VALUE) {
  5962. var lruEntry = lruHash[key];
  5963. if (!lruEntry) return;
  5964. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  5965. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  5966. link(lruEntry.n,lruEntry.p);
  5967. delete lruHash[key];
  5968. }
  5969. if (!(key in data)) return;
  5970. delete data[key];
  5971. size--;
  5972. },
  5973. /**
  5974. * @ngdoc method
  5975. * @name $cacheFactory.Cache#removeAll
  5976. * @kind function
  5977. *
  5978. * @description
  5979. * Clears the cache object of any entries.
  5980. */
  5981. removeAll: function() {
  5982. data = createMap();
  5983. size = 0;
  5984. lruHash = createMap();
  5985. freshEnd = staleEnd = null;
  5986. },
  5987. /**
  5988. * @ngdoc method
  5989. * @name $cacheFactory.Cache#destroy
  5990. * @kind function
  5991. *
  5992. * @description
  5993. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5994. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5995. */
  5996. destroy: function() {
  5997. data = null;
  5998. stats = null;
  5999. lruHash = null;
  6000. delete caches[cacheId];
  6001. },
  6002. /**
  6003. * @ngdoc method
  6004. * @name $cacheFactory.Cache#info
  6005. * @kind function
  6006. *
  6007. * @description
  6008. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6009. *
  6010. * @returns {object} an object with the following properties:
  6011. * <ul>
  6012. * <li>**id**: the id of the cache instance</li>
  6013. * <li>**size**: the number of entries kept in the cache instance</li>
  6014. * <li>**...**: any additional properties from the options object when creating the
  6015. * cache.</li>
  6016. * </ul>
  6017. */
  6018. info: function() {
  6019. return extend({}, stats, {size: size});
  6020. }
  6021. });
  6022. /**
  6023. * makes the `entry` the freshEnd of the LRU linked list
  6024. */
  6025. function refresh(entry) {
  6026. if (entry !== freshEnd) {
  6027. if (!staleEnd) {
  6028. staleEnd = entry;
  6029. } else if (staleEnd === entry) {
  6030. staleEnd = entry.n;
  6031. }
  6032. link(entry.n, entry.p);
  6033. link(entry, freshEnd);
  6034. freshEnd = entry;
  6035. freshEnd.n = null;
  6036. }
  6037. }
  6038. /**
  6039. * bidirectionally links two entries of the LRU linked list
  6040. */
  6041. function link(nextEntry, prevEntry) {
  6042. if (nextEntry !== prevEntry) {
  6043. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6044. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6045. }
  6046. }
  6047. }
  6048. /**
  6049. * @ngdoc method
  6050. * @name $cacheFactory#info
  6051. *
  6052. * @description
  6053. * Get information about all the caches that have been created
  6054. *
  6055. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6056. */
  6057. cacheFactory.info = function() {
  6058. var info = {};
  6059. forEach(caches, function(cache, cacheId) {
  6060. info[cacheId] = cache.info();
  6061. });
  6062. return info;
  6063. };
  6064. /**
  6065. * @ngdoc method
  6066. * @name $cacheFactory#get
  6067. *
  6068. * @description
  6069. * Get access to a cache object by the `cacheId` used when it was created.
  6070. *
  6071. * @param {string} cacheId Name or id of a cache to access.
  6072. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6073. */
  6074. cacheFactory.get = function(cacheId) {
  6075. return caches[cacheId];
  6076. };
  6077. return cacheFactory;
  6078. };
  6079. }
  6080. /**
  6081. * @ngdoc service
  6082. * @name $templateCache
  6083. * @this
  6084. *
  6085. * @description
  6086. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6087. * can load templates directly into the cache in a `script` tag, or by consuming the
  6088. * `$templateCache` service directly.
  6089. *
  6090. * Adding via the `script` tag:
  6091. *
  6092. * ```html
  6093. * <script type="text/ng-template" id="templateId.html">
  6094. * <p>This is the content of the template</p>
  6095. * </script>
  6096. * ```
  6097. *
  6098. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6099. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6100. * element with ng-app attribute), otherwise the template will be ignored.
  6101. *
  6102. * Adding via the `$templateCache` service:
  6103. *
  6104. * ```js
  6105. * var myApp = angular.module('myApp', []);
  6106. * myApp.run(function($templateCache) {
  6107. * $templateCache.put('templateId.html', 'This is the content of the template');
  6108. * });
  6109. * ```
  6110. *
  6111. * To retrieve the template later, simply use it in your component:
  6112. * ```js
  6113. * myApp.component('myComponent', {
  6114. * templateUrl: 'templateId.html'
  6115. * });
  6116. * ```
  6117. *
  6118. * or get it via the `$templateCache` service:
  6119. * ```js
  6120. * $templateCache.get('templateId.html')
  6121. * ```
  6122. *
  6123. * See {@link ng.$cacheFactory $cacheFactory}.
  6124. *
  6125. */
  6126. function $TemplateCacheProvider() {
  6127. this.$get = ['$cacheFactory', function($cacheFactory) {
  6128. return $cacheFactory('templates');
  6129. }];
  6130. }
  6131. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6132. * Any commits to this file should be reviewed with security in mind. *
  6133. * Changes to this file can potentially create security vulnerabilities. *
  6134. * An approval from 2 Core members with history of modifying *
  6135. * this file is required. *
  6136. * *
  6137. * Does the change somehow allow for arbitrary javascript to be executed? *
  6138. * Or allows for someone to change the prototype of built-in objects? *
  6139. * Or gives undesired access to variables like document or window? *
  6140. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6141. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6142. *
  6143. * DOM-related variables:
  6144. *
  6145. * - "node" - DOM Node
  6146. * - "element" - DOM Element or Node
  6147. * - "$node" or "$element" - jqLite-wrapped node or element
  6148. *
  6149. *
  6150. * Compiler related stuff:
  6151. *
  6152. * - "linkFn" - linking fn of a single directive
  6153. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6154. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6155. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6156. */
  6157. /**
  6158. * @ngdoc service
  6159. * @name $compile
  6160. * @kind function
  6161. *
  6162. * @description
  6163. * Compiles an HTML string or DOM into a template and produces a template function, which
  6164. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6165. *
  6166. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6167. * {@link ng.$compileProvider#directive directives}.
  6168. *
  6169. * <div class="alert alert-warning">
  6170. * **Note:** This document is an in-depth reference of all directive options.
  6171. * For a gentle introduction to directives with examples of common use cases,
  6172. * see the {@link guide/directive directive guide}.
  6173. * </div>
  6174. *
  6175. * ## Comprehensive Directive API
  6176. *
  6177. * There are many different options for a directive.
  6178. *
  6179. * The difference resides in the return value of the factory function.
  6180. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6181. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6182. * the default values).
  6183. *
  6184. * <div class="alert alert-success">
  6185. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6186. * </div>
  6187. *
  6188. * Here's an example directive declared with a Directive Definition Object:
  6189. *
  6190. * ```js
  6191. * var myModule = angular.module(...);
  6192. *
  6193. * myModule.directive('directiveName', function factory(injectables) {
  6194. * var directiveDefinitionObject = {
  6195. * {@link $compile#-priority- priority}: 0,
  6196. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6197. * // or
  6198. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6199. * {@link $compile#-transclude- transclude}: false,
  6200. * {@link $compile#-restrict- restrict}: 'A',
  6201. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6202. * {@link $compile#-scope- scope}: false,
  6203. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6204. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6205. * {@link $compile#-bindtocontroller- bindToController}: false,
  6206. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6207. * {@link $compile#-multielement- multiElement}: false,
  6208. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6209. * return {
  6210. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6211. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6212. * }
  6213. * // or
  6214. * // return function postLink( ... ) { ... }
  6215. * },
  6216. * // or
  6217. * // {@link $compile#-link- link}: {
  6218. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6219. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6220. * // }
  6221. * // or
  6222. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6223. * };
  6224. * return directiveDefinitionObject;
  6225. * });
  6226. * ```
  6227. *
  6228. * <div class="alert alert-warning">
  6229. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6230. * </div>
  6231. *
  6232. * Therefore the above can be simplified as:
  6233. *
  6234. * ```js
  6235. * var myModule = angular.module(...);
  6236. *
  6237. * myModule.directive('directiveName', function factory(injectables) {
  6238. * var directiveDefinitionObject = {
  6239. * link: function postLink(scope, iElement, iAttrs) { ... }
  6240. * };
  6241. * return directiveDefinitionObject;
  6242. * // or
  6243. * // return function postLink(scope, iElement, iAttrs) { ... }
  6244. * });
  6245. * ```
  6246. *
  6247. * ### Life-cycle hooks
  6248. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6249. * directive:
  6250. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6251. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6252. * this element). This is a good place to put initialization code for your controller.
  6253. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6254. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6255. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6256. * component such as cloning the bound value to prevent accidental mutation of the outer value.
  6257. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6258. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6259. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6260. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6261. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6262. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6263. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6264. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6265. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6266. * components will have their `$onDestroy()` hook called before child components.
  6267. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6268. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6269. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6270. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6271. * suspended until that occurs.
  6272. *
  6273. * #### Comparison with Angular 2 life-cycle hooks
  6274. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6275. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6276. *
  6277. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6278. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6279. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6280. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6281. * `ngDoCheck` in Angular 2
  6282. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6283. * propagated throughout the application.
  6284. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6285. * error or do nothing depending upon the state of `enableProdMode()`.
  6286. *
  6287. * #### Life-cycle hook examples
  6288. *
  6289. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6290. * has not changed.
  6291. *
  6292. * <example name="doCheckDateExample" module="do-check-module">
  6293. * <file name="app.js">
  6294. * angular.module('do-check-module', [])
  6295. * .component('app', {
  6296. * template:
  6297. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6298. * 'Date: {{ $ctrl.date }}' +
  6299. * '<test date="$ctrl.date"></test>',
  6300. * controller: function() {
  6301. * this.date = new Date();
  6302. * this.month = this.date.getMonth();
  6303. * this.updateDate = function() {
  6304. * this.date.setMonth(this.month);
  6305. * };
  6306. * }
  6307. * })
  6308. * .component('test', {
  6309. * bindings: { date: '<' },
  6310. * template:
  6311. * '<pre>{{ $ctrl.log | json }}</pre>',
  6312. * controller: function() {
  6313. * var previousValue;
  6314. * this.log = [];
  6315. * this.$doCheck = function() {
  6316. * var currentValue = this.date && this.date.valueOf();
  6317. * if (previousValue !== currentValue) {
  6318. * this.log.push('doCheck: date mutated: ' + this.date);
  6319. * previousValue = currentValue;
  6320. * }
  6321. * };
  6322. * }
  6323. * });
  6324. * </file>
  6325. * <file name="index.html">
  6326. * <app></app>
  6327. * </file>
  6328. * </example>
  6329. *
  6330. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6331. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6332. * arrays or objects can have a negative impact on your application performance)
  6333. *
  6334. * <example name="doCheckArrayExample" module="do-check-module">
  6335. * <file name="index.html">
  6336. * <div ng-init="items = []">
  6337. * <button ng-click="items.push(items.length)">Add Item</button>
  6338. * <button ng-click="items = []">Reset Items</button>
  6339. * <pre>{{ items }}</pre>
  6340. * <test items="items"></test>
  6341. * </div>
  6342. * </file>
  6343. * <file name="app.js">
  6344. * angular.module('do-check-module', [])
  6345. * .component('test', {
  6346. * bindings: { items: '<' },
  6347. * template:
  6348. * '<pre>{{ $ctrl.log | json }}</pre>',
  6349. * controller: function() {
  6350. * this.log = [];
  6351. *
  6352. * this.$doCheck = function() {
  6353. * if (this.items_ref !== this.items) {
  6354. * this.log.push('doCheck: items changed');
  6355. * this.items_ref = this.items;
  6356. * }
  6357. * if (!angular.equals(this.items_clone, this.items)) {
  6358. * this.log.push('doCheck: items mutated');
  6359. * this.items_clone = angular.copy(this.items);
  6360. * }
  6361. * };
  6362. * }
  6363. * });
  6364. * </file>
  6365. * </example>
  6366. *
  6367. *
  6368. * ### Directive Definition Object
  6369. *
  6370. * The directive definition object provides instructions to the {@link ng.$compile
  6371. * compiler}. The attributes are:
  6372. *
  6373. * #### `multiElement`
  6374. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6375. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6376. * together as the directive elements. It is recommended that this feature be used on directives
  6377. * which are not strictly behavioral (such as {@link ngClick}), and which
  6378. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6379. *
  6380. * #### `priority`
  6381. * When there are multiple directives defined on a single DOM element, sometimes it
  6382. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6383. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6384. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6385. * are also run in priority order, but post-link functions are run in reverse order. The order
  6386. * of directives with the same priority is undefined. The default priority is `0`.
  6387. *
  6388. * #### `terminal`
  6389. * If set to true then the current `priority` will be the last set of directives
  6390. * which will execute (any directives at the current priority will still execute
  6391. * as the order of execution on same `priority` is undefined). Note that expressions
  6392. * and other directives used in the directive's template will also be excluded from execution.
  6393. *
  6394. * #### `scope`
  6395. * The scope property can be `false`, `true`, or an object:
  6396. *
  6397. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6398. * parent's scope.
  6399. *
  6400. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6401. * the directive's element. If multiple directives on the same element request a new scope,
  6402. * only one new scope is created.
  6403. *
  6404. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6405. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6406. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6407. * data in the parent scope.
  6408. *
  6409. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6410. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6411. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6412. * is bound to the parent scope, via matching attributes on the directive's element:
  6413. *
  6414. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6415. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6416. * attribute name is assumed to be the same as the local name. Given `<my-component
  6417. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6418. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6419. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6420. * scope. The `name` is read from the parent scope (not the directive's scope).
  6421. *
  6422. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6423. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6424. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6425. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6426. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6427. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6428. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6429. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6430. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6431. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6432. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6433. * method is used for tracking changes, and the equality check is based on object identity.
  6434. * However, if an object literal or an array literal is passed as the binding expression, the
  6435. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6436. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6437. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6438. *
  6439. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6440. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6441. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6442. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6443. *
  6444. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6445. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6446. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6447. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6448. * two caveats:
  6449. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6450. * sets the same value. That means if your bound value is an object, changes to its properties
  6451. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6452. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6453. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6454. * to the value has changed. In most cases, this should not be of concern, but can be important
  6455. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6456. * If you now change a property of the object in your parent scope, the change will not be
  6457. * propagated to the isolated scope, because the identity of the object on the parent scope
  6458. * has not changed. Instead you must assign a new object.
  6459. *
  6460. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6461. * back to the parent. However, it does not make this completely impossible.
  6462. *
  6463. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6464. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6465. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6466. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6467. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6468. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6469. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6470. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6471. *
  6472. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6473. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6474. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6475. *
  6476. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6477. * * **child scope** + **no scope** => Both directives will share one single child scope
  6478. * * **child scope** + **child scope** => Both directives will share one single child scope
  6479. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6480. * its parent's scope
  6481. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6482. * be applied to the same element.
  6483. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6484. * cannot be applied to the same element.
  6485. *
  6486. *
  6487. * #### `bindToController`
  6488. * This property is used to bind scope properties directly to the controller. It can be either
  6489. * `true` or an object hash with the same format as the `scope` property.
  6490. *
  6491. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6492. * allow a component to have its properties bound to the controller, rather than to scope.
  6493. *
  6494. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6495. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6496. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6497. * initialized.
  6498. *
  6499. * <div class="alert alert-warning">
  6500. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6501. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6502. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6503. * </div>
  6504. *
  6505. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6506. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6507. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6508. * scope (useful for component directives).
  6509. *
  6510. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6511. *
  6512. *
  6513. * #### `controller`
  6514. * Controller constructor function. The controller is instantiated before the
  6515. * pre-linking phase and can be accessed by other directives (see
  6516. * `require` attribute). This allows the directives to communicate with each other and augment
  6517. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6518. *
  6519. * * `$scope` - Current scope associated with the element
  6520. * * `$element` - Current element
  6521. * * `$attrs` - Current attributes object for the element
  6522. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6523. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6524. * * `scope`: (optional) override the scope.
  6525. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6526. * * `futureParentElement` (optional):
  6527. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6528. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6529. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6530. * and when the `cloneLinkingFn` is passed,
  6531. * as those elements need to created and cloned in a special way when they are defined outside their
  6532. * usual containers (e.g. like `<svg>`).
  6533. * * See also the `directive.templateNamespace` property.
  6534. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6535. * then the default transclusion is provided.
  6536. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6537. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6538. *
  6539. * #### `require`
  6540. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6541. * `require` property can be a string, an array or an object:
  6542. * * a **string** containing the name of the directive to pass to the linking function
  6543. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6544. * linking function will be an array of controllers in the same order as the names in the `require` property
  6545. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6546. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6547. * controllers.
  6548. *
  6549. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6550. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6551. * have been constructed but before `$onInit` is called.
  6552. * If the name of the required controller is the same as the local name (the key), the name can be
  6553. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6554. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6555. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6556. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6557. * controller, in which case error checking is skipped). The name can be prefixed with:
  6558. *
  6559. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6560. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6561. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6562. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6563. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6564. * `null` to the `link` fn if not found.
  6565. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6566. * `null` to the `link` fn if not found.
  6567. *
  6568. *
  6569. * #### `controllerAs`
  6570. * Identifier name for a reference to the controller in the directive's scope.
  6571. * This allows the controller to be referenced from the directive template. This is especially
  6572. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6573. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6574. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6575. *
  6576. *
  6577. * #### `restrict`
  6578. * String of subset of `EACM` which restricts the directive to a specific directive
  6579. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6580. *
  6581. * * `E` - Element name (default): `<my-directive></my-directive>`
  6582. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6583. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6584. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6585. *
  6586. *
  6587. * #### `templateNamespace`
  6588. * String representing the document type used by the markup in the template.
  6589. * AngularJS needs this information as those elements need to be created and cloned
  6590. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6591. *
  6592. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6593. * top-level elements such as `<svg>` or `<math>`.
  6594. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6595. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6596. *
  6597. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6598. *
  6599. * #### `template`
  6600. * HTML markup that may:
  6601. * * Replace the contents of the directive's element (default).
  6602. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6603. * * Wrap the contents of the directive's element (if `transclude` is true).
  6604. *
  6605. * Value may be:
  6606. *
  6607. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6608. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6609. * function api below) and returns a string value.
  6610. *
  6611. *
  6612. * #### `templateUrl`
  6613. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6614. *
  6615. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6616. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6617. * sibling and parent elements as though this element had not contained any directives.
  6618. *
  6619. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6620. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6621. * case when only one deeply nested directive has `templateUrl`.
  6622. *
  6623. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6624. *
  6625. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6626. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6627. * a string value representing the url. In either case, the template URL is passed through {@link
  6628. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6629. *
  6630. *
  6631. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6632. * specify what the template should replace. Defaults to `false`.
  6633. *
  6634. * * `true` - the template will replace the directive's element.
  6635. * * `false` - the template will replace the contents of the directive's element.
  6636. *
  6637. * The replacement process migrates all of the attributes / classes from the old element to the new
  6638. * one. See the {@link guide/directive#template-expanding-directive
  6639. * Directives Guide} for an example.
  6640. *
  6641. * There are very few scenarios where element replacement is required for the application function,
  6642. * the main one being reusable custom components that are used within SVG contexts
  6643. * (because SVG doesn't work with custom elements in the DOM tree).
  6644. *
  6645. * #### `transclude`
  6646. * Extract the contents of the element where the directive appears and make it available to the directive.
  6647. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6648. * {@link $compile#transclusion Transclusion} section below.
  6649. *
  6650. *
  6651. * #### `compile`
  6652. *
  6653. * ```js
  6654. * function compile(tElement, tAttrs, transclude) { ... }
  6655. * ```
  6656. *
  6657. * The compile function deals with transforming the template DOM. Since most directives do not do
  6658. * template transformation, it is not used often. The compile function takes the following arguments:
  6659. *
  6660. * * `tElement` - template element - The element where the directive has been declared. It is
  6661. * safe to do template transformation on the element and child elements only.
  6662. *
  6663. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6664. * between all directive compile functions.
  6665. *
  6666. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6667. *
  6668. * <div class="alert alert-warning">
  6669. * **Note:** The template instance and the link instance may be different objects if the template has
  6670. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6671. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6672. * should be done in a linking function rather than in a compile function.
  6673. * </div>
  6674. * <div class="alert alert-warning">
  6675. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6676. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6677. * stack overflow errors.
  6678. *
  6679. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6680. * a directive's template instead of relying on automatic template compilation via `template` or
  6681. * `templateUrl` declaration or manual compilation inside the compile function.
  6682. * </div>
  6683. *
  6684. * <div class="alert alert-danger">
  6685. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6686. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6687. * to the link function instead.
  6688. * </div>
  6689. * A compile function can have a return value which can be either a function or an object.
  6690. *
  6691. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6692. * `link` property of the config object when the compile function is empty.
  6693. *
  6694. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6695. * control when a linking function should be called during the linking phase. See info about
  6696. * pre-linking and post-linking functions below.
  6697. *
  6698. *
  6699. * #### `link`
  6700. * This property is used only if the `compile` property is not defined.
  6701. *
  6702. * ```js
  6703. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6704. * ```
  6705. *
  6706. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6707. * executed after the template has been cloned. This is where most of the directive logic will be
  6708. * put.
  6709. *
  6710. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6711. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6712. *
  6713. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6714. * manipulate the children of the element only in `postLink` function since the children have
  6715. * already been linked.
  6716. *
  6717. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6718. * between all directive linking functions.
  6719. *
  6720. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6721. * among all directives, which allows the directives to use the controllers as a communication
  6722. * channel. The exact value depends on the directive's `require` property:
  6723. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6724. * * `string`: the controller instance
  6725. * * `array`: array of controller instances
  6726. *
  6727. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6728. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6729. *
  6730. * Note that you can also require the directive's own controller - it will be made available like
  6731. * any other controller.
  6732. *
  6733. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6734. * This is the same as the `$transclude` parameter of directive controllers,
  6735. * see {@link ng.$compile#-controller- the controller section for details}.
  6736. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6737. *
  6738. * #### Pre-linking function
  6739. *
  6740. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6741. * compiler linking function will fail to locate the correct elements for linking.
  6742. *
  6743. * #### Post-linking function
  6744. *
  6745. * Executed after the child elements are linked.
  6746. *
  6747. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6748. * and linked since they are waiting for their template to load asynchronously and their own
  6749. * compilation and linking has been suspended until that occurs.
  6750. *
  6751. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6752. * for their async templates to be resolved.
  6753. *
  6754. *
  6755. * ### Transclusion
  6756. *
  6757. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6758. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6759. * scope from where they were taken.
  6760. *
  6761. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6762. * original contents of a directive's element into a specified place in the template of the directive.
  6763. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6764. * content has access to the properties on the scope from which it was taken, even if the directive
  6765. * has isolated scope.
  6766. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6767. *
  6768. * This makes it possible for the widget to have private state for its template, while the transcluded
  6769. * content has access to its originating scope.
  6770. *
  6771. * <div class="alert alert-warning">
  6772. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6773. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6774. * Testing Transclusion Directives}.
  6775. * </div>
  6776. *
  6777. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6778. * directive's element, the entire element or multiple parts of the element contents:
  6779. *
  6780. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6781. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6782. * element that defined at a lower priority than this directive. When used, the `template`
  6783. * property is ignored.
  6784. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6785. *
  6786. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6787. *
  6788. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6789. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6790. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6791. *
  6792. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6793. *
  6794. * If the element selector is prefixed with a `?` then that slot is optional.
  6795. *
  6796. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6797. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6798. *
  6799. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6800. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6801. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6802. * injectable into the directive's controller.
  6803. *
  6804. *
  6805. * #### Transclusion Functions
  6806. *
  6807. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6808. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6809. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6810. *
  6811. * <div class="alert alert-info">
  6812. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6813. * ngTransclude will deal with it for us.
  6814. * </div>
  6815. *
  6816. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6817. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6818. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6819. *
  6820. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6821. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6822. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  6823. *
  6824. * <div class="alert alert-info">
  6825. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6826. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6827. * </div>
  6828. *
  6829. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6830. * attach function**:
  6831. *
  6832. * ```js
  6833. * var transcludedContent, transclusionScope;
  6834. *
  6835. * $transclude(function(clone, scope) {
  6836. * element.append(clone);
  6837. * transcludedContent = clone;
  6838. * transclusionScope = scope;
  6839. * });
  6840. * ```
  6841. *
  6842. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6843. * associated transclusion scope:
  6844. *
  6845. * ```js
  6846. * transcludedContent.remove();
  6847. * transclusionScope.$destroy();
  6848. * ```
  6849. *
  6850. * <div class="alert alert-info">
  6851. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6852. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6853. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6854. * </div>
  6855. *
  6856. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6857. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6858. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6859. *
  6860. *
  6861. * #### Transclusion Scopes
  6862. *
  6863. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6864. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6865. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6866. * was taken.
  6867. *
  6868. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6869. * like this:
  6870. *
  6871. * ```html
  6872. * <div ng-app>
  6873. * <div isolate>
  6874. * <div transclusion>
  6875. * </div>
  6876. * </div>
  6877. * </div>
  6878. * ```
  6879. *
  6880. * The `$parent` scope hierarchy will look like this:
  6881. *
  6882. ```
  6883. - $rootScope
  6884. - isolate
  6885. - transclusion
  6886. ```
  6887. *
  6888. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6889. *
  6890. ```
  6891. - $rootScope
  6892. - transclusion
  6893. - isolate
  6894. ```
  6895. *
  6896. *
  6897. * ### Attributes
  6898. *
  6899. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6900. * `link()` or `compile()` functions. It has a variety of uses.
  6901. *
  6902. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6903. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6904. * to the attributes.
  6905. *
  6906. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6907. * object which allows the directives to use the attributes object as inter directive
  6908. * communication.
  6909. *
  6910. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6911. * allowing other directives to read the interpolated value.
  6912. *
  6913. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6914. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6915. * the only way to easily get the actual value because during the linking phase the interpolation
  6916. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6917. *
  6918. * ```js
  6919. * function linkingFn(scope, elm, attrs, ctrl) {
  6920. * // get the attribute value
  6921. * console.log(attrs.ngModel);
  6922. *
  6923. * // change the attribute
  6924. * attrs.$set('ngModel', 'new value');
  6925. *
  6926. * // observe changes to interpolated attribute
  6927. * attrs.$observe('ngModel', function(value) {
  6928. * console.log('ngModel has changed value to ' + value);
  6929. * });
  6930. * }
  6931. * ```
  6932. *
  6933. * ## Example
  6934. *
  6935. * <div class="alert alert-warning">
  6936. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6937. * to illustrate how `$compile` works.
  6938. * </div>
  6939. *
  6940. <example module="compileExample" name="compile">
  6941. <file name="index.html">
  6942. <script>
  6943. angular.module('compileExample', [], function($compileProvider) {
  6944. // configure new 'compile' directive by passing a directive
  6945. // factory function. The factory function injects the '$compile'
  6946. $compileProvider.directive('compile', function($compile) {
  6947. // directive factory creates a link function
  6948. return function(scope, element, attrs) {
  6949. scope.$watch(
  6950. function(scope) {
  6951. // watch the 'compile' expression for changes
  6952. return scope.$eval(attrs.compile);
  6953. },
  6954. function(value) {
  6955. // when the 'compile' expression changes
  6956. // assign it into the current DOM
  6957. element.html(value);
  6958. // compile the new DOM and link it to the current
  6959. // scope.
  6960. // NOTE: we only compile .childNodes so that
  6961. // we don't get into infinite loop compiling ourselves
  6962. $compile(element.contents())(scope);
  6963. }
  6964. );
  6965. };
  6966. });
  6967. })
  6968. .controller('GreeterController', ['$scope', function($scope) {
  6969. $scope.name = 'Angular';
  6970. $scope.html = 'Hello {{name}}';
  6971. }]);
  6972. </script>
  6973. <div ng-controller="GreeterController">
  6974. <input ng-model="name"> <br/>
  6975. <textarea ng-model="html"></textarea> <br/>
  6976. <div compile="html"></div>
  6977. </div>
  6978. </file>
  6979. <file name="protractor.js" type="protractor">
  6980. it('should auto compile', function() {
  6981. var textarea = $('textarea');
  6982. var output = $('div[compile]');
  6983. // The initial state reads 'Hello Angular'.
  6984. expect(output.getText()).toBe('Hello Angular');
  6985. textarea.clear();
  6986. textarea.sendKeys('{{name}}!');
  6987. expect(output.getText()).toBe('Angular!');
  6988. });
  6989. </file>
  6990. </example>
  6991. *
  6992. *
  6993. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6994. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6995. *
  6996. * <div class="alert alert-danger">
  6997. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6998. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6999. * `parentBoundTranscludeFn` to the link function instead.
  7000. * </div>
  7001. *
  7002. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7003. * root element(s), not their children)
  7004. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7005. * (a DOM element/tree) to a scope. Where:
  7006. *
  7007. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7008. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7009. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7010. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7011. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7012. *
  7013. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7014. * * `scope` - is the current scope with which the linking function is working with.
  7015. *
  7016. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7017. * keys may be used to control linking behavior:
  7018. *
  7019. * * `parentBoundTranscludeFn` - the transclude function made available to
  7020. * directives; if given, it will be passed through to the link functions of
  7021. * directives found in `element` during compilation.
  7022. * * `transcludeControllers` - an object hash with keys that map controller names
  7023. * to a hash with the key `instance`, which maps to the controller instance;
  7024. * if given, it will make the controllers available to directives on the compileNode:
  7025. * ```
  7026. * {
  7027. * parent: {
  7028. * instance: parentControllerInstance
  7029. * }
  7030. * }
  7031. * ```
  7032. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7033. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7034. * elements (e.g. SVG elements). See also the directive.controller property.
  7035. *
  7036. * Calling the linking function returns the element of the template. It is either the original
  7037. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7038. *
  7039. * After linking the view is not updated until after a call to $digest which typically is done by
  7040. * Angular automatically.
  7041. *
  7042. * If you need access to the bound view, there are two ways to do it:
  7043. *
  7044. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7045. * before you send them to the compiler and keep this reference around.
  7046. * ```js
  7047. * var element = $compile('<p>{{total}}</p>')(scope);
  7048. * ```
  7049. *
  7050. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7051. * example would not point to the clone, but rather to the original template that was cloned. In
  7052. * this case, you can access the clone via the cloneAttachFn:
  7053. * ```js
  7054. * var templateElement = angular.element('<p>{{total}}</p>'),
  7055. * scope = ....;
  7056. *
  7057. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7058. * //attach the clone to DOM document at the right place
  7059. * });
  7060. *
  7061. * //now we have reference to the cloned DOM via `clonedElement`
  7062. * ```
  7063. *
  7064. *
  7065. * For information on how the compiler works, see the
  7066. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7067. *
  7068. * @knownIssue
  7069. *
  7070. * ### Double Compilation
  7071. *
  7072. Double compilation occurs when an already compiled part of the DOM gets
  7073. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7074. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7075. section on double compilation} for an in-depth explanation and ways to avoid it.
  7076. *
  7077. */
  7078. var $compileMinErr = minErr('$compile');
  7079. function UNINITIALIZED_VALUE() {}
  7080. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7081. /**
  7082. * @ngdoc provider
  7083. * @name $compileProvider
  7084. *
  7085. * @description
  7086. */
  7087. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7088. /** @this */
  7089. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7090. var hasDirectives = {},
  7091. Suffix = 'Directive',
  7092. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7093. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7094. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7095. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7096. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7097. // The assumption is that future DOM event attribute names will begin with
  7098. // 'on' and be composed of only English letters.
  7099. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7100. var bindingCache = createMap();
  7101. function parseIsolateBindings(scope, directiveName, isController) {
  7102. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  7103. var bindings = createMap();
  7104. forEach(scope, function(definition, scopeName) {
  7105. if (definition in bindingCache) {
  7106. bindings[scopeName] = bindingCache[definition];
  7107. return;
  7108. }
  7109. var match = definition.match(LOCAL_REGEXP);
  7110. if (!match) {
  7111. throw $compileMinErr('iscp',
  7112. 'Invalid {3} for directive \'{0}\'.' +
  7113. ' Definition: {... {1}: \'{2}\' ...}',
  7114. directiveName, scopeName, definition,
  7115. (isController ? 'controller bindings definition' :
  7116. 'isolate scope definition'));
  7117. }
  7118. bindings[scopeName] = {
  7119. mode: match[1][0],
  7120. collection: match[2] === '*',
  7121. optional: match[3] === '?',
  7122. attrName: match[4] || scopeName
  7123. };
  7124. if (match[4]) {
  7125. bindingCache[definition] = bindings[scopeName];
  7126. }
  7127. });
  7128. return bindings;
  7129. }
  7130. function parseDirectiveBindings(directive, directiveName) {
  7131. var bindings = {
  7132. isolateScope: null,
  7133. bindToController: null
  7134. };
  7135. if (isObject(directive.scope)) {
  7136. if (directive.bindToController === true) {
  7137. bindings.bindToController = parseIsolateBindings(directive.scope,
  7138. directiveName, true);
  7139. bindings.isolateScope = {};
  7140. } else {
  7141. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7142. directiveName, false);
  7143. }
  7144. }
  7145. if (isObject(directive.bindToController)) {
  7146. bindings.bindToController =
  7147. parseIsolateBindings(directive.bindToController, directiveName, true);
  7148. }
  7149. if (bindings.bindToController && !directive.controller) {
  7150. // There is no controller
  7151. throw $compileMinErr('noctrl',
  7152. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7153. directiveName);
  7154. }
  7155. return bindings;
  7156. }
  7157. function assertValidDirectiveName(name) {
  7158. var letter = name.charAt(0);
  7159. if (!letter || letter !== lowercase(letter)) {
  7160. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7161. }
  7162. if (name !== name.trim()) {
  7163. throw $compileMinErr('baddir',
  7164. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7165. name);
  7166. }
  7167. }
  7168. function getDirectiveRequire(directive) {
  7169. var require = directive.require || (directive.controller && directive.name);
  7170. if (!isArray(require) && isObject(require)) {
  7171. forEach(require, function(value, key) {
  7172. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7173. var name = value.substring(match[0].length);
  7174. if (!name) require[key] = match[0] + key;
  7175. });
  7176. }
  7177. return require;
  7178. }
  7179. function getDirectiveRestrict(restrict, name) {
  7180. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7181. throw $compileMinErr('badrestrict',
  7182. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7183. restrict,
  7184. name);
  7185. }
  7186. return restrict || 'EA';
  7187. }
  7188. /**
  7189. * @ngdoc method
  7190. * @name $compileProvider#directive
  7191. * @kind function
  7192. *
  7193. * @description
  7194. * Register a new directive with the compiler.
  7195. *
  7196. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7197. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7198. * names and the values are the factories.
  7199. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7200. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7201. * @returns {ng.$compileProvider} Self for chaining.
  7202. */
  7203. this.directive = function registerDirective(name, directiveFactory) {
  7204. assertArg(name, 'name');
  7205. assertNotHasOwnProperty(name, 'directive');
  7206. if (isString(name)) {
  7207. assertValidDirectiveName(name);
  7208. assertArg(directiveFactory, 'directiveFactory');
  7209. if (!hasDirectives.hasOwnProperty(name)) {
  7210. hasDirectives[name] = [];
  7211. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7212. function($injector, $exceptionHandler) {
  7213. var directives = [];
  7214. forEach(hasDirectives[name], function(directiveFactory, index) {
  7215. try {
  7216. var directive = $injector.invoke(directiveFactory);
  7217. if (isFunction(directive)) {
  7218. directive = { compile: valueFn(directive) };
  7219. } else if (!directive.compile && directive.link) {
  7220. directive.compile = valueFn(directive.link);
  7221. }
  7222. directive.priority = directive.priority || 0;
  7223. directive.index = index;
  7224. directive.name = directive.name || name;
  7225. directive.require = getDirectiveRequire(directive);
  7226. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7227. directive.$$moduleName = directiveFactory.$$moduleName;
  7228. directives.push(directive);
  7229. } catch (e) {
  7230. $exceptionHandler(e);
  7231. }
  7232. });
  7233. return directives;
  7234. }]);
  7235. }
  7236. hasDirectives[name].push(directiveFactory);
  7237. } else {
  7238. forEach(name, reverseParams(registerDirective));
  7239. }
  7240. return this;
  7241. };
  7242. /**
  7243. * @ngdoc method
  7244. * @name $compileProvider#component
  7245. * @module ng
  7246. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7247. * @param {Object} options Component definition object (a simplified
  7248. * {@link ng.$compile#directive-definition-object directive definition object}),
  7249. * with the following properties (all optional):
  7250. *
  7251. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7252. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7253. * registered controller} if passed as a string. An empty `noop` function by default.
  7254. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7255. * If present, the controller will be published to scope under the `controllerAs` name.
  7256. * If not present, this will default to be `$ctrl`.
  7257. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7258. * returns an html template as a string which should be used as the contents of this component.
  7259. * Empty string by default.
  7260. *
  7261. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7262. * the following locals:
  7263. *
  7264. * - `$element` - Current element
  7265. * - `$attrs` - Current attributes object for the element
  7266. *
  7267. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7268. * template that should be used as the contents of this component.
  7269. *
  7270. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7271. * the following locals:
  7272. *
  7273. * - `$element` - Current element
  7274. * - `$attrs` - Current attributes object for the element
  7275. *
  7276. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7277. * Component properties are always bound to the component controller and not to the scope.
  7278. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7279. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7280. * Disabled by default.
  7281. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7282. * this component's controller. The object keys specify the property names under which the required
  7283. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7284. * - `$...` – additional properties to attach to the directive factory function and the controller
  7285. * constructor function. (This is used by the component router to annotate)
  7286. *
  7287. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7288. * @description
  7289. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7290. * type of directive, which represents a self-contained UI component in your application. Such components
  7291. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7292. *
  7293. * Component definitions are very simple and do not require as much configuration as defining general
  7294. * directives. Component definitions usually consist only of a template and a controller backing it.
  7295. *
  7296. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7297. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7298. *
  7299. * Here are a few examples of how you would usually define components:
  7300. *
  7301. * ```js
  7302. * var myMod = angular.module(...);
  7303. * myMod.component('myComp', {
  7304. * template: '<div>My name is {{$ctrl.name}}</div>',
  7305. * controller: function() {
  7306. * this.name = 'shahar';
  7307. * }
  7308. * });
  7309. *
  7310. * myMod.component('myComp', {
  7311. * template: '<div>My name is {{$ctrl.name}}</div>',
  7312. * bindings: {name: '@'}
  7313. * });
  7314. *
  7315. * myMod.component('myComp', {
  7316. * templateUrl: 'views/my-comp.html',
  7317. * controller: 'MyCtrl',
  7318. * controllerAs: 'ctrl',
  7319. * bindings: {name: '@'}
  7320. * });
  7321. *
  7322. * ```
  7323. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7324. *
  7325. * <br />
  7326. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7327. */
  7328. this.component = function registerComponent(name, options) {
  7329. var controller = options.controller || function() {};
  7330. function factory($injector) {
  7331. function makeInjectable(fn) {
  7332. if (isFunction(fn) || isArray(fn)) {
  7333. return /** @this */ function(tElement, tAttrs) {
  7334. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7335. };
  7336. } else {
  7337. return fn;
  7338. }
  7339. }
  7340. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7341. var ddo = {
  7342. controller: controller,
  7343. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7344. template: makeInjectable(template),
  7345. templateUrl: makeInjectable(options.templateUrl),
  7346. transclude: options.transclude,
  7347. scope: {},
  7348. bindToController: options.bindings || {},
  7349. restrict: 'E',
  7350. require: options.require
  7351. };
  7352. // Copy annotations (starting with $) over to the DDO
  7353. forEach(options, function(val, key) {
  7354. if (key.charAt(0) === '$') ddo[key] = val;
  7355. });
  7356. return ddo;
  7357. }
  7358. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7359. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7360. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7361. // it from 1.5.x yet.
  7362. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7363. // These could be used by libraries such as the new component router
  7364. forEach(options, function(val, key) {
  7365. if (key.charAt(0) === '$') {
  7366. factory[key] = val;
  7367. // Don't try to copy over annotations to named controller
  7368. if (isFunction(controller)) controller[key] = val;
  7369. }
  7370. });
  7371. factory.$inject = ['$injector'];
  7372. return this.directive(name, factory);
  7373. };
  7374. /**
  7375. * @ngdoc method
  7376. * @name $compileProvider#aHrefSanitizationWhitelist
  7377. * @kind function
  7378. *
  7379. * @description
  7380. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7381. * urls during a[href] sanitization.
  7382. *
  7383. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7384. *
  7385. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7386. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7387. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7388. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7389. *
  7390. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7391. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7392. * chaining otherwise.
  7393. */
  7394. this.aHrefSanitizationWhitelist = function(regexp) {
  7395. if (isDefined(regexp)) {
  7396. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7397. return this;
  7398. } else {
  7399. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7400. }
  7401. };
  7402. /**
  7403. * @ngdoc method
  7404. * @name $compileProvider#imgSrcSanitizationWhitelist
  7405. * @kind function
  7406. *
  7407. * @description
  7408. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7409. * urls during img[src] sanitization.
  7410. *
  7411. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7412. *
  7413. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7414. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7415. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7416. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7417. *
  7418. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7419. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7420. * chaining otherwise.
  7421. */
  7422. this.imgSrcSanitizationWhitelist = function(regexp) {
  7423. if (isDefined(regexp)) {
  7424. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7425. return this;
  7426. } else {
  7427. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7428. }
  7429. };
  7430. /**
  7431. * @ngdoc method
  7432. * @name $compileProvider#debugInfoEnabled
  7433. *
  7434. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7435. * current debugInfoEnabled state
  7436. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7437. *
  7438. * @kind function
  7439. *
  7440. * @description
  7441. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7442. * binding information and a reference to the current scope on to DOM elements.
  7443. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7444. * * `ng-binding` CSS class
  7445. * * `$binding` data property containing an array of the binding expressions
  7446. *
  7447. * You may want to disable this in production for a significant performance boost. See
  7448. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7449. *
  7450. * The default value is true.
  7451. */
  7452. var debugInfoEnabled = true;
  7453. this.debugInfoEnabled = function(enabled) {
  7454. if (isDefined(enabled)) {
  7455. debugInfoEnabled = enabled;
  7456. return this;
  7457. }
  7458. return debugInfoEnabled;
  7459. };
  7460. /**
  7461. * @ngdoc method
  7462. * @name $compileProvider#preAssignBindingsEnabled
  7463. *
  7464. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7465. * current preAssignBindingsEnabled state
  7466. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7467. *
  7468. * @kind function
  7469. *
  7470. * @description
  7471. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7472. * calling the controller's constructor.
  7473. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7474. * properties of the controller object before the constructor of this object is called.
  7475. *
  7476. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7477. *
  7478. * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
  7479. */
  7480. var preAssignBindingsEnabled = false;
  7481. this.preAssignBindingsEnabled = function(enabled) {
  7482. if (isDefined(enabled)) {
  7483. preAssignBindingsEnabled = enabled;
  7484. return this;
  7485. }
  7486. return preAssignBindingsEnabled;
  7487. };
  7488. var TTL = 10;
  7489. /**
  7490. * @ngdoc method
  7491. * @name $compileProvider#onChangesTtl
  7492. * @description
  7493. *
  7494. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7495. * assuming that the model is unstable.
  7496. *
  7497. * The current default is 10 iterations.
  7498. *
  7499. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7500. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7501. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7502. * the `$onChanges` hook execution.
  7503. *
  7504. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7505. *
  7506. * @param {number} limit The number of `$onChanges` hook iterations.
  7507. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7508. */
  7509. this.onChangesTtl = function(value) {
  7510. if (arguments.length) {
  7511. TTL = value;
  7512. return this;
  7513. }
  7514. return TTL;
  7515. };
  7516. var commentDirectivesEnabledConfig = true;
  7517. /**
  7518. * @ngdoc method
  7519. * @name $compileProvider#commentDirectivesEnabled
  7520. * @description
  7521. *
  7522. * It indicates to the compiler
  7523. * whether or not directives on comments should be compiled.
  7524. * Defaults to `true`.
  7525. *
  7526. * Calling this function with false disables the compilation of directives
  7527. * on comments for the whole application.
  7528. * This results in a compilation performance gain,
  7529. * as the compiler doesn't have to check comments when looking for directives.
  7530. * This should however only be used if you are sure that no comment directives are used in
  7531. * the application (including any 3rd party directives).
  7532. *
  7533. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7534. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7535. */
  7536. this.commentDirectivesEnabled = function(value) {
  7537. if (arguments.length) {
  7538. commentDirectivesEnabledConfig = value;
  7539. return this;
  7540. }
  7541. return commentDirectivesEnabledConfig;
  7542. };
  7543. var cssClassDirectivesEnabledConfig = true;
  7544. /**
  7545. * @ngdoc method
  7546. * @name $compileProvider#cssClassDirectivesEnabled
  7547. * @description
  7548. *
  7549. * It indicates to the compiler
  7550. * whether or not directives on element classes should be compiled.
  7551. * Defaults to `true`.
  7552. *
  7553. * Calling this function with false disables the compilation of directives
  7554. * on element classes for the whole application.
  7555. * This results in a compilation performance gain,
  7556. * as the compiler doesn't have to check element classes when looking for directives.
  7557. * This should however only be used if you are sure that no class directives are used in
  7558. * the application (including any 3rd party directives).
  7559. *
  7560. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7561. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7562. */
  7563. this.cssClassDirectivesEnabled = function(value) {
  7564. if (arguments.length) {
  7565. cssClassDirectivesEnabledConfig = value;
  7566. return this;
  7567. }
  7568. return cssClassDirectivesEnabledConfig;
  7569. };
  7570. this.$get = [
  7571. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7572. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7573. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7574. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7575. var SIMPLE_ATTR_NAME = /^\w/;
  7576. var specialAttrHolder = window.document.createElement('div');
  7577. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7578. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7579. var onChangesTtl = TTL;
  7580. // The onChanges hooks should all be run together in a single digest
  7581. // When changes occur, the call to trigger their hooks will be added to this queue
  7582. var onChangesQueue;
  7583. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7584. function flushOnChangesQueue() {
  7585. try {
  7586. if (!(--onChangesTtl)) {
  7587. // We have hit the TTL limit so reset everything
  7588. onChangesQueue = undefined;
  7589. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7590. }
  7591. // We must run this hook in an apply since the $$postDigest runs outside apply
  7592. $rootScope.$apply(function() {
  7593. var errors = [];
  7594. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7595. try {
  7596. onChangesQueue[i]();
  7597. } catch (e) {
  7598. errors.push(e);
  7599. }
  7600. }
  7601. // Reset the queue to trigger a new schedule next time there is a change
  7602. onChangesQueue = undefined;
  7603. if (errors.length) {
  7604. throw errors;
  7605. }
  7606. });
  7607. } finally {
  7608. onChangesTtl++;
  7609. }
  7610. }
  7611. function Attributes(element, attributesToCopy) {
  7612. if (attributesToCopy) {
  7613. var keys = Object.keys(attributesToCopy);
  7614. var i, l, key;
  7615. for (i = 0, l = keys.length; i < l; i++) {
  7616. key = keys[i];
  7617. this[key] = attributesToCopy[key];
  7618. }
  7619. } else {
  7620. this.$attr = {};
  7621. }
  7622. this.$$element = element;
  7623. }
  7624. Attributes.prototype = {
  7625. /**
  7626. * @ngdoc method
  7627. * @name $compile.directive.Attributes#$normalize
  7628. * @kind function
  7629. *
  7630. * @description
  7631. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7632. * `data-`) to its normalized, camelCase form.
  7633. *
  7634. * Also there is special case for Moz prefix starting with upper case letter.
  7635. *
  7636. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7637. *
  7638. * @param {string} name Name to normalize
  7639. */
  7640. $normalize: directiveNormalize,
  7641. /**
  7642. * @ngdoc method
  7643. * @name $compile.directive.Attributes#$addClass
  7644. * @kind function
  7645. *
  7646. * @description
  7647. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7648. * are enabled then an animation will be triggered for the class addition.
  7649. *
  7650. * @param {string} classVal The className value that will be added to the element
  7651. */
  7652. $addClass: function(classVal) {
  7653. if (classVal && classVal.length > 0) {
  7654. $animate.addClass(this.$$element, classVal);
  7655. }
  7656. },
  7657. /**
  7658. * @ngdoc method
  7659. * @name $compile.directive.Attributes#$removeClass
  7660. * @kind function
  7661. *
  7662. * @description
  7663. * Removes the CSS class value specified by the classVal parameter from the element. If
  7664. * animations are enabled then an animation will be triggered for the class removal.
  7665. *
  7666. * @param {string} classVal The className value that will be removed from the element
  7667. */
  7668. $removeClass: function(classVal) {
  7669. if (classVal && classVal.length > 0) {
  7670. $animate.removeClass(this.$$element, classVal);
  7671. }
  7672. },
  7673. /**
  7674. * @ngdoc method
  7675. * @name $compile.directive.Attributes#$updateClass
  7676. * @kind function
  7677. *
  7678. * @description
  7679. * Adds and removes the appropriate CSS class values to the element based on the difference
  7680. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7681. *
  7682. * @param {string} newClasses The current CSS className value
  7683. * @param {string} oldClasses The former CSS className value
  7684. */
  7685. $updateClass: function(newClasses, oldClasses) {
  7686. var toAdd = tokenDifference(newClasses, oldClasses);
  7687. if (toAdd && toAdd.length) {
  7688. $animate.addClass(this.$$element, toAdd);
  7689. }
  7690. var toRemove = tokenDifference(oldClasses, newClasses);
  7691. if (toRemove && toRemove.length) {
  7692. $animate.removeClass(this.$$element, toRemove);
  7693. }
  7694. },
  7695. /**
  7696. * Set a normalized attribute on the element in a way such that all directives
  7697. * can share the attribute. This function properly handles boolean attributes.
  7698. * @param {string} key Normalized key. (ie ngAttribute)
  7699. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7700. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7701. * Defaults to true.
  7702. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7703. */
  7704. $set: function(key, value, writeAttr, attrName) {
  7705. // TODO: decide whether or not to throw an error if "class"
  7706. //is set through this function since it may cause $updateClass to
  7707. //become unstable.
  7708. var node = this.$$element[0],
  7709. booleanKey = getBooleanAttrName(node, key),
  7710. aliasedKey = getAliasedAttrName(key),
  7711. observer = key,
  7712. nodeName;
  7713. if (booleanKey) {
  7714. this.$$element.prop(key, value);
  7715. attrName = booleanKey;
  7716. } else if (aliasedKey) {
  7717. this[aliasedKey] = value;
  7718. observer = aliasedKey;
  7719. }
  7720. this[key] = value;
  7721. // translate normalized key to actual key
  7722. if (attrName) {
  7723. this.$attr[key] = attrName;
  7724. } else {
  7725. attrName = this.$attr[key];
  7726. if (!attrName) {
  7727. this.$attr[key] = attrName = snake_case(key, '-');
  7728. }
  7729. }
  7730. nodeName = nodeName_(this.$$element);
  7731. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7732. (nodeName === 'img' && key === 'src')) {
  7733. // sanitize a[href] and img[src] values
  7734. this[key] = value = $$sanitizeUri(value, key === 'src');
  7735. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7736. // sanitize img[srcset] values
  7737. var result = '';
  7738. // first check if there are spaces because it's not the same pattern
  7739. var trimmedSrcset = trim(value);
  7740. // ( 999x ,| 999w ,| ,|, )
  7741. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7742. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7743. // split srcset into tuple of uri and descriptor except for the last item
  7744. var rawUris = trimmedSrcset.split(pattern);
  7745. // for each tuples
  7746. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7747. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7748. var innerIdx = i * 2;
  7749. // sanitize the uri
  7750. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7751. // add the descriptor
  7752. result += (' ' + trim(rawUris[innerIdx + 1]));
  7753. }
  7754. // split the last item into uri and descriptor
  7755. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7756. // sanitize the last uri
  7757. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7758. // and add the last descriptor if any
  7759. if (lastTuple.length === 2) {
  7760. result += (' ' + trim(lastTuple[1]));
  7761. }
  7762. this[key] = value = result;
  7763. }
  7764. if (writeAttr !== false) {
  7765. if (value === null || isUndefined(value)) {
  7766. this.$$element.removeAttr(attrName);
  7767. } else {
  7768. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7769. this.$$element.attr(attrName, value);
  7770. } else {
  7771. setSpecialAttr(this.$$element[0], attrName, value);
  7772. }
  7773. }
  7774. }
  7775. // fire observers
  7776. var $$observers = this.$$observers;
  7777. if ($$observers) {
  7778. forEach($$observers[observer], function(fn) {
  7779. try {
  7780. fn(value);
  7781. } catch (e) {
  7782. $exceptionHandler(e);
  7783. }
  7784. });
  7785. }
  7786. },
  7787. /**
  7788. * @ngdoc method
  7789. * @name $compile.directive.Attributes#$observe
  7790. * @kind function
  7791. *
  7792. * @description
  7793. * Observes an interpolated attribute.
  7794. *
  7795. * The observer function will be invoked once during the next `$digest` following
  7796. * compilation. The observer is then invoked whenever the interpolated value
  7797. * changes.
  7798. *
  7799. * @param {string} key Normalized key. (ie ngAttribute) .
  7800. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7801. the interpolated value of the attribute changes.
  7802. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7803. * guide} for more info.
  7804. * @returns {function()} Returns a deregistration function for this observer.
  7805. */
  7806. $observe: function(key, fn) {
  7807. var attrs = this,
  7808. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7809. listeners = ($$observers[key] || ($$observers[key] = []));
  7810. listeners.push(fn);
  7811. $rootScope.$evalAsync(function() {
  7812. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7813. // no one registered attribute interpolation function, so lets call it manually
  7814. fn(attrs[key]);
  7815. }
  7816. });
  7817. return function() {
  7818. arrayRemove(listeners, fn);
  7819. };
  7820. }
  7821. };
  7822. function setSpecialAttr(element, attrName, value) {
  7823. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7824. // so we have to jump through some hoops to get such an attribute
  7825. // https://github.com/angular/angular.js/pull/13318
  7826. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  7827. var attributes = specialAttrHolder.firstChild.attributes;
  7828. var attribute = attributes[0];
  7829. // We have to remove the attribute from its container element before we can add it to the destination element
  7830. attributes.removeNamedItem(attribute.name);
  7831. attribute.value = value;
  7832. element.attributes.setNamedItem(attribute);
  7833. }
  7834. function safeAddClass($element, className) {
  7835. try {
  7836. $element.addClass(className);
  7837. } catch (e) {
  7838. // ignore, since it means that we are trying to set class on
  7839. // SVG element, where class name is read-only.
  7840. }
  7841. }
  7842. var startSymbol = $interpolate.startSymbol(),
  7843. endSymbol = $interpolate.endSymbol(),
  7844. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  7845. ? identity
  7846. : function denormalizeTemplate(template) {
  7847. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7848. },
  7849. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7850. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7851. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7852. var bindings = $element.data('$binding') || [];
  7853. if (isArray(binding)) {
  7854. bindings = bindings.concat(binding);
  7855. } else {
  7856. bindings.push(binding);
  7857. }
  7858. $element.data('$binding', bindings);
  7859. } : noop;
  7860. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7861. safeAddClass($element, 'ng-binding');
  7862. } : noop;
  7863. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7864. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7865. $element.data(dataName, scope);
  7866. } : noop;
  7867. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7868. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7869. } : noop;
  7870. compile.$$createComment = function(directiveName, comment) {
  7871. var content = '';
  7872. if (debugInfoEnabled) {
  7873. content = ' ' + (directiveName || '') + ': ';
  7874. if (comment) content += comment + ' ';
  7875. }
  7876. return window.document.createComment(content);
  7877. };
  7878. return compile;
  7879. //================================
  7880. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7881. previousCompileContext) {
  7882. if (!($compileNodes instanceof jqLite)) {
  7883. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7884. // modify it.
  7885. $compileNodes = jqLite($compileNodes);
  7886. }
  7887. var compositeLinkFn =
  7888. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7889. maxPriority, ignoreDirective, previousCompileContext);
  7890. compile.$$addScopeClass($compileNodes);
  7891. var namespace = null;
  7892. return function publicLinkFn(scope, cloneConnectFn, options) {
  7893. if (!$compileNodes) {
  7894. throw $compileMinErr('multilink', 'This element has already been linked.');
  7895. }
  7896. assertArg(scope, 'scope');
  7897. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7898. // A parent directive did a replace and a directive on this element asked
  7899. // for transclusion, which caused us to lose a layer of element on which
  7900. // we could hold the new transclusion scope, so we will create it manually
  7901. // here.
  7902. scope = scope.$parent.$new();
  7903. }
  7904. options = options || {};
  7905. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7906. transcludeControllers = options.transcludeControllers,
  7907. futureParentElement = options.futureParentElement;
  7908. // When `parentBoundTranscludeFn` is passed, it is a
  7909. // `controllersBoundTransclude` function (it was previously passed
  7910. // as `transclude` to directive.link) so we must unwrap it to get
  7911. // its `boundTranscludeFn`
  7912. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7913. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7914. }
  7915. if (!namespace) {
  7916. namespace = detectNamespaceForChildElements(futureParentElement);
  7917. }
  7918. var $linkNode;
  7919. if (namespace !== 'html') {
  7920. // When using a directive with replace:true and templateUrl the $compileNodes
  7921. // (or a child element inside of them)
  7922. // might change, so we need to recreate the namespace adapted compileNodes
  7923. // for call to the link function.
  7924. // Note: This will already clone the nodes...
  7925. $linkNode = jqLite(
  7926. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7927. );
  7928. } else if (cloneConnectFn) {
  7929. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7930. // and sometimes changes the structure of the DOM.
  7931. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7932. } else {
  7933. $linkNode = $compileNodes;
  7934. }
  7935. if (transcludeControllers) {
  7936. for (var controllerName in transcludeControllers) {
  7937. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7938. }
  7939. }
  7940. compile.$$addScopeInfo($linkNode, scope);
  7941. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7942. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7943. if (!cloneConnectFn) {
  7944. $compileNodes = compositeLinkFn = null;
  7945. }
  7946. return $linkNode;
  7947. };
  7948. }
  7949. function detectNamespaceForChildElements(parentElement) {
  7950. // TODO: Make this detect MathML as well...
  7951. var node = parentElement && parentElement[0];
  7952. if (!node) {
  7953. return 'html';
  7954. } else {
  7955. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7956. }
  7957. }
  7958. /**
  7959. * Compile function matches each node in nodeList against the directives. Once all directives
  7960. * for a particular node are collected their compile functions are executed. The compile
  7961. * functions return values - the linking functions - are combined into a composite linking
  7962. * function, which is the a linking function for the node.
  7963. *
  7964. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7965. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7966. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7967. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7968. * the rootElement must be set the jqLite collection of the compile root. This is
  7969. * needed so that the jqLite collection items can be replaced with widgets.
  7970. * @param {number=} maxPriority Max directive priority.
  7971. * @returns {Function} A composite linking function of all of the matched directives or null.
  7972. */
  7973. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7974. previousCompileContext) {
  7975. var linkFns = [],
  7976. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  7977. // or a jqLite/jQuery collection or an array
  7978. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  7979. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7980. for (var i = 0; i < nodeList.length; i++) {
  7981. attrs = new Attributes();
  7982. // Support: IE 11 only
  7983. // Workaround for #11781 and #14924
  7984. if (msie === 11) {
  7985. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  7986. }
  7987. // We must always refer to `nodeList[i]` hereafter,
  7988. // since the nodes can be replaced underneath us.
  7989. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7990. ignoreDirective);
  7991. nodeLinkFn = (directives.length)
  7992. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7993. null, [], [], previousCompileContext)
  7994. : null;
  7995. if (nodeLinkFn && nodeLinkFn.scope) {
  7996. compile.$$addScopeClass(attrs.$$element);
  7997. }
  7998. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7999. !(childNodes = nodeList[i].childNodes) ||
  8000. !childNodes.length)
  8001. ? null
  8002. : compileNodes(childNodes,
  8003. nodeLinkFn ? (
  8004. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8005. && nodeLinkFn.transclude) : transcludeFn);
  8006. if (nodeLinkFn || childLinkFn) {
  8007. linkFns.push(i, nodeLinkFn, childLinkFn);
  8008. linkFnFound = true;
  8009. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8010. }
  8011. //use the previous context only for the first element in the virtual group
  8012. previousCompileContext = null;
  8013. }
  8014. // return a linking function if we have found anything, null otherwise
  8015. return linkFnFound ? compositeLinkFn : null;
  8016. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8017. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8018. var stableNodeList;
  8019. if (nodeLinkFnFound) {
  8020. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8021. // offsets don't get screwed up
  8022. var nodeListLength = nodeList.length;
  8023. stableNodeList = new Array(nodeListLength);
  8024. // create a sparse array by only copying the elements which have a linkFn
  8025. for (i = 0; i < linkFns.length; i += 3) {
  8026. idx = linkFns[i];
  8027. stableNodeList[idx] = nodeList[idx];
  8028. }
  8029. } else {
  8030. stableNodeList = nodeList;
  8031. }
  8032. for (i = 0, ii = linkFns.length; i < ii;) {
  8033. node = stableNodeList[linkFns[i++]];
  8034. nodeLinkFn = linkFns[i++];
  8035. childLinkFn = linkFns[i++];
  8036. if (nodeLinkFn) {
  8037. if (nodeLinkFn.scope) {
  8038. childScope = scope.$new();
  8039. compile.$$addScopeInfo(jqLite(node), childScope);
  8040. } else {
  8041. childScope = scope;
  8042. }
  8043. if (nodeLinkFn.transcludeOnThisElement) {
  8044. childBoundTranscludeFn = createBoundTranscludeFn(
  8045. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8046. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8047. childBoundTranscludeFn = parentBoundTranscludeFn;
  8048. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8049. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8050. } else {
  8051. childBoundTranscludeFn = null;
  8052. }
  8053. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8054. } else if (childLinkFn) {
  8055. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8056. }
  8057. }
  8058. }
  8059. }
  8060. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8061. var node = nodeList[idx];
  8062. var parent = node.parentNode;
  8063. var sibling;
  8064. if (node.nodeType !== NODE_TYPE_TEXT) {
  8065. return;
  8066. }
  8067. while (true) {
  8068. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8069. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8070. break;
  8071. }
  8072. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8073. if (sibling.parentNode) {
  8074. sibling.parentNode.removeChild(sibling);
  8075. }
  8076. if (notLiveList && sibling === nodeList[idx + 1]) {
  8077. nodeList.splice(idx + 1, 1);
  8078. }
  8079. }
  8080. }
  8081. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8082. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8083. if (!transcludedScope) {
  8084. transcludedScope = scope.$new(false, containingScope);
  8085. transcludedScope.$$transcluded = true;
  8086. }
  8087. return transcludeFn(transcludedScope, cloneFn, {
  8088. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8089. transcludeControllers: controllers,
  8090. futureParentElement: futureParentElement
  8091. });
  8092. }
  8093. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8094. // so that they are available inside the `controllersBoundTransclude` function
  8095. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8096. for (var slotName in transcludeFn.$$slots) {
  8097. if (transcludeFn.$$slots[slotName]) {
  8098. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8099. } else {
  8100. boundSlots[slotName] = null;
  8101. }
  8102. }
  8103. return boundTranscludeFn;
  8104. }
  8105. /**
  8106. * Looks for directives on the given node and adds them to the directive collection which is
  8107. * sorted.
  8108. *
  8109. * @param node Node to search.
  8110. * @param directives An array to which the directives are added to. This array is sorted before
  8111. * the function returns.
  8112. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8113. * @param {number=} maxPriority Max directive priority.
  8114. */
  8115. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8116. var nodeType = node.nodeType,
  8117. attrsMap = attrs.$attr,
  8118. match,
  8119. nodeName,
  8120. className;
  8121. switch (nodeType) {
  8122. case NODE_TYPE_ELEMENT: /* Element */
  8123. nodeName = nodeName_(node);
  8124. // use the node name: <directive>
  8125. addDirective(directives,
  8126. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8127. // iterate over the attributes
  8128. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8129. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8130. var attrStartName = false;
  8131. var attrEndName = false;
  8132. attr = nAttrs[j];
  8133. name = attr.name;
  8134. value = attr.value;
  8135. // support ngAttr attribute binding
  8136. ngAttrName = directiveNormalize(name);
  8137. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8138. if (isNgAttr) {
  8139. name = name.replace(PREFIX_REGEXP, '')
  8140. .substr(8).replace(/_(.)/g, function(match, letter) {
  8141. return letter.toUpperCase();
  8142. });
  8143. }
  8144. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8145. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8146. attrStartName = name;
  8147. attrEndName = name.substr(0, name.length - 5) + 'end';
  8148. name = name.substr(0, name.length - 6);
  8149. }
  8150. nName = directiveNormalize(name.toLowerCase());
  8151. attrsMap[nName] = name;
  8152. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8153. attrs[nName] = value;
  8154. if (getBooleanAttrName(node, nName)) {
  8155. attrs[nName] = true; // presence means true
  8156. }
  8157. }
  8158. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8159. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8160. attrEndName);
  8161. }
  8162. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8163. // Hidden input elements can have strange behaviour when navigating back to the page
  8164. // This tells the browser not to try to cache and reinstate previous values
  8165. node.setAttribute('autocomplete', 'off');
  8166. }
  8167. // use class as directive
  8168. if (!cssClassDirectivesEnabled) break;
  8169. className = node.className;
  8170. if (isObject(className)) {
  8171. // Maybe SVGAnimatedString
  8172. className = className.animVal;
  8173. }
  8174. if (isString(className) && className !== '') {
  8175. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8176. nName = directiveNormalize(match[2]);
  8177. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8178. attrs[nName] = trim(match[3]);
  8179. }
  8180. className = className.substr(match.index + match[0].length);
  8181. }
  8182. }
  8183. break;
  8184. case NODE_TYPE_TEXT: /* Text Node */
  8185. addTextInterpolateDirective(directives, node.nodeValue);
  8186. break;
  8187. case NODE_TYPE_COMMENT: /* Comment */
  8188. if (!commentDirectivesEnabled) break;
  8189. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8190. break;
  8191. }
  8192. directives.sort(byPriority);
  8193. return directives;
  8194. }
  8195. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8196. // function created because of performance, try/catch disables
  8197. // the optimization of the whole function #14848
  8198. try {
  8199. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8200. if (match) {
  8201. var nName = directiveNormalize(match[1]);
  8202. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8203. attrs[nName] = trim(match[2]);
  8204. }
  8205. }
  8206. } catch (e) {
  8207. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8208. // comment's node value.
  8209. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8210. }
  8211. }
  8212. /**
  8213. * Given a node with a directive-start it collects all of the siblings until it finds
  8214. * directive-end.
  8215. * @param node
  8216. * @param attrStart
  8217. * @param attrEnd
  8218. * @returns {*}
  8219. */
  8220. function groupScan(node, attrStart, attrEnd) {
  8221. var nodes = [];
  8222. var depth = 0;
  8223. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8224. do {
  8225. if (!node) {
  8226. throw $compileMinErr('uterdir',
  8227. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8228. attrStart, attrEnd);
  8229. }
  8230. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8231. if (node.hasAttribute(attrStart)) depth++;
  8232. if (node.hasAttribute(attrEnd)) depth--;
  8233. }
  8234. nodes.push(node);
  8235. node = node.nextSibling;
  8236. } while (depth > 0);
  8237. } else {
  8238. nodes.push(node);
  8239. }
  8240. return jqLite(nodes);
  8241. }
  8242. /**
  8243. * Wrapper for linking function which converts normal linking function into a grouped
  8244. * linking function.
  8245. * @param linkFn
  8246. * @param attrStart
  8247. * @param attrEnd
  8248. * @returns {Function}
  8249. */
  8250. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8251. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8252. element = groupScan(element[0], attrStart, attrEnd);
  8253. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8254. };
  8255. }
  8256. /**
  8257. * A function generator that is used to support both eager and lazy compilation
  8258. * linking function.
  8259. * @param eager
  8260. * @param $compileNodes
  8261. * @param transcludeFn
  8262. * @param maxPriority
  8263. * @param ignoreDirective
  8264. * @param previousCompileContext
  8265. * @returns {Function}
  8266. */
  8267. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8268. var compiled;
  8269. if (eager) {
  8270. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8271. }
  8272. return /** @this */ function lazyCompilation() {
  8273. if (!compiled) {
  8274. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8275. // Null out all of these references in order to make them eligible for garbage collection
  8276. // since this is a potentially long lived closure
  8277. $compileNodes = transcludeFn = previousCompileContext = null;
  8278. }
  8279. return compiled.apply(this, arguments);
  8280. };
  8281. }
  8282. /**
  8283. * Once the directives have been collected, their compile functions are executed. This method
  8284. * is responsible for inlining directive templates as well as terminating the application
  8285. * of the directives if the terminal directive has been reached.
  8286. *
  8287. * @param {Array} directives Array of collected directives to execute their compile function.
  8288. * this needs to be pre-sorted by priority order.
  8289. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8290. * @param {Object} templateAttrs The shared attribute function
  8291. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8292. * scope argument is auto-generated to the new
  8293. * child of the transcluded parent scope.
  8294. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8295. * argument has the root jqLite array so that we can replace nodes
  8296. * on it.
  8297. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8298. * compiling the transclusion.
  8299. * @param {Array.<Function>} preLinkFns
  8300. * @param {Array.<Function>} postLinkFns
  8301. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8302. * node
  8303. * @returns {Function} linkFn
  8304. */
  8305. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8306. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8307. previousCompileContext) {
  8308. previousCompileContext = previousCompileContext || {};
  8309. var terminalPriority = -Number.MAX_VALUE,
  8310. newScopeDirective = previousCompileContext.newScopeDirective,
  8311. controllerDirectives = previousCompileContext.controllerDirectives,
  8312. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8313. templateDirective = previousCompileContext.templateDirective,
  8314. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8315. hasTranscludeDirective = false,
  8316. hasTemplate = false,
  8317. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8318. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8319. directive,
  8320. directiveName,
  8321. $template,
  8322. replaceDirective = originalReplaceDirective,
  8323. childTranscludeFn = transcludeFn,
  8324. linkFn,
  8325. didScanForMultipleTransclusion = false,
  8326. mightHaveMultipleTransclusionError = false,
  8327. directiveValue;
  8328. // executes all directives on the current element
  8329. for (var i = 0, ii = directives.length; i < ii; i++) {
  8330. directive = directives[i];
  8331. var attrStart = directive.$$start;
  8332. var attrEnd = directive.$$end;
  8333. // collect multiblock sections
  8334. if (attrStart) {
  8335. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8336. }
  8337. $template = undefined;
  8338. if (terminalPriority > directive.priority) {
  8339. break; // prevent further processing of directives
  8340. }
  8341. directiveValue = directive.scope;
  8342. if (directiveValue) {
  8343. // skip the check for directives with async templates, we'll check the derived sync
  8344. // directive when the template arrives
  8345. if (!directive.templateUrl) {
  8346. if (isObject(directiveValue)) {
  8347. // This directive is trying to add an isolated scope.
  8348. // Check that there is no scope of any kind already
  8349. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8350. directive, $compileNode);
  8351. newIsolateScopeDirective = directive;
  8352. } else {
  8353. // This directive is trying to add a child scope.
  8354. // Check that there is no isolated scope already
  8355. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8356. $compileNode);
  8357. }
  8358. }
  8359. newScopeDirective = newScopeDirective || directive;
  8360. }
  8361. directiveName = directive.name;
  8362. // If we encounter a condition that can result in transclusion on the directive,
  8363. // then scan ahead in the remaining directives for others that may cause a multiple
  8364. // transclusion error to be thrown during the compilation process. If a matching directive
  8365. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8366. // compile the `transclude` function rather than doing it lazily in order to throw
  8367. // exceptions at the correct time
  8368. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8369. || (directive.transclude && !directive.$$tlb))) {
  8370. var candidateDirective;
  8371. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8372. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8373. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8374. mightHaveMultipleTransclusionError = true;
  8375. break;
  8376. }
  8377. }
  8378. didScanForMultipleTransclusion = true;
  8379. }
  8380. if (!directive.templateUrl && directive.controller) {
  8381. controllerDirectives = controllerDirectives || createMap();
  8382. assertNoDuplicate('\'' + directiveName + '\' controller',
  8383. controllerDirectives[directiveName], directive, $compileNode);
  8384. controllerDirectives[directiveName] = directive;
  8385. }
  8386. directiveValue = directive.transclude;
  8387. if (directiveValue) {
  8388. hasTranscludeDirective = true;
  8389. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8390. // This option should only be used by directives that know how to safely handle element transclusion,
  8391. // where the transcluded nodes are added or replaced after linking.
  8392. if (!directive.$$tlb) {
  8393. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8394. nonTlbTranscludeDirective = directive;
  8395. }
  8396. if (directiveValue === 'element') {
  8397. hasElementTranscludeDirective = true;
  8398. terminalPriority = directive.priority;
  8399. $template = $compileNode;
  8400. $compileNode = templateAttrs.$$element =
  8401. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8402. compileNode = $compileNode[0];
  8403. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8404. // Support: Chrome < 50
  8405. // https://github.com/angular/angular.js/issues/14041
  8406. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8407. // in the `replaceWith` function is improperly garbage collected despite still
  8408. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8409. // a reference to the fragment via a different property, we can avoid that incorrect
  8410. // behavior.
  8411. // TODO: remove this line after Chrome 50 has been released
  8412. $template[0].$$parentNode = $template[0].parentNode;
  8413. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8414. replaceDirective && replaceDirective.name, {
  8415. // Don't pass in:
  8416. // - controllerDirectives - otherwise we'll create duplicates controllers
  8417. // - newIsolateScopeDirective or templateDirective - combining templates with
  8418. // element transclusion doesn't make sense.
  8419. //
  8420. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8421. // on the same element more than once.
  8422. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8423. });
  8424. } else {
  8425. var slots = createMap();
  8426. if (!isObject(directiveValue)) {
  8427. $template = jqLite(jqLiteClone(compileNode)).contents();
  8428. } else {
  8429. // We have transclusion slots,
  8430. // collect them up, compile them and store their transclusion functions
  8431. $template = [];
  8432. var slotMap = createMap();
  8433. var filledSlots = createMap();
  8434. // Parse the element selectors
  8435. forEach(directiveValue, function(elementSelector, slotName) {
  8436. // If an element selector starts with a ? then it is optional
  8437. var optional = (elementSelector.charAt(0) === '?');
  8438. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8439. slotMap[elementSelector] = slotName;
  8440. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8441. // Later when calling boundTransclusion functions with a slot name we only error if the
  8442. // slot is `undefined`
  8443. slots[slotName] = null;
  8444. // filledSlots contains `true` for all slots that are either optional or have been
  8445. // filled. This is used to check that we have not missed any required slots
  8446. filledSlots[slotName] = optional;
  8447. });
  8448. // Add the matching elements into their slot
  8449. forEach($compileNode.contents(), function(node) {
  8450. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8451. if (slotName) {
  8452. filledSlots[slotName] = true;
  8453. slots[slotName] = slots[slotName] || [];
  8454. slots[slotName].push(node);
  8455. } else {
  8456. $template.push(node);
  8457. }
  8458. });
  8459. // Check for required slots that were not filled
  8460. forEach(filledSlots, function(filled, slotName) {
  8461. if (!filled) {
  8462. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8463. }
  8464. });
  8465. for (var slotName in slots) {
  8466. if (slots[slotName]) {
  8467. // Only define a transclusion function if the slot was filled
  8468. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8469. }
  8470. }
  8471. }
  8472. $compileNode.empty(); // clear contents
  8473. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8474. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8475. childTranscludeFn.$$slots = slots;
  8476. }
  8477. }
  8478. if (directive.template) {
  8479. hasTemplate = true;
  8480. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8481. templateDirective = directive;
  8482. directiveValue = (isFunction(directive.template))
  8483. ? directive.template($compileNode, templateAttrs)
  8484. : directive.template;
  8485. directiveValue = denormalizeTemplate(directiveValue);
  8486. if (directive.replace) {
  8487. replaceDirective = directive;
  8488. if (jqLiteIsTextNode(directiveValue)) {
  8489. $template = [];
  8490. } else {
  8491. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8492. }
  8493. compileNode = $template[0];
  8494. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8495. throw $compileMinErr('tplrt',
  8496. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8497. directiveName, '');
  8498. }
  8499. replaceWith(jqCollection, $compileNode, compileNode);
  8500. var newTemplateAttrs = {$attr: {}};
  8501. // combine directives from the original node and from the template:
  8502. // - take the array of directives for this element
  8503. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8504. // - collect directives from the template and sort them by priority
  8505. // - combine directives as: processed + template + unprocessed
  8506. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8507. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8508. if (newIsolateScopeDirective || newScopeDirective) {
  8509. // The original directive caused the current element to be replaced but this element
  8510. // also needs to have a new scope, so we need to tell the template directives
  8511. // that they would need to get their scope from further up, if they require transclusion
  8512. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8513. }
  8514. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8515. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8516. ii = directives.length;
  8517. } else {
  8518. $compileNode.html(directiveValue);
  8519. }
  8520. }
  8521. if (directive.templateUrl) {
  8522. hasTemplate = true;
  8523. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8524. templateDirective = directive;
  8525. if (directive.replace) {
  8526. replaceDirective = directive;
  8527. }
  8528. // eslint-disable-next-line no-func-assign
  8529. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8530. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8531. controllerDirectives: controllerDirectives,
  8532. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8533. newIsolateScopeDirective: newIsolateScopeDirective,
  8534. templateDirective: templateDirective,
  8535. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8536. });
  8537. ii = directives.length;
  8538. } else if (directive.compile) {
  8539. try {
  8540. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8541. var context = directive.$$originalDirective || directive;
  8542. if (isFunction(linkFn)) {
  8543. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8544. } else if (linkFn) {
  8545. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8546. }
  8547. } catch (e) {
  8548. $exceptionHandler(e, startingTag($compileNode));
  8549. }
  8550. }
  8551. if (directive.terminal) {
  8552. nodeLinkFn.terminal = true;
  8553. terminalPriority = Math.max(terminalPriority, directive.priority);
  8554. }
  8555. }
  8556. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8557. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8558. nodeLinkFn.templateOnThisElement = hasTemplate;
  8559. nodeLinkFn.transclude = childTranscludeFn;
  8560. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8561. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8562. return nodeLinkFn;
  8563. ////////////////////
  8564. function addLinkFns(pre, post, attrStart, attrEnd) {
  8565. if (pre) {
  8566. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8567. pre.require = directive.require;
  8568. pre.directiveName = directiveName;
  8569. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8570. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8571. }
  8572. preLinkFns.push(pre);
  8573. }
  8574. if (post) {
  8575. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8576. post.require = directive.require;
  8577. post.directiveName = directiveName;
  8578. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8579. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8580. }
  8581. postLinkFns.push(post);
  8582. }
  8583. }
  8584. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8585. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8586. attrs, scopeBindingInfo;
  8587. if (compileNode === linkNode) {
  8588. attrs = templateAttrs;
  8589. $element = templateAttrs.$$element;
  8590. } else {
  8591. $element = jqLite(linkNode);
  8592. attrs = new Attributes($element, templateAttrs);
  8593. }
  8594. controllerScope = scope;
  8595. if (newIsolateScopeDirective) {
  8596. isolateScope = scope.$new(true);
  8597. } else if (newScopeDirective) {
  8598. controllerScope = scope.$parent;
  8599. }
  8600. if (boundTranscludeFn) {
  8601. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8602. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8603. transcludeFn = controllersBoundTransclude;
  8604. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8605. // expose the slots on the `$transclude` function
  8606. transcludeFn.isSlotFilled = function(slotName) {
  8607. return !!boundTranscludeFn.$$slots[slotName];
  8608. };
  8609. }
  8610. if (controllerDirectives) {
  8611. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8612. }
  8613. if (newIsolateScopeDirective) {
  8614. // Initialize isolate scope bindings for new isolate scope directive.
  8615. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8616. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8617. compile.$$addScopeClass($element, true);
  8618. isolateScope.$$isolateBindings =
  8619. newIsolateScopeDirective.$$isolateBindings;
  8620. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8621. isolateScope.$$isolateBindings,
  8622. newIsolateScopeDirective);
  8623. if (scopeBindingInfo.removeWatches) {
  8624. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8625. }
  8626. }
  8627. // Initialize bindToController bindings
  8628. for (var name in elementControllers) {
  8629. var controllerDirective = controllerDirectives[name];
  8630. var controller = elementControllers[name];
  8631. var bindings = controllerDirective.$$bindings.bindToController;
  8632. if (preAssignBindingsEnabled) {
  8633. if (bindings) {
  8634. controller.bindingInfo =
  8635. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8636. } else {
  8637. controller.bindingInfo = {};
  8638. }
  8639. var controllerResult = controller();
  8640. if (controllerResult !== controller.instance) {
  8641. // If the controller constructor has a return value, overwrite the instance
  8642. // from setupControllers
  8643. controller.instance = controllerResult;
  8644. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8645. if (controller.bindingInfo.removeWatches) {
  8646. controller.bindingInfo.removeWatches();
  8647. }
  8648. controller.bindingInfo =
  8649. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8650. }
  8651. } else {
  8652. controller.instance = controller();
  8653. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8654. controller.bindingInfo =
  8655. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8656. }
  8657. }
  8658. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8659. forEach(controllerDirectives, function(controllerDirective, name) {
  8660. var require = controllerDirective.require;
  8661. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8662. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8663. }
  8664. });
  8665. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8666. forEach(elementControllers, function(controller) {
  8667. var controllerInstance = controller.instance;
  8668. if (isFunction(controllerInstance.$onChanges)) {
  8669. try {
  8670. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8671. } catch (e) {
  8672. $exceptionHandler(e);
  8673. }
  8674. }
  8675. if (isFunction(controllerInstance.$onInit)) {
  8676. try {
  8677. controllerInstance.$onInit();
  8678. } catch (e) {
  8679. $exceptionHandler(e);
  8680. }
  8681. }
  8682. if (isFunction(controllerInstance.$doCheck)) {
  8683. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8684. controllerInstance.$doCheck();
  8685. }
  8686. if (isFunction(controllerInstance.$onDestroy)) {
  8687. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8688. controllerInstance.$onDestroy();
  8689. });
  8690. }
  8691. });
  8692. // PRELINKING
  8693. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8694. linkFn = preLinkFns[i];
  8695. invokeLinkFn(linkFn,
  8696. linkFn.isolateScope ? isolateScope : scope,
  8697. $element,
  8698. attrs,
  8699. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8700. transcludeFn
  8701. );
  8702. }
  8703. // RECURSION
  8704. // We only pass the isolate scope, if the isolate directive has a template,
  8705. // otherwise the child elements do not belong to the isolate directive.
  8706. var scopeToChild = scope;
  8707. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8708. scopeToChild = isolateScope;
  8709. }
  8710. if (childLinkFn) {
  8711. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8712. }
  8713. // POSTLINKING
  8714. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8715. linkFn = postLinkFns[i];
  8716. invokeLinkFn(linkFn,
  8717. linkFn.isolateScope ? isolateScope : scope,
  8718. $element,
  8719. attrs,
  8720. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8721. transcludeFn
  8722. );
  8723. }
  8724. // Trigger $postLink lifecycle hooks
  8725. forEach(elementControllers, function(controller) {
  8726. var controllerInstance = controller.instance;
  8727. if (isFunction(controllerInstance.$postLink)) {
  8728. controllerInstance.$postLink();
  8729. }
  8730. });
  8731. // This is the function that is injected as `$transclude`.
  8732. // Note: all arguments are optional!
  8733. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8734. var transcludeControllers;
  8735. // No scope passed in:
  8736. if (!isScope(scope)) {
  8737. slotName = futureParentElement;
  8738. futureParentElement = cloneAttachFn;
  8739. cloneAttachFn = scope;
  8740. scope = undefined;
  8741. }
  8742. if (hasElementTranscludeDirective) {
  8743. transcludeControllers = elementControllers;
  8744. }
  8745. if (!futureParentElement) {
  8746. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8747. }
  8748. if (slotName) {
  8749. // slotTranscludeFn can be one of three things:
  8750. // * a transclude function - a filled slot
  8751. // * `null` - an optional slot that was not filled
  8752. // * `undefined` - a slot that was not declared (i.e. invalid)
  8753. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8754. if (slotTranscludeFn) {
  8755. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8756. } else if (isUndefined(slotTranscludeFn)) {
  8757. throw $compileMinErr('noslot',
  8758. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8759. 'Element: {1}',
  8760. slotName, startingTag($element));
  8761. }
  8762. } else {
  8763. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8764. }
  8765. }
  8766. }
  8767. }
  8768. function getControllers(directiveName, require, $element, elementControllers) {
  8769. var value;
  8770. if (isString(require)) {
  8771. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8772. var name = require.substring(match[0].length);
  8773. var inheritType = match[1] || match[3];
  8774. var optional = match[2] === '?';
  8775. //If only parents then start at the parent element
  8776. if (inheritType === '^^') {
  8777. $element = $element.parent();
  8778. //Otherwise attempt getting the controller from elementControllers in case
  8779. //the element is transcluded (and has no data) and to avoid .data if possible
  8780. } else {
  8781. value = elementControllers && elementControllers[name];
  8782. value = value && value.instance;
  8783. }
  8784. if (!value) {
  8785. var dataName = '$' + name + 'Controller';
  8786. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8787. }
  8788. if (!value && !optional) {
  8789. throw $compileMinErr('ctreq',
  8790. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  8791. name, directiveName);
  8792. }
  8793. } else if (isArray(require)) {
  8794. value = [];
  8795. for (var i = 0, ii = require.length; i < ii; i++) {
  8796. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8797. }
  8798. } else if (isObject(require)) {
  8799. value = {};
  8800. forEach(require, function(controller, property) {
  8801. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8802. });
  8803. }
  8804. return value || null;
  8805. }
  8806. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8807. var elementControllers = createMap();
  8808. for (var controllerKey in controllerDirectives) {
  8809. var directive = controllerDirectives[controllerKey];
  8810. var locals = {
  8811. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8812. $element: $element,
  8813. $attrs: attrs,
  8814. $transclude: transcludeFn
  8815. };
  8816. var controller = directive.controller;
  8817. if (controller === '@') {
  8818. controller = attrs[directive.name];
  8819. }
  8820. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8821. // For directives with element transclusion the element is a comment.
  8822. // In this case .data will not attach any data.
  8823. // Instead, we save the controllers for the element in a local hash and attach to .data
  8824. // later, once we have the actual element.
  8825. elementControllers[directive.name] = controllerInstance;
  8826. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8827. }
  8828. return elementControllers;
  8829. }
  8830. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8831. // or child scope created. For instance:
  8832. // * if the directive has been pulled into a template because another directive with a higher priority
  8833. // asked for element transclusion
  8834. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8835. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8836. function markDirectiveScope(directives, isolateScope, newScope) {
  8837. for (var j = 0, jj = directives.length; j < jj; j++) {
  8838. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8839. }
  8840. }
  8841. /**
  8842. * looks up the directive and decorates it with exception handling and proper parameters. We
  8843. * call this the boundDirective.
  8844. *
  8845. * @param {string} name name of the directive to look up.
  8846. * @param {string} location The directive must be found in specific format.
  8847. * String containing any of theses characters:
  8848. *
  8849. * * `E`: element name
  8850. * * `A': attribute
  8851. * * `C`: class
  8852. * * `M`: comment
  8853. * @returns {boolean} true if directive was added.
  8854. */
  8855. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8856. endAttrName) {
  8857. if (name === ignoreDirective) return null;
  8858. var match = null;
  8859. if (hasDirectives.hasOwnProperty(name)) {
  8860. for (var directive, directives = $injector.get(name + Suffix),
  8861. i = 0, ii = directives.length; i < ii; i++) {
  8862. directive = directives[i];
  8863. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8864. directive.restrict.indexOf(location) !== -1) {
  8865. if (startAttrName) {
  8866. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8867. }
  8868. if (!directive.$$bindings) {
  8869. var bindings = directive.$$bindings =
  8870. parseDirectiveBindings(directive, directive.name);
  8871. if (isObject(bindings.isolateScope)) {
  8872. directive.$$isolateBindings = bindings.isolateScope;
  8873. }
  8874. }
  8875. tDirectives.push(directive);
  8876. match = directive;
  8877. }
  8878. }
  8879. }
  8880. return match;
  8881. }
  8882. /**
  8883. * looks up the directive and returns true if it is a multi-element directive,
  8884. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8885. * together.
  8886. *
  8887. * @param {string} name name of the directive to look up.
  8888. * @returns true if directive was registered as multi-element.
  8889. */
  8890. function directiveIsMultiElement(name) {
  8891. if (hasDirectives.hasOwnProperty(name)) {
  8892. for (var directive, directives = $injector.get(name + Suffix),
  8893. i = 0, ii = directives.length; i < ii; i++) {
  8894. directive = directives[i];
  8895. if (directive.multiElement) {
  8896. return true;
  8897. }
  8898. }
  8899. }
  8900. return false;
  8901. }
  8902. /**
  8903. * When the element is replaced with HTML template then the new attributes
  8904. * on the template need to be merged with the existing attributes in the DOM.
  8905. * The desired effect is to have both of the attributes present.
  8906. *
  8907. * @param {object} dst destination attributes (original DOM)
  8908. * @param {object} src source attributes (from the directive template)
  8909. */
  8910. function mergeTemplateAttributes(dst, src) {
  8911. var srcAttr = src.$attr,
  8912. dstAttr = dst.$attr;
  8913. // reapply the old attributes to the new element
  8914. forEach(dst, function(value, key) {
  8915. if (key.charAt(0) !== '$') {
  8916. if (src[key] && src[key] !== value) {
  8917. if (value.length) {
  8918. value += (key === 'style' ? ';' : ' ') + src[key];
  8919. } else {
  8920. value = src[key];
  8921. }
  8922. }
  8923. dst.$set(key, value, true, srcAttr[key]);
  8924. }
  8925. });
  8926. // copy the new attributes on the old attrs object
  8927. forEach(src, function(value, key) {
  8928. // Check if we already set this attribute in the loop above.
  8929. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8930. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8931. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8932. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  8933. dst[key] = value;
  8934. if (key !== 'class' && key !== 'style') {
  8935. dstAttr[key] = srcAttr[key];
  8936. }
  8937. }
  8938. });
  8939. }
  8940. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8941. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8942. var linkQueue = [],
  8943. afterTemplateNodeLinkFn,
  8944. afterTemplateChildLinkFn,
  8945. beforeTemplateCompileNode = $compileNode[0],
  8946. origAsyncDirective = directives.shift(),
  8947. derivedSyncDirective = inherit(origAsyncDirective, {
  8948. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8949. }),
  8950. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8951. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8952. : origAsyncDirective.templateUrl,
  8953. templateNamespace = origAsyncDirective.templateNamespace;
  8954. $compileNode.empty();
  8955. $templateRequest(templateUrl)
  8956. .then(function(content) {
  8957. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8958. content = denormalizeTemplate(content);
  8959. if (origAsyncDirective.replace) {
  8960. if (jqLiteIsTextNode(content)) {
  8961. $template = [];
  8962. } else {
  8963. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8964. }
  8965. compileNode = $template[0];
  8966. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8967. throw $compileMinErr('tplrt',
  8968. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8969. origAsyncDirective.name, templateUrl);
  8970. }
  8971. tempTemplateAttrs = {$attr: {}};
  8972. replaceWith($rootElement, $compileNode, compileNode);
  8973. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8974. if (isObject(origAsyncDirective.scope)) {
  8975. // the original directive that caused the template to be loaded async required
  8976. // an isolate scope
  8977. markDirectiveScope(templateDirectives, true);
  8978. }
  8979. directives = templateDirectives.concat(directives);
  8980. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8981. } else {
  8982. compileNode = beforeTemplateCompileNode;
  8983. $compileNode.html(content);
  8984. }
  8985. directives.unshift(derivedSyncDirective);
  8986. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8987. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8988. previousCompileContext);
  8989. forEach($rootElement, function(node, i) {
  8990. if (node === compileNode) {
  8991. $rootElement[i] = $compileNode[0];
  8992. }
  8993. });
  8994. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8995. while (linkQueue.length) {
  8996. var scope = linkQueue.shift(),
  8997. beforeTemplateLinkNode = linkQueue.shift(),
  8998. linkRootElement = linkQueue.shift(),
  8999. boundTranscludeFn = linkQueue.shift(),
  9000. linkNode = $compileNode[0];
  9001. if (scope.$$destroyed) continue;
  9002. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9003. var oldClasses = beforeTemplateLinkNode.className;
  9004. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9005. origAsyncDirective.replace)) {
  9006. // it was cloned therefore we have to clone as well.
  9007. linkNode = jqLiteClone(compileNode);
  9008. }
  9009. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9010. // Copy in CSS classes from original node
  9011. safeAddClass(jqLite(linkNode), oldClasses);
  9012. }
  9013. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9014. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9015. } else {
  9016. childBoundTranscludeFn = boundTranscludeFn;
  9017. }
  9018. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9019. childBoundTranscludeFn);
  9020. }
  9021. linkQueue = null;
  9022. }).catch(function(error) {
  9023. if (error instanceof Error) {
  9024. $exceptionHandler(error);
  9025. }
  9026. }).catch(noop);
  9027. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9028. var childBoundTranscludeFn = boundTranscludeFn;
  9029. if (scope.$$destroyed) return;
  9030. if (linkQueue) {
  9031. linkQueue.push(scope,
  9032. node,
  9033. rootElement,
  9034. childBoundTranscludeFn);
  9035. } else {
  9036. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9037. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9038. }
  9039. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9040. }
  9041. };
  9042. }
  9043. /**
  9044. * Sorting function for bound directives.
  9045. */
  9046. function byPriority(a, b) {
  9047. var diff = b.priority - a.priority;
  9048. if (diff !== 0) return diff;
  9049. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9050. return a.index - b.index;
  9051. }
  9052. function assertNoDuplicate(what, previousDirective, directive, element) {
  9053. function wrapModuleNameIfDefined(moduleName) {
  9054. return moduleName ?
  9055. (' (module: ' + moduleName + ')') :
  9056. '';
  9057. }
  9058. if (previousDirective) {
  9059. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9060. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9061. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9062. }
  9063. }
  9064. function addTextInterpolateDirective(directives, text) {
  9065. var interpolateFn = $interpolate(text, true);
  9066. if (interpolateFn) {
  9067. directives.push({
  9068. priority: 0,
  9069. compile: function textInterpolateCompileFn(templateNode) {
  9070. var templateNodeParent = templateNode.parent(),
  9071. hasCompileParent = !!templateNodeParent.length;
  9072. // When transcluding a template that has bindings in the root
  9073. // we don't have a parent and thus need to add the class during linking fn.
  9074. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9075. return function textInterpolateLinkFn(scope, node) {
  9076. var parent = node.parent();
  9077. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9078. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9079. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9080. node[0].nodeValue = value;
  9081. });
  9082. };
  9083. }
  9084. });
  9085. }
  9086. }
  9087. function wrapTemplate(type, template) {
  9088. type = lowercase(type || 'html');
  9089. switch (type) {
  9090. case 'svg':
  9091. case 'math':
  9092. var wrapper = window.document.createElement('div');
  9093. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9094. return wrapper.childNodes[0].childNodes;
  9095. default:
  9096. return template;
  9097. }
  9098. }
  9099. function getTrustedContext(node, attrNormalizedName) {
  9100. if (attrNormalizedName === 'srcdoc') {
  9101. return $sce.HTML;
  9102. }
  9103. var tag = nodeName_(node);
  9104. // All tags with src attributes require a RESOURCE_URL value, except for
  9105. // img and various html5 media tags.
  9106. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9107. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9108. return $sce.RESOURCE_URL;
  9109. }
  9110. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9111. } else if (attrNormalizedName === 'xlinkHref' ||
  9112. (tag === 'form' && attrNormalizedName === 'action') ||
  9113. // links can be stylesheets or imports, which can run script in the current origin
  9114. (tag === 'link' && attrNormalizedName === 'href')
  9115. ) {
  9116. return $sce.RESOURCE_URL;
  9117. }
  9118. }
  9119. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9120. var trustedContext = getTrustedContext(node, name);
  9121. var mustHaveExpression = !isNgAttr;
  9122. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9123. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9124. // no interpolation found -> ignore
  9125. if (!interpolateFn) return;
  9126. if (name === 'multiple' && nodeName_(node) === 'select') {
  9127. throw $compileMinErr('selmulti',
  9128. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9129. startingTag(node));
  9130. }
  9131. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9132. throw $compileMinErr('nodomevents',
  9133. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9134. 'ng- versions (such as ng-click instead of onclick) instead.');
  9135. }
  9136. directives.push({
  9137. priority: 100,
  9138. compile: function() {
  9139. return {
  9140. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9141. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9142. // If the attribute has changed since last $interpolate()ed
  9143. var newValue = attr[name];
  9144. if (newValue !== value) {
  9145. // we need to interpolate again since the attribute value has been updated
  9146. // (e.g. by another directive's compile function)
  9147. // ensure unset/empty values make interpolateFn falsy
  9148. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9149. value = newValue;
  9150. }
  9151. // if attribute was updated so that there is no interpolation going on we don't want to
  9152. // register any observers
  9153. if (!interpolateFn) return;
  9154. // initialize attr object so that it's ready in case we need the value for isolate
  9155. // scope initialization, otherwise the value would not be available from isolate
  9156. // directive's linking fn during linking phase
  9157. attr[name] = interpolateFn(scope);
  9158. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9159. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9160. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9161. //special case for class attribute addition + removal
  9162. //so that class changes can tap into the animation
  9163. //hooks provided by the $animate service. Be sure to
  9164. //skip animations when the first digest occurs (when
  9165. //both the new and the old values are the same) since
  9166. //the CSS classes are the non-interpolated values
  9167. if (name === 'class' && newValue !== oldValue) {
  9168. attr.$updateClass(newValue, oldValue);
  9169. } else {
  9170. attr.$set(name, newValue);
  9171. }
  9172. });
  9173. }
  9174. };
  9175. }
  9176. });
  9177. }
  9178. /**
  9179. * This is a special jqLite.replaceWith, which can replace items which
  9180. * have no parents, provided that the containing jqLite collection is provided.
  9181. *
  9182. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9183. * in the root of the tree.
  9184. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9185. * the shell, but replace its DOM node reference.
  9186. * @param {Node} newNode The new DOM node.
  9187. */
  9188. function replaceWith($rootElement, elementsToRemove, newNode) {
  9189. var firstElementToRemove = elementsToRemove[0],
  9190. removeCount = elementsToRemove.length,
  9191. parent = firstElementToRemove.parentNode,
  9192. i, ii;
  9193. if ($rootElement) {
  9194. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9195. if ($rootElement[i] === firstElementToRemove) {
  9196. $rootElement[i++] = newNode;
  9197. for (var j = i, j2 = j + removeCount - 1,
  9198. jj = $rootElement.length;
  9199. j < jj; j++, j2++) {
  9200. if (j2 < jj) {
  9201. $rootElement[j] = $rootElement[j2];
  9202. } else {
  9203. delete $rootElement[j];
  9204. }
  9205. }
  9206. $rootElement.length -= removeCount - 1;
  9207. // If the replaced element is also the jQuery .context then replace it
  9208. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9209. // http://api.jquery.com/context/
  9210. if ($rootElement.context === firstElementToRemove) {
  9211. $rootElement.context = newNode;
  9212. }
  9213. break;
  9214. }
  9215. }
  9216. }
  9217. if (parent) {
  9218. parent.replaceChild(newNode, firstElementToRemove);
  9219. }
  9220. // Append all the `elementsToRemove` to a fragment. This will...
  9221. // - remove them from the DOM
  9222. // - allow them to still be traversed with .nextSibling
  9223. // - allow a single fragment.qSA to fetch all elements being removed
  9224. var fragment = window.document.createDocumentFragment();
  9225. for (i = 0; i < removeCount; i++) {
  9226. fragment.appendChild(elementsToRemove[i]);
  9227. }
  9228. if (jqLite.hasData(firstElementToRemove)) {
  9229. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9230. // data here because there's no public interface in jQuery to do that and copying over
  9231. // event listeners (which is the main use of private data) wouldn't work anyway.
  9232. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9233. // Remove $destroy event listeners from `firstElementToRemove`
  9234. jqLite(firstElementToRemove).off('$destroy');
  9235. }
  9236. // Cleanup any data/listeners on the elements and children.
  9237. // This includes invoking the $destroy event on any elements with listeners.
  9238. jqLite.cleanData(fragment.querySelectorAll('*'));
  9239. // Update the jqLite collection to only contain the `newNode`
  9240. for (i = 1; i < removeCount; i++) {
  9241. delete elementsToRemove[i];
  9242. }
  9243. elementsToRemove[0] = newNode;
  9244. elementsToRemove.length = 1;
  9245. }
  9246. function cloneAndAnnotateFn(fn, annotation) {
  9247. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9248. }
  9249. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9250. try {
  9251. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9252. } catch (e) {
  9253. $exceptionHandler(e, startingTag($element));
  9254. }
  9255. }
  9256. // Set up $watches for isolate scope and controller bindings.
  9257. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9258. var removeWatchCollection = [];
  9259. var initialChanges = {};
  9260. var changes;
  9261. forEach(bindings, function initializeBinding(definition, scopeName) {
  9262. var attrName = definition.attrName,
  9263. optional = definition.optional,
  9264. mode = definition.mode, // @, =, <, or &
  9265. lastValue,
  9266. parentGet, parentSet, compare, removeWatch;
  9267. switch (mode) {
  9268. case '@':
  9269. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9270. destination[scopeName] = attrs[attrName] = undefined;
  9271. }
  9272. removeWatch = attrs.$observe(attrName, function(value) {
  9273. if (isString(value) || isBoolean(value)) {
  9274. var oldValue = destination[scopeName];
  9275. recordChanges(scopeName, value, oldValue);
  9276. destination[scopeName] = value;
  9277. }
  9278. });
  9279. attrs.$$observers[attrName].$$scope = scope;
  9280. lastValue = attrs[attrName];
  9281. if (isString(lastValue)) {
  9282. // If the attribute has been provided then we trigger an interpolation to ensure
  9283. // the value is there for use in the link fn
  9284. destination[scopeName] = $interpolate(lastValue)(scope);
  9285. } else if (isBoolean(lastValue)) {
  9286. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9287. // the value to boolean rather than a string, so we special case this situation
  9288. destination[scopeName] = lastValue;
  9289. }
  9290. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9291. removeWatchCollection.push(removeWatch);
  9292. break;
  9293. case '=':
  9294. if (!hasOwnProperty.call(attrs, attrName)) {
  9295. if (optional) break;
  9296. attrs[attrName] = undefined;
  9297. }
  9298. if (optional && !attrs[attrName]) break;
  9299. parentGet = $parse(attrs[attrName]);
  9300. if (parentGet.literal) {
  9301. compare = equals;
  9302. } else {
  9303. // eslint-disable-next-line no-self-compare
  9304. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  9305. }
  9306. parentSet = parentGet.assign || function() {
  9307. // reset the change, or we will throw this exception on every $digest
  9308. lastValue = destination[scopeName] = parentGet(scope);
  9309. throw $compileMinErr('nonassign',
  9310. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9311. attrs[attrName], attrName, directive.name);
  9312. };
  9313. lastValue = destination[scopeName] = parentGet(scope);
  9314. var parentValueWatch = function parentValueWatch(parentValue) {
  9315. if (!compare(parentValue, destination[scopeName])) {
  9316. // we are out of sync and need to copy
  9317. if (!compare(parentValue, lastValue)) {
  9318. // parent changed and it has precedence
  9319. destination[scopeName] = parentValue;
  9320. } else {
  9321. // if the parent can be assigned then do so
  9322. parentSet(scope, parentValue = destination[scopeName]);
  9323. }
  9324. }
  9325. lastValue = parentValue;
  9326. return lastValue;
  9327. };
  9328. parentValueWatch.$stateful = true;
  9329. if (definition.collection) {
  9330. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9331. } else {
  9332. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9333. }
  9334. removeWatchCollection.push(removeWatch);
  9335. break;
  9336. case '<':
  9337. if (!hasOwnProperty.call(attrs, attrName)) {
  9338. if (optional) break;
  9339. attrs[attrName] = undefined;
  9340. }
  9341. if (optional && !attrs[attrName]) break;
  9342. parentGet = $parse(attrs[attrName]);
  9343. var deepWatch = parentGet.literal;
  9344. var initialValue = destination[scopeName] = parentGet(scope);
  9345. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9346. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9347. if (oldValue === newValue) {
  9348. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9349. return;
  9350. }
  9351. oldValue = initialValue;
  9352. }
  9353. recordChanges(scopeName, newValue, oldValue);
  9354. destination[scopeName] = newValue;
  9355. }, deepWatch);
  9356. removeWatchCollection.push(removeWatch);
  9357. break;
  9358. case '&':
  9359. // Don't assign Object.prototype method to scope
  9360. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9361. // Don't assign noop to destination if expression is not valid
  9362. if (parentGet === noop && optional) break;
  9363. destination[scopeName] = function(locals) {
  9364. return parentGet(scope, locals);
  9365. };
  9366. break;
  9367. }
  9368. });
  9369. function recordChanges(key, currentValue, previousValue) {
  9370. if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
  9371. // eslint-disable-next-line no-self-compare
  9372. (currentValue === currentValue || previousValue === previousValue)) {
  9373. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9374. if (!onChangesQueue) {
  9375. scope.$$postDigest(flushOnChangesQueue);
  9376. onChangesQueue = [];
  9377. }
  9378. // If we have not already queued a trigger of onChanges for this controller then do so now
  9379. if (!changes) {
  9380. changes = {};
  9381. onChangesQueue.push(triggerOnChangesHook);
  9382. }
  9383. // If the has been a change on this property already then we need to reuse the previous value
  9384. if (changes[key]) {
  9385. previousValue = changes[key].previousValue;
  9386. }
  9387. // Store this change
  9388. changes[key] = new SimpleChange(previousValue, currentValue);
  9389. }
  9390. }
  9391. function triggerOnChangesHook() {
  9392. destination.$onChanges(changes);
  9393. // Now clear the changes so that we schedule onChanges when more changes arrive
  9394. changes = undefined;
  9395. }
  9396. return {
  9397. initialChanges: initialChanges,
  9398. removeWatches: removeWatchCollection.length && function removeWatches() {
  9399. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9400. removeWatchCollection[i]();
  9401. }
  9402. }
  9403. };
  9404. }
  9405. }];
  9406. }
  9407. function SimpleChange(previous, current) {
  9408. this.previousValue = previous;
  9409. this.currentValue = current;
  9410. }
  9411. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9412. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9413. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9414. /**
  9415. * Converts all accepted directives format into proper directive name.
  9416. * @param name Name to normalize
  9417. */
  9418. function directiveNormalize(name) {
  9419. return name
  9420. .replace(PREFIX_REGEXP, '')
  9421. .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
  9422. }
  9423. /**
  9424. * @ngdoc type
  9425. * @name $compile.directive.Attributes
  9426. *
  9427. * @description
  9428. * A shared object between directive compile / linking functions which contains normalized DOM
  9429. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9430. * needed since all of these are treated as equivalent in Angular:
  9431. *
  9432. * ```
  9433. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9434. * ```
  9435. */
  9436. /**
  9437. * @ngdoc property
  9438. * @name $compile.directive.Attributes#$attr
  9439. *
  9440. * @description
  9441. * A map of DOM element attribute names to the normalized name. This is
  9442. * needed to do reverse lookup from normalized name back to actual name.
  9443. */
  9444. /**
  9445. * @ngdoc method
  9446. * @name $compile.directive.Attributes#$set
  9447. * @kind function
  9448. *
  9449. * @description
  9450. * Set DOM element attribute value.
  9451. *
  9452. *
  9453. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9454. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9455. * property to the original name.
  9456. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9457. */
  9458. /**
  9459. * Closure compiler type information
  9460. */
  9461. function nodesetLinkingFn(
  9462. /* angular.Scope */ scope,
  9463. /* NodeList */ nodeList,
  9464. /* Element */ rootElement,
  9465. /* function(Function) */ boundTranscludeFn
  9466. ) {}
  9467. function directiveLinkingFn(
  9468. /* nodesetLinkingFn */ nodesetLinkingFn,
  9469. /* angular.Scope */ scope,
  9470. /* Node */ node,
  9471. /* Element */ rootElement,
  9472. /* function(Function) */ boundTranscludeFn
  9473. ) {}
  9474. function tokenDifference(str1, str2) {
  9475. var values = '',
  9476. tokens1 = str1.split(/\s+/),
  9477. tokens2 = str2.split(/\s+/);
  9478. outer:
  9479. for (var i = 0; i < tokens1.length; i++) {
  9480. var token = tokens1[i];
  9481. for (var j = 0; j < tokens2.length; j++) {
  9482. if (token === tokens2[j]) continue outer;
  9483. }
  9484. values += (values.length > 0 ? ' ' : '') + token;
  9485. }
  9486. return values;
  9487. }
  9488. function removeComments(jqNodes) {
  9489. jqNodes = jqLite(jqNodes);
  9490. var i = jqNodes.length;
  9491. if (i <= 1) {
  9492. return jqNodes;
  9493. }
  9494. while (i--) {
  9495. var node = jqNodes[i];
  9496. if (node.nodeType === NODE_TYPE_COMMENT ||
  9497. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9498. splice.call(jqNodes, i, 1);
  9499. }
  9500. }
  9501. return jqNodes;
  9502. }
  9503. var $controllerMinErr = minErr('$controller');
  9504. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9505. function identifierForController(controller, ident) {
  9506. if (ident && isString(ident)) return ident;
  9507. if (isString(controller)) {
  9508. var match = CNTRL_REG.exec(controller);
  9509. if (match) return match[3];
  9510. }
  9511. }
  9512. /**
  9513. * @ngdoc provider
  9514. * @name $controllerProvider
  9515. * @this
  9516. *
  9517. * @description
  9518. * The {@link ng.$controller $controller service} is used by Angular to create new
  9519. * controllers.
  9520. *
  9521. * This provider allows controller registration via the
  9522. * {@link ng.$controllerProvider#register register} method.
  9523. */
  9524. function $ControllerProvider() {
  9525. var controllers = {},
  9526. globals = false;
  9527. /**
  9528. * @ngdoc method
  9529. * @name $controllerProvider#has
  9530. * @param {string} name Controller name to check.
  9531. */
  9532. this.has = function(name) {
  9533. return controllers.hasOwnProperty(name);
  9534. };
  9535. /**
  9536. * @ngdoc method
  9537. * @name $controllerProvider#register
  9538. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9539. * the names and the values are the constructors.
  9540. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9541. * annotations in the array notation).
  9542. */
  9543. this.register = function(name, constructor) {
  9544. assertNotHasOwnProperty(name, 'controller');
  9545. if (isObject(name)) {
  9546. extend(controllers, name);
  9547. } else {
  9548. controllers[name] = constructor;
  9549. }
  9550. };
  9551. /**
  9552. * @ngdoc method
  9553. * @name $controllerProvider#allowGlobals
  9554. * @description If called, allows `$controller` to find controller constructors on `window`
  9555. *
  9556. * @deprecated
  9557. * sinceVersion="v1.3.0"
  9558. * removeVersion="v1.7.0"
  9559. * This method of finding controllers has been deprecated.
  9560. */
  9561. this.allowGlobals = function() {
  9562. globals = true;
  9563. };
  9564. this.$get = ['$injector', '$window', function($injector, $window) {
  9565. /**
  9566. * @ngdoc service
  9567. * @name $controller
  9568. * @requires $injector
  9569. *
  9570. * @param {Function|string} constructor If called with a function then it's considered to be the
  9571. * controller constructor function. Otherwise it's considered to be a string which is used
  9572. * to retrieve the controller constructor using the following steps:
  9573. *
  9574. * * check if a controller with given name is registered via `$controllerProvider`
  9575. * * check if evaluating the string on the current scope returns a constructor
  9576. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9577. * `window` object (deprecated, not recommended)
  9578. *
  9579. * The string can use the `controller as property` syntax, where the controller instance is published
  9580. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9581. * to work correctly.
  9582. *
  9583. * @param {Object} locals Injection locals for Controller.
  9584. * @return {Object} Instance of given controller.
  9585. *
  9586. * @description
  9587. * `$controller` service is responsible for instantiating controllers.
  9588. *
  9589. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9590. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9591. */
  9592. return function $controller(expression, locals, later, ident) {
  9593. // PRIVATE API:
  9594. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9595. // If true, $controller will allocate the object with the correct
  9596. // prototype chain, but will not invoke the controller until a returned
  9597. // callback is invoked.
  9598. // param `ident` --- An optional label which overrides the label parsed from the controller
  9599. // expression, if any.
  9600. var instance, match, constructor, identifier;
  9601. later = later === true;
  9602. if (ident && isString(ident)) {
  9603. identifier = ident;
  9604. }
  9605. if (isString(expression)) {
  9606. match = expression.match(CNTRL_REG);
  9607. if (!match) {
  9608. throw $controllerMinErr('ctrlfmt',
  9609. 'Badly formed controller string \'{0}\'. ' +
  9610. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9611. }
  9612. constructor = match[1];
  9613. identifier = identifier || match[3];
  9614. expression = controllers.hasOwnProperty(constructor)
  9615. ? controllers[constructor]
  9616. : getter(locals.$scope, constructor, true) ||
  9617. (globals ? getter($window, constructor, true) : undefined);
  9618. if (!expression) {
  9619. throw $controllerMinErr('ctrlreg',
  9620. 'The controller with the name \'{0}\' is not registered.', constructor);
  9621. }
  9622. assertArgFn(expression, constructor, true);
  9623. }
  9624. if (later) {
  9625. // Instantiate controller later:
  9626. // This machinery is used to create an instance of the object before calling the
  9627. // controller's constructor itself.
  9628. //
  9629. // This allows properties to be added to the controller before the constructor is
  9630. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9631. //
  9632. // This feature is not intended for use by applications, and is thus not documented
  9633. // publicly.
  9634. // Object creation: http://jsperf.com/create-constructor/2
  9635. var controllerPrototype = (isArray(expression) ?
  9636. expression[expression.length - 1] : expression).prototype;
  9637. instance = Object.create(controllerPrototype || null);
  9638. if (identifier) {
  9639. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9640. }
  9641. return extend(function $controllerInit() {
  9642. var result = $injector.invoke(expression, instance, locals, constructor);
  9643. if (result !== instance && (isObject(result) || isFunction(result))) {
  9644. instance = result;
  9645. if (identifier) {
  9646. // If result changed, re-assign controllerAs value to scope.
  9647. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9648. }
  9649. }
  9650. return instance;
  9651. }, {
  9652. instance: instance,
  9653. identifier: identifier
  9654. });
  9655. }
  9656. instance = $injector.instantiate(expression, locals, constructor);
  9657. if (identifier) {
  9658. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9659. }
  9660. return instance;
  9661. };
  9662. function addIdentifier(locals, identifier, instance, name) {
  9663. if (!(locals && isObject(locals.$scope))) {
  9664. throw minErr('$controller')('noscp',
  9665. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9666. name, identifier);
  9667. }
  9668. locals.$scope[identifier] = instance;
  9669. }
  9670. }];
  9671. }
  9672. /**
  9673. * @ngdoc service
  9674. * @name $document
  9675. * @requires $window
  9676. * @this
  9677. *
  9678. * @description
  9679. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9680. *
  9681. * @example
  9682. <example module="documentExample" name="document">
  9683. <file name="index.html">
  9684. <div ng-controller="ExampleController">
  9685. <p>$document title: <b ng-bind="title"></b></p>
  9686. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9687. </div>
  9688. </file>
  9689. <file name="script.js">
  9690. angular.module('documentExample', [])
  9691. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9692. $scope.title = $document[0].title;
  9693. $scope.windowTitle = angular.element(window.document)[0].title;
  9694. }]);
  9695. </file>
  9696. </example>
  9697. */
  9698. function $DocumentProvider() {
  9699. this.$get = ['$window', function(window) {
  9700. return jqLite(window.document);
  9701. }];
  9702. }
  9703. /**
  9704. * @private
  9705. * @this
  9706. * Listens for document visibility change and makes the current status accessible.
  9707. */
  9708. function $$IsDocumentHiddenProvider() {
  9709. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9710. var doc = $document[0];
  9711. var hidden = doc && doc.hidden;
  9712. $document.on('visibilitychange', changeListener);
  9713. $rootScope.$on('$destroy', function() {
  9714. $document.off('visibilitychange', changeListener);
  9715. });
  9716. function changeListener() {
  9717. hidden = doc.hidden;
  9718. }
  9719. return function() {
  9720. return hidden;
  9721. };
  9722. }];
  9723. }
  9724. /**
  9725. * @ngdoc service
  9726. * @name $exceptionHandler
  9727. * @requires ng.$log
  9728. * @this
  9729. *
  9730. * @description
  9731. * Any uncaught exception in angular expressions is delegated to this service.
  9732. * The default implementation simply delegates to `$log.error` which logs it into
  9733. * the browser console.
  9734. *
  9735. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9736. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9737. *
  9738. * ## Example:
  9739. *
  9740. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9741. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9742. * of `$log.error()`.
  9743. *
  9744. * ```js
  9745. * angular.
  9746. * module('exceptionOverwrite', []).
  9747. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9748. * return function myExceptionHandler(exception, cause) {
  9749. * logErrorsToBackend(exception, cause);
  9750. * $log.warn(exception, cause);
  9751. * };
  9752. * }]);
  9753. * ```
  9754. *
  9755. * <hr />
  9756. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9757. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9758. * (unless executed during a digest).
  9759. *
  9760. * If you wish, you can manually delegate exceptions, e.g.
  9761. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9762. *
  9763. * @param {Error} exception Exception associated with the error.
  9764. * @param {string=} cause Optional information about the context in which
  9765. * the error was thrown.
  9766. *
  9767. */
  9768. function $ExceptionHandlerProvider() {
  9769. this.$get = ['$log', function($log) {
  9770. return function(exception, cause) {
  9771. $log.error.apply($log, arguments);
  9772. };
  9773. }];
  9774. }
  9775. var $$ForceReflowProvider = /** @this */ function() {
  9776. this.$get = ['$document', function($document) {
  9777. return function(domNode) {
  9778. //the line below will force the browser to perform a repaint so
  9779. //that all the animated elements within the animation frame will
  9780. //be properly updated and drawn on screen. This is required to
  9781. //ensure that the preparation animation is properly flushed so that
  9782. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9783. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9784. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9785. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9786. if (domNode) {
  9787. if (!domNode.nodeType && domNode instanceof jqLite) {
  9788. domNode = domNode[0];
  9789. }
  9790. } else {
  9791. domNode = $document[0].body;
  9792. }
  9793. return domNode.offsetWidth + 1;
  9794. };
  9795. }];
  9796. };
  9797. var APPLICATION_JSON = 'application/json';
  9798. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9799. var JSON_START = /^\[|^\{(?!\{)/;
  9800. var JSON_ENDS = {
  9801. '[': /]$/,
  9802. '{': /}$/
  9803. };
  9804. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  9805. var $httpMinErr = minErr('$http');
  9806. function serializeValue(v) {
  9807. if (isObject(v)) {
  9808. return isDate(v) ? v.toISOString() : toJson(v);
  9809. }
  9810. return v;
  9811. }
  9812. /** @this */
  9813. function $HttpParamSerializerProvider() {
  9814. /**
  9815. * @ngdoc service
  9816. * @name $httpParamSerializer
  9817. * @description
  9818. *
  9819. * Default {@link $http `$http`} params serializer that converts objects to strings
  9820. * according to the following rules:
  9821. *
  9822. * * `{'foo': 'bar'}` results in `foo=bar`
  9823. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9824. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9825. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9826. *
  9827. * Note that serializer will sort the request parameters alphabetically.
  9828. * */
  9829. this.$get = function() {
  9830. return function ngParamSerializer(params) {
  9831. if (!params) return '';
  9832. var parts = [];
  9833. forEachSorted(params, function(value, key) {
  9834. if (value === null || isUndefined(value)) return;
  9835. if (isArray(value)) {
  9836. forEach(value, function(v) {
  9837. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9838. });
  9839. } else {
  9840. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9841. }
  9842. });
  9843. return parts.join('&');
  9844. };
  9845. };
  9846. }
  9847. /** @this */
  9848. function $HttpParamSerializerJQLikeProvider() {
  9849. /**
  9850. * @ngdoc service
  9851. * @name $httpParamSerializerJQLike
  9852. *
  9853. * @description
  9854. *
  9855. * Alternative {@link $http `$http`} params serializer that follows
  9856. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9857. * The serializer will also sort the params alphabetically.
  9858. *
  9859. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9860. *
  9861. * ```js
  9862. * $http({
  9863. * url: myUrl,
  9864. * method: 'GET',
  9865. * params: myParams,
  9866. * paramSerializer: '$httpParamSerializerJQLike'
  9867. * });
  9868. * ```
  9869. *
  9870. * It is also possible to set it as the default `paramSerializer` in the
  9871. * {@link $httpProvider#defaults `$httpProvider`}.
  9872. *
  9873. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9874. * form data for submission:
  9875. *
  9876. * ```js
  9877. * .controller(function($http, $httpParamSerializerJQLike) {
  9878. * //...
  9879. *
  9880. * $http({
  9881. * url: myUrl,
  9882. * method: 'POST',
  9883. * data: $httpParamSerializerJQLike(myData),
  9884. * headers: {
  9885. * 'Content-Type': 'application/x-www-form-urlencoded'
  9886. * }
  9887. * });
  9888. *
  9889. * });
  9890. * ```
  9891. *
  9892. * */
  9893. this.$get = function() {
  9894. return function jQueryLikeParamSerializer(params) {
  9895. if (!params) return '';
  9896. var parts = [];
  9897. serialize(params, '', true);
  9898. return parts.join('&');
  9899. function serialize(toSerialize, prefix, topLevel) {
  9900. if (toSerialize === null || isUndefined(toSerialize)) return;
  9901. if (isArray(toSerialize)) {
  9902. forEach(toSerialize, function(value, index) {
  9903. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9904. });
  9905. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9906. forEachSorted(toSerialize, function(value, key) {
  9907. serialize(value, prefix +
  9908. (topLevel ? '' : '[') +
  9909. key +
  9910. (topLevel ? '' : ']'));
  9911. });
  9912. } else {
  9913. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9914. }
  9915. }
  9916. };
  9917. };
  9918. }
  9919. function defaultHttpResponseTransform(data, headers) {
  9920. if (isString(data)) {
  9921. // Strip json vulnerability protection prefix and trim whitespace
  9922. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9923. if (tempData) {
  9924. var contentType = headers('Content-Type');
  9925. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9926. data = fromJson(tempData);
  9927. }
  9928. }
  9929. }
  9930. return data;
  9931. }
  9932. function isJsonLike(str) {
  9933. var jsonStart = str.match(JSON_START);
  9934. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9935. }
  9936. /**
  9937. * Parse headers into key value object
  9938. *
  9939. * @param {string} headers Raw headers as a string
  9940. * @returns {Object} Parsed headers as key value object
  9941. */
  9942. function parseHeaders(headers) {
  9943. var parsed = createMap(), i;
  9944. function fillInParsed(key, val) {
  9945. if (key) {
  9946. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9947. }
  9948. }
  9949. if (isString(headers)) {
  9950. forEach(headers.split('\n'), function(line) {
  9951. i = line.indexOf(':');
  9952. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9953. });
  9954. } else if (isObject(headers)) {
  9955. forEach(headers, function(headerVal, headerKey) {
  9956. fillInParsed(lowercase(headerKey), trim(headerVal));
  9957. });
  9958. }
  9959. return parsed;
  9960. }
  9961. /**
  9962. * Returns a function that provides access to parsed headers.
  9963. *
  9964. * Headers are lazy parsed when first requested.
  9965. * @see parseHeaders
  9966. *
  9967. * @param {(string|Object)} headers Headers to provide access to.
  9968. * @returns {function(string=)} Returns a getter function which if called with:
  9969. *
  9970. * - if called with an argument returns a single header value or null
  9971. * - if called with no arguments returns an object containing all headers.
  9972. */
  9973. function headersGetter(headers) {
  9974. var headersObj;
  9975. return function(name) {
  9976. if (!headersObj) headersObj = parseHeaders(headers);
  9977. if (name) {
  9978. var value = headersObj[lowercase(name)];
  9979. if (value === undefined) {
  9980. value = null;
  9981. }
  9982. return value;
  9983. }
  9984. return headersObj;
  9985. };
  9986. }
  9987. /**
  9988. * Chain all given functions
  9989. *
  9990. * This function is used for both request and response transforming
  9991. *
  9992. * @param {*} data Data to transform.
  9993. * @param {function(string=)} headers HTTP headers getter fn.
  9994. * @param {number} status HTTP status code of the response.
  9995. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9996. * @returns {*} Transformed data.
  9997. */
  9998. function transformData(data, headers, status, fns) {
  9999. if (isFunction(fns)) {
  10000. return fns(data, headers, status);
  10001. }
  10002. forEach(fns, function(fn) {
  10003. data = fn(data, headers, status);
  10004. });
  10005. return data;
  10006. }
  10007. function isSuccess(status) {
  10008. return 200 <= status && status < 300;
  10009. }
  10010. /**
  10011. * @ngdoc provider
  10012. * @name $httpProvider
  10013. * @this
  10014. *
  10015. * @description
  10016. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10017. * */
  10018. function $HttpProvider() {
  10019. /**
  10020. * @ngdoc property
  10021. * @name $httpProvider#defaults
  10022. * @description
  10023. *
  10024. * Object containing default values for all {@link ng.$http $http} requests.
  10025. *
  10026. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10027. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10028. * by default. See {@link $http#caching $http Caching} for more information.
  10029. *
  10030. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10031. * Defaults value is `'XSRF-TOKEN'`.
  10032. *
  10033. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10034. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10035. *
  10036. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10037. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10038. * setting default headers.
  10039. * - **`defaults.headers.common`**
  10040. * - **`defaults.headers.post`**
  10041. * - **`defaults.headers.put`**
  10042. * - **`defaults.headers.patch`**
  10043. *
  10044. *
  10045. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10046. * used to the prepare string representation of request parameters (specified as an object).
  10047. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10048. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10049. *
  10050. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10051. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10052. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10053. *
  10054. **/
  10055. var defaults = this.defaults = {
  10056. // transform incoming response data
  10057. transformResponse: [defaultHttpResponseTransform],
  10058. // transform outgoing request data
  10059. transformRequest: [function(d) {
  10060. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10061. }],
  10062. // default headers
  10063. headers: {
  10064. common: {
  10065. 'Accept': 'application/json, text/plain, */*'
  10066. },
  10067. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10068. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10069. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10070. },
  10071. xsrfCookieName: 'XSRF-TOKEN',
  10072. xsrfHeaderName: 'X-XSRF-TOKEN',
  10073. paramSerializer: '$httpParamSerializer',
  10074. jsonpCallbackParam: 'callback'
  10075. };
  10076. var useApplyAsync = false;
  10077. /**
  10078. * @ngdoc method
  10079. * @name $httpProvider#useApplyAsync
  10080. * @description
  10081. *
  10082. * Configure $http service to combine processing of multiple http responses received at around
  10083. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10084. * significant performance improvement for bigger applications that make many HTTP requests
  10085. * concurrently (common during application bootstrap).
  10086. *
  10087. * Defaults to false. If no value is specified, returns the current configured value.
  10088. *
  10089. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10090. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10091. * to load and share the same digest cycle.
  10092. *
  10093. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10094. * otherwise, returns the current configured value.
  10095. **/
  10096. this.useApplyAsync = function(value) {
  10097. if (isDefined(value)) {
  10098. useApplyAsync = !!value;
  10099. return this;
  10100. }
  10101. return useApplyAsync;
  10102. };
  10103. /**
  10104. * @ngdoc property
  10105. * @name $httpProvider#interceptors
  10106. * @description
  10107. *
  10108. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10109. * pre-processing of request or postprocessing of responses.
  10110. *
  10111. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10112. * array, on request, but reverse order, on response.
  10113. *
  10114. * {@link ng.$http#interceptors Interceptors detailed info}
  10115. **/
  10116. var interceptorFactories = this.interceptors = [];
  10117. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10118. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10119. var defaultCache = $cacheFactory('$http');
  10120. /**
  10121. * Make sure that default param serializer is exposed as a function
  10122. */
  10123. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10124. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10125. /**
  10126. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10127. * The reversal is needed so that we can build up the interception chain around the
  10128. * server request.
  10129. */
  10130. var reversedInterceptors = [];
  10131. forEach(interceptorFactories, function(interceptorFactory) {
  10132. reversedInterceptors.unshift(isString(interceptorFactory)
  10133. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10134. });
  10135. /**
  10136. * @ngdoc service
  10137. * @kind function
  10138. * @name $http
  10139. * @requires ng.$httpBackend
  10140. * @requires $cacheFactory
  10141. * @requires $rootScope
  10142. * @requires $q
  10143. * @requires $injector
  10144. *
  10145. * @description
  10146. * The `$http` service is a core Angular service that facilitates communication with the remote
  10147. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10148. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10149. *
  10150. * For unit testing applications that use `$http` service, see
  10151. * {@link ngMock.$httpBackend $httpBackend mock}.
  10152. *
  10153. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10154. * $resource} service.
  10155. *
  10156. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10157. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10158. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10159. *
  10160. *
  10161. * ## General usage
  10162. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10163. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10164. *
  10165. * ```js
  10166. * // Simple GET request example:
  10167. * $http({
  10168. * method: 'GET',
  10169. * url: '/someUrl'
  10170. * }).then(function successCallback(response) {
  10171. * // this callback will be called asynchronously
  10172. * // when the response is available
  10173. * }, function errorCallback(response) {
  10174. * // called asynchronously if an error occurs
  10175. * // or server returns response with an error status.
  10176. * });
  10177. * ```
  10178. *
  10179. * The response object has these properties:
  10180. *
  10181. * - **data** – `{string|Object}` – The response body transformed with the transform
  10182. * functions.
  10183. * - **status** – `{number}` – HTTP status code of the response.
  10184. * - **headers** – `{function([headerName])}` – Header getter function.
  10185. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10186. * - **statusText** – `{string}` – HTTP status text of the response.
  10187. *
  10188. * A response status code between 200 and 299 is considered a success status and will result in
  10189. * the success callback being called. Any response status code outside of that range is
  10190. * considered an error status and will result in the error callback being called.
  10191. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10192. * aborted, e.g. using a `config.timeout`.
  10193. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10194. * that the outcome (success or error) will be determined by the final response status code.
  10195. *
  10196. *
  10197. * ## Shortcut methods
  10198. *
  10199. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10200. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10201. * last argument.
  10202. *
  10203. * ```js
  10204. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10205. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10206. * ```
  10207. *
  10208. * Complete list of shortcut methods:
  10209. *
  10210. * - {@link ng.$http#get $http.get}
  10211. * - {@link ng.$http#head $http.head}
  10212. * - {@link ng.$http#post $http.post}
  10213. * - {@link ng.$http#put $http.put}
  10214. * - {@link ng.$http#delete $http.delete}
  10215. * - {@link ng.$http#jsonp $http.jsonp}
  10216. * - {@link ng.$http#patch $http.patch}
  10217. *
  10218. *
  10219. * ## Writing Unit Tests that use $http
  10220. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10221. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10222. * request using trained responses.
  10223. *
  10224. * ```
  10225. * $httpBackend.expectGET(...);
  10226. * $http.get(...);
  10227. * $httpBackend.flush();
  10228. * ```
  10229. *
  10230. * ## Setting HTTP Headers
  10231. *
  10232. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10233. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10234. * object, which currently contains this default configuration:
  10235. *
  10236. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10237. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10238. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10239. * - `Content-Type: application/json`
  10240. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10241. * - `Content-Type: application/json`
  10242. *
  10243. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10244. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10245. * with the lowercased HTTP method name as the key, e.g.
  10246. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10247. *
  10248. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10249. * fashion. For example:
  10250. *
  10251. * ```
  10252. * module.run(function($http) {
  10253. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10254. * });
  10255. * ```
  10256. *
  10257. * In addition, you can supply a `headers` property in the config object passed when
  10258. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10259. *
  10260. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10261. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10262. *
  10263. * ```js
  10264. * var req = {
  10265. * method: 'POST',
  10266. * url: 'http://example.com',
  10267. * headers: {
  10268. * 'Content-Type': undefined
  10269. * },
  10270. * data: { test: 'test' }
  10271. * }
  10272. *
  10273. * $http(req).then(function(){...}, function(){...});
  10274. * ```
  10275. *
  10276. * ## Transforming Requests and Responses
  10277. *
  10278. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10279. * and `transformResponse`. These properties can be a single function that returns
  10280. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10281. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10282. *
  10283. * <div class="alert alert-warning">
  10284. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10285. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10286. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10287. * function will be reflected on the scope and in any templates where the object is data-bound.
  10288. * To prevent this, transform functions should have no side-effects.
  10289. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10290. * </div>
  10291. *
  10292. * ### Default Transformations
  10293. *
  10294. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10295. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10296. * then these will be applied.
  10297. *
  10298. * You can augment or replace the default transformations by modifying these properties by adding to or
  10299. * replacing the array.
  10300. *
  10301. * Angular provides the following default transformations:
  10302. *
  10303. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  10304. *
  10305. * - If the `data` property of the request configuration object contains an object, serialize it
  10306. * into JSON format.
  10307. *
  10308. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10309. *
  10310. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10311. * - If JSON response is detected, deserialize it using a JSON parser.
  10312. *
  10313. *
  10314. * ### Overriding the Default Transformations Per Request
  10315. *
  10316. * If you wish to override the request/response transformations only for a single request then provide
  10317. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10318. * into `$http`.
  10319. *
  10320. * Note that if you provide these properties on the config object the default transformations will be
  10321. * overwritten. If you wish to augment the default transformations then you must include them in your
  10322. * local transformation array.
  10323. *
  10324. * The following code demonstrates adding a new response transformation to be run after the default response
  10325. * transformations have been run.
  10326. *
  10327. * ```js
  10328. * function appendTransform(defaults, transform) {
  10329. *
  10330. * // We can't guarantee that the default transformation is an array
  10331. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10332. *
  10333. * // Append the new transformation to the defaults
  10334. * return defaults.concat(transform);
  10335. * }
  10336. *
  10337. * $http({
  10338. * url: '...',
  10339. * method: 'GET',
  10340. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10341. * return doTransform(value);
  10342. * })
  10343. * });
  10344. * ```
  10345. *
  10346. *
  10347. * ## Caching
  10348. *
  10349. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10350. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10351. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10352. * precedence over the default cache value.
  10353. *
  10354. * In order to:
  10355. * * cache all responses - set the default cache value to TRUE or to a cache object
  10356. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10357. *
  10358. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10359. * then the default `$cacheFactory("$http")` object is used.
  10360. *
  10361. * The default cache value can be set by updating the
  10362. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10363. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10364. *
  10365. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10366. * the relevant cache object. The next time the same request is made, the response is returned
  10367. * from the cache without sending a request to the server.
  10368. *
  10369. * Take note that:
  10370. *
  10371. * * Only GET and JSONP requests are cached.
  10372. * * The cache key is the request URL including search parameters; headers are not considered.
  10373. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10374. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10375. * one request will be made to the server and remaining requests will return the same response.
  10376. * * A cache-control header on the response does not affect if or how responses are cached.
  10377. *
  10378. *
  10379. * ## Interceptors
  10380. *
  10381. * Before you start creating interceptors, be sure to understand the
  10382. * {@link ng.$q $q and deferred/promise APIs}.
  10383. *
  10384. * For purposes of global error handling, authentication, or any kind of synchronous or
  10385. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10386. * able to intercept requests before they are handed to the server and
  10387. * responses before they are handed over to the application code that
  10388. * initiated these requests. The interceptors leverage the {@link ng.$q
  10389. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10390. *
  10391. * The interceptors are service factories that are registered with the `$httpProvider` by
  10392. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10393. * injected with dependencies (if specified) and returns the interceptor.
  10394. *
  10395. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10396. *
  10397. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10398. * modify the `config` object or create a new one. The function needs to return the `config`
  10399. * object directly, or a promise containing the `config` or a new `config` object.
  10400. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10401. * resolved with a rejection.
  10402. * * `response`: interceptors get called with http `response` object. The function is free to
  10403. * modify the `response` object or create a new one. The function needs to return the `response`
  10404. * object directly, or as a promise containing the `response` or a new `response` object.
  10405. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10406. * resolved with a rejection.
  10407. *
  10408. *
  10409. * ```js
  10410. * // register the interceptor as a service
  10411. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10412. * return {
  10413. * // optional method
  10414. * 'request': function(config) {
  10415. * // do something on success
  10416. * return config;
  10417. * },
  10418. *
  10419. * // optional method
  10420. * 'requestError': function(rejection) {
  10421. * // do something on error
  10422. * if (canRecover(rejection)) {
  10423. * return responseOrNewPromise
  10424. * }
  10425. * return $q.reject(rejection);
  10426. * },
  10427. *
  10428. *
  10429. *
  10430. * // optional method
  10431. * 'response': function(response) {
  10432. * // do something on success
  10433. * return response;
  10434. * },
  10435. *
  10436. * // optional method
  10437. * 'responseError': function(rejection) {
  10438. * // do something on error
  10439. * if (canRecover(rejection)) {
  10440. * return responseOrNewPromise
  10441. * }
  10442. * return $q.reject(rejection);
  10443. * }
  10444. * };
  10445. * });
  10446. *
  10447. * $httpProvider.interceptors.push('myHttpInterceptor');
  10448. *
  10449. *
  10450. * // alternatively, register the interceptor via an anonymous factory
  10451. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10452. * return {
  10453. * 'request': function(config) {
  10454. * // same as above
  10455. * },
  10456. *
  10457. * 'response': function(response) {
  10458. * // same as above
  10459. * }
  10460. * };
  10461. * });
  10462. * ```
  10463. *
  10464. * ## Security Considerations
  10465. *
  10466. * When designing web applications, consider security threats from:
  10467. *
  10468. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10469. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10470. *
  10471. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10472. * pre-configured with strategies that address these issues, but for this to work backend server
  10473. * cooperation is required.
  10474. *
  10475. * ### JSON Vulnerability Protection
  10476. *
  10477. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10478. * allows third party website to turn your JSON resource URL into
  10479. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10480. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10481. * Angular will automatically strip the prefix before processing it as JSON.
  10482. *
  10483. * For example if your server needs to return:
  10484. * ```js
  10485. * ['one','two']
  10486. * ```
  10487. *
  10488. * which is vulnerable to attack, your server can return:
  10489. * ```js
  10490. * )]}',
  10491. * ['one','two']
  10492. * ```
  10493. *
  10494. * Angular will strip the prefix, before processing the JSON.
  10495. *
  10496. *
  10497. * ### Cross Site Request Forgery (XSRF) Protection
  10498. *
  10499. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10500. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10501. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10502. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10503. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10504. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10505. * The header will not be set for cross-domain requests.
  10506. *
  10507. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10508. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10509. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10510. * that only JavaScript running on your domain could have sent the request. The token must be
  10511. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10512. * making up its own tokens). We recommend that the token is a digest of your site's
  10513. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10514. * for added security.
  10515. *
  10516. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10517. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10518. * or the per-request config object.
  10519. *
  10520. * In order to prevent collisions in environments where multiple Angular apps share the
  10521. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10522. *
  10523. * @param {object} config Object describing the request to be made and how it should be
  10524. * processed. The object has following properties:
  10525. *
  10526. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10527. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10528. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10529. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10530. * with the `paramSerializer` and appended as GET parameters.
  10531. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10532. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10533. * HTTP headers to send to the server. If the return value of a function is null, the
  10534. * header will not be sent. Functions accept a config object as an argument.
  10535. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10536. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10537. * The handler will be called in the context of a `$apply` block.
  10538. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10539. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10540. * The handler will be called in the context of a `$apply` block.
  10541. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10542. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10543. * - **transformRequest** –
  10544. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10545. * transform function or an array of such functions. The transform function takes the http
  10546. * request body and headers and returns its transformed (typically serialized) version.
  10547. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10548. * Overriding the Default Transformations}
  10549. * - **transformResponse** –
  10550. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10551. * transform function or an array of such functions. The transform function takes the http
  10552. * response body, headers and status and returns its transformed (typically deserialized) version.
  10553. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10554. * Overriding the Default Transformations}
  10555. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10556. * prepare the string representation of request parameters (specified as an object).
  10557. * If specified as string, it is interpreted as function registered with the
  10558. * {@link $injector $injector}, which means you can create your own serializer
  10559. * by registering it as a {@link auto.$provide#service service}.
  10560. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10561. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10562. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10563. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10564. * See {@link $http#caching $http Caching} for more information.
  10565. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10566. * that should abort the request when resolved.
  10567. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10568. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10569. * for more information.
  10570. * - **responseType** - `{string}` - see
  10571. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10572. *
  10573. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10574. * when the request succeeds or fails.
  10575. *
  10576. *
  10577. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10578. * requests. This is primarily meant to be used for debugging purposes.
  10579. *
  10580. *
  10581. * @example
  10582. <example module="httpExample" name="http-service">
  10583. <file name="index.html">
  10584. <div ng-controller="FetchController">
  10585. <select ng-model="method" aria-label="Request method">
  10586. <option>GET</option>
  10587. <option>JSONP</option>
  10588. </select>
  10589. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10590. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10591. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10592. <button id="samplejsonpbtn"
  10593. ng-click="updateModel('JSONP',
  10594. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10595. Sample JSONP
  10596. </button>
  10597. <button id="invalidjsonpbtn"
  10598. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10599. Invalid JSONP
  10600. </button>
  10601. <pre>http status code: {{status}}</pre>
  10602. <pre>http response data: {{data}}</pre>
  10603. </div>
  10604. </file>
  10605. <file name="script.js">
  10606. angular.module('httpExample', [])
  10607. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10608. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10609. $sceDelegateProvider.resourceUrlWhitelist([
  10610. 'self',
  10611. 'https://angularjs.org/**'
  10612. ]);
  10613. }])
  10614. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10615. function($scope, $http, $templateCache) {
  10616. $scope.method = 'GET';
  10617. $scope.url = 'http-hello.html';
  10618. $scope.fetch = function() {
  10619. $scope.code = null;
  10620. $scope.response = null;
  10621. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10622. then(function(response) {
  10623. $scope.status = response.status;
  10624. $scope.data = response.data;
  10625. }, function(response) {
  10626. $scope.data = response.data || 'Request failed';
  10627. $scope.status = response.status;
  10628. });
  10629. };
  10630. $scope.updateModel = function(method, url) {
  10631. $scope.method = method;
  10632. $scope.url = url;
  10633. };
  10634. }]);
  10635. </file>
  10636. <file name="http-hello.html">
  10637. Hello, $http!
  10638. </file>
  10639. <file name="protractor.js" type="protractor">
  10640. var status = element(by.binding('status'));
  10641. var data = element(by.binding('data'));
  10642. var fetchBtn = element(by.id('fetchbtn'));
  10643. var sampleGetBtn = element(by.id('samplegetbtn'));
  10644. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10645. it('should make an xhr GET request', function() {
  10646. sampleGetBtn.click();
  10647. fetchBtn.click();
  10648. expect(status.getText()).toMatch('200');
  10649. expect(data.getText()).toMatch(/Hello, \$http!/);
  10650. });
  10651. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10652. // it('should make a JSONP request to angularjs.org', function() {
  10653. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10654. // sampleJsonpBtn.click();
  10655. // fetchBtn.click();
  10656. // expect(status.getText()).toMatch('200');
  10657. // expect(data.getText()).toMatch(/Super Hero!/);
  10658. // });
  10659. it('should make JSONP request to invalid URL and invoke the error handler',
  10660. function() {
  10661. invalidJsonpBtn.click();
  10662. fetchBtn.click();
  10663. expect(status.getText()).toMatch('0');
  10664. expect(data.getText()).toMatch('Request failed');
  10665. });
  10666. </file>
  10667. </example>
  10668. */
  10669. function $http(requestConfig) {
  10670. if (!isObject(requestConfig)) {
  10671. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10672. }
  10673. if (!isString($sce.valueOf(requestConfig.url))) {
  10674. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  10675. }
  10676. var config = extend({
  10677. method: 'get',
  10678. transformRequest: defaults.transformRequest,
  10679. transformResponse: defaults.transformResponse,
  10680. paramSerializer: defaults.paramSerializer,
  10681. jsonpCallbackParam: defaults.jsonpCallbackParam
  10682. }, requestConfig);
  10683. config.headers = mergeHeaders(requestConfig);
  10684. config.method = uppercase(config.method);
  10685. config.paramSerializer = isString(config.paramSerializer) ?
  10686. $injector.get(config.paramSerializer) : config.paramSerializer;
  10687. $browser.$$incOutstandingRequestCount();
  10688. var requestInterceptors = [];
  10689. var responseInterceptors = [];
  10690. var promise = $q.resolve(config);
  10691. // apply interceptors
  10692. forEach(reversedInterceptors, function(interceptor) {
  10693. if (interceptor.request || interceptor.requestError) {
  10694. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10695. }
  10696. if (interceptor.response || interceptor.responseError) {
  10697. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10698. }
  10699. });
  10700. promise = chainInterceptors(promise, requestInterceptors);
  10701. promise = promise.then(serverRequest);
  10702. promise = chainInterceptors(promise, responseInterceptors);
  10703. promise = promise.finally(completeOutstandingRequest);
  10704. return promise;
  10705. function chainInterceptors(promise, interceptors) {
  10706. for (var i = 0, ii = interceptors.length; i < ii;) {
  10707. var thenFn = interceptors[i++];
  10708. var rejectFn = interceptors[i++];
  10709. promise = promise.then(thenFn, rejectFn);
  10710. }
  10711. interceptors.length = 0;
  10712. return promise;
  10713. }
  10714. function completeOutstandingRequest() {
  10715. $browser.$$completeOutstandingRequest(noop);
  10716. }
  10717. function executeHeaderFns(headers, config) {
  10718. var headerContent, processedHeaders = {};
  10719. forEach(headers, function(headerFn, header) {
  10720. if (isFunction(headerFn)) {
  10721. headerContent = headerFn(config);
  10722. if (headerContent != null) {
  10723. processedHeaders[header] = headerContent;
  10724. }
  10725. } else {
  10726. processedHeaders[header] = headerFn;
  10727. }
  10728. });
  10729. return processedHeaders;
  10730. }
  10731. function mergeHeaders(config) {
  10732. var defHeaders = defaults.headers,
  10733. reqHeaders = extend({}, config.headers),
  10734. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10735. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10736. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10737. defaultHeadersIteration:
  10738. for (defHeaderName in defHeaders) {
  10739. lowercaseDefHeaderName = lowercase(defHeaderName);
  10740. for (reqHeaderName in reqHeaders) {
  10741. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10742. continue defaultHeadersIteration;
  10743. }
  10744. }
  10745. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10746. }
  10747. // execute if header value is a function for merged headers
  10748. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10749. }
  10750. function serverRequest(config) {
  10751. var headers = config.headers;
  10752. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10753. // strip content-type if data is undefined
  10754. if (isUndefined(reqData)) {
  10755. forEach(headers, function(value, header) {
  10756. if (lowercase(header) === 'content-type') {
  10757. delete headers[header];
  10758. }
  10759. });
  10760. }
  10761. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10762. config.withCredentials = defaults.withCredentials;
  10763. }
  10764. // send request
  10765. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10766. }
  10767. function transformResponse(response) {
  10768. // make a copy since the response must be cacheable
  10769. var resp = extend({}, response);
  10770. resp.data = transformData(response.data, response.headers, response.status,
  10771. config.transformResponse);
  10772. return (isSuccess(response.status))
  10773. ? resp
  10774. : $q.reject(resp);
  10775. }
  10776. }
  10777. $http.pendingRequests = [];
  10778. /**
  10779. * @ngdoc method
  10780. * @name $http#get
  10781. *
  10782. * @description
  10783. * Shortcut method to perform `GET` request.
  10784. *
  10785. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10786. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10787. * @param {Object=} config Optional configuration object
  10788. * @returns {HttpPromise} Future object
  10789. */
  10790. /**
  10791. * @ngdoc method
  10792. * @name $http#delete
  10793. *
  10794. * @description
  10795. * Shortcut method to perform `DELETE` request.
  10796. *
  10797. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10798. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10799. * @param {Object=} config Optional configuration object
  10800. * @returns {HttpPromise} Future object
  10801. */
  10802. /**
  10803. * @ngdoc method
  10804. * @name $http#head
  10805. *
  10806. * @description
  10807. * Shortcut method to perform `HEAD` request.
  10808. *
  10809. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10810. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10811. * @param {Object=} config Optional configuration object
  10812. * @returns {HttpPromise} Future object
  10813. */
  10814. /**
  10815. * @ngdoc method
  10816. * @name $http#jsonp
  10817. *
  10818. * @description
  10819. * Shortcut method to perform `JSONP` request.
  10820. *
  10821. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  10822. * the url must be declared, via {@link $sce} as a trusted resource URL.
  10823. * You can trust a URL by adding it to the whitelist via
  10824. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  10825. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  10826. *
  10827. * JSONP requests must specify a callback to be used in the response from the server. This callback
  10828. * is passed as a query parameter in the request. You must specify the name of this parameter by
  10829. * setting the `jsonpCallbackParam` property on the request config object.
  10830. *
  10831. * ```
  10832. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  10833. * ```
  10834. *
  10835. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  10836. * Initially this is set to `'callback'`.
  10837. *
  10838. * <div class="alert alert-danger">
  10839. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  10840. * parameter value should go.
  10841. * </div>
  10842. *
  10843. * If you would like to customise where and how the callbacks are stored then try overriding
  10844. * or decorating the {@link $jsonpCallbacks} service.
  10845. *
  10846. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10847. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10848. * @param {Object=} config Optional configuration object
  10849. * @returns {HttpPromise} Future object
  10850. */
  10851. createShortMethods('get', 'delete', 'head', 'jsonp');
  10852. /**
  10853. * @ngdoc method
  10854. * @name $http#post
  10855. *
  10856. * @description
  10857. * Shortcut method to perform `POST` request.
  10858. *
  10859. * @param {string} url Relative or absolute URL specifying the destination of the request
  10860. * @param {*} data Request content
  10861. * @param {Object=} config Optional configuration object
  10862. * @returns {HttpPromise} Future object
  10863. */
  10864. /**
  10865. * @ngdoc method
  10866. * @name $http#put
  10867. *
  10868. * @description
  10869. * Shortcut method to perform `PUT` request.
  10870. *
  10871. * @param {string} url Relative or absolute URL specifying the destination of the request
  10872. * @param {*} data Request content
  10873. * @param {Object=} config Optional configuration object
  10874. * @returns {HttpPromise} Future object
  10875. */
  10876. /**
  10877. * @ngdoc method
  10878. * @name $http#patch
  10879. *
  10880. * @description
  10881. * Shortcut method to perform `PATCH` request.
  10882. *
  10883. * @param {string} url Relative or absolute URL specifying the destination of the request
  10884. * @param {*} data Request content
  10885. * @param {Object=} config Optional configuration object
  10886. * @returns {HttpPromise} Future object
  10887. */
  10888. createShortMethodsWithData('post', 'put', 'patch');
  10889. /**
  10890. * @ngdoc property
  10891. * @name $http#defaults
  10892. *
  10893. * @description
  10894. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10895. * default headers, withCredentials as well as request and response transformations.
  10896. *
  10897. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10898. */
  10899. $http.defaults = defaults;
  10900. return $http;
  10901. function createShortMethods(names) {
  10902. forEach(arguments, function(name) {
  10903. $http[name] = function(url, config) {
  10904. return $http(extend({}, config || {}, {
  10905. method: name,
  10906. url: url
  10907. }));
  10908. };
  10909. });
  10910. }
  10911. function createShortMethodsWithData(name) {
  10912. forEach(arguments, function(name) {
  10913. $http[name] = function(url, data, config) {
  10914. return $http(extend({}, config || {}, {
  10915. method: name,
  10916. url: url,
  10917. data: data
  10918. }));
  10919. };
  10920. });
  10921. }
  10922. /**
  10923. * Makes the request.
  10924. *
  10925. * !!! ACCESSES CLOSURE VARS:
  10926. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10927. */
  10928. function sendReq(config, reqData) {
  10929. var deferred = $q.defer(),
  10930. promise = deferred.promise,
  10931. cache,
  10932. cachedResp,
  10933. reqHeaders = config.headers,
  10934. isJsonp = lowercase(config.method) === 'jsonp',
  10935. url = config.url;
  10936. if (isJsonp) {
  10937. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  10938. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  10939. url = $sce.getTrustedResourceUrl(url);
  10940. } else if (!isString(url)) {
  10941. // If it is not a string then the URL must be a $sce trusted object
  10942. url = $sce.valueOf(url);
  10943. }
  10944. url = buildUrl(url, config.paramSerializer(config.params));
  10945. if (isJsonp) {
  10946. // Check the url and add the JSONP callback placeholder
  10947. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  10948. }
  10949. $http.pendingRequests.push(config);
  10950. promise.then(removePendingReq, removePendingReq);
  10951. if ((config.cache || defaults.cache) && config.cache !== false &&
  10952. (config.method === 'GET' || config.method === 'JSONP')) {
  10953. cache = isObject(config.cache) ? config.cache
  10954. : isObject(defaults.cache) ? defaults.cache
  10955. : defaultCache;
  10956. }
  10957. if (cache) {
  10958. cachedResp = cache.get(url);
  10959. if (isDefined(cachedResp)) {
  10960. if (isPromiseLike(cachedResp)) {
  10961. // cached request has already been sent, but there is no response yet
  10962. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10963. } else {
  10964. // serving from cache
  10965. if (isArray(cachedResp)) {
  10966. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10967. } else {
  10968. resolvePromise(cachedResp, 200, {}, 'OK');
  10969. }
  10970. }
  10971. } else {
  10972. // put the promise for the non-transformed response into cache as a placeholder
  10973. cache.put(url, promise);
  10974. }
  10975. }
  10976. // if we won't have the response in cache, set the xsrf headers and
  10977. // send the request to the backend
  10978. if (isUndefined(cachedResp)) {
  10979. var xsrfValue = urlIsSameOrigin(config.url)
  10980. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10981. : undefined;
  10982. if (xsrfValue) {
  10983. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10984. }
  10985. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10986. config.withCredentials, config.responseType,
  10987. createApplyHandlers(config.eventHandlers),
  10988. createApplyHandlers(config.uploadEventHandlers));
  10989. }
  10990. return promise;
  10991. function createApplyHandlers(eventHandlers) {
  10992. if (eventHandlers) {
  10993. var applyHandlers = {};
  10994. forEach(eventHandlers, function(eventHandler, key) {
  10995. applyHandlers[key] = function(event) {
  10996. if (useApplyAsync) {
  10997. $rootScope.$applyAsync(callEventHandler);
  10998. } else if ($rootScope.$$phase) {
  10999. callEventHandler();
  11000. } else {
  11001. $rootScope.$apply(callEventHandler);
  11002. }
  11003. function callEventHandler() {
  11004. eventHandler(event);
  11005. }
  11006. };
  11007. });
  11008. return applyHandlers;
  11009. }
  11010. }
  11011. /**
  11012. * Callback registered to $httpBackend():
  11013. * - caches the response if desired
  11014. * - resolves the raw $http promise
  11015. * - calls $apply
  11016. */
  11017. function done(status, response, headersString, statusText) {
  11018. if (cache) {
  11019. if (isSuccess(status)) {
  11020. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  11021. } else {
  11022. // remove promise from the cache
  11023. cache.remove(url);
  11024. }
  11025. }
  11026. function resolveHttpPromise() {
  11027. resolvePromise(response, status, headersString, statusText);
  11028. }
  11029. if (useApplyAsync) {
  11030. $rootScope.$applyAsync(resolveHttpPromise);
  11031. } else {
  11032. resolveHttpPromise();
  11033. if (!$rootScope.$$phase) $rootScope.$apply();
  11034. }
  11035. }
  11036. /**
  11037. * Resolves the raw $http promise.
  11038. */
  11039. function resolvePromise(response, status, headers, statusText) {
  11040. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11041. status = status >= -1 ? status : 0;
  11042. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11043. data: response,
  11044. status: status,
  11045. headers: headersGetter(headers),
  11046. config: config,
  11047. statusText: statusText
  11048. });
  11049. }
  11050. function resolvePromiseWithResult(result) {
  11051. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  11052. }
  11053. function removePendingReq() {
  11054. var idx = $http.pendingRequests.indexOf(config);
  11055. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11056. }
  11057. }
  11058. function buildUrl(url, serializedParams) {
  11059. if (serializedParams.length > 0) {
  11060. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11061. }
  11062. return url;
  11063. }
  11064. function sanitizeJsonpCallbackParam(url, key) {
  11065. if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
  11066. // Throw if the url already contains a reference to JSON_CALLBACK
  11067. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11068. }
  11069. var callbackParamRegex = new RegExp('[&?]' + key + '=');
  11070. if (callbackParamRegex.test(url)) {
  11071. // Throw if the callback param was already provided
  11072. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
  11073. }
  11074. // Add in the JSON_CALLBACK callback param value
  11075. url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
  11076. return url;
  11077. }
  11078. }];
  11079. }
  11080. /**
  11081. * @ngdoc service
  11082. * @name $xhrFactory
  11083. * @this
  11084. *
  11085. * @description
  11086. * Factory function used to create XMLHttpRequest objects.
  11087. *
  11088. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11089. *
  11090. * ```
  11091. * angular.module('myApp', [])
  11092. * .factory('$xhrFactory', function() {
  11093. * return function createXhr(method, url) {
  11094. * return new window.XMLHttpRequest({mozSystem: true});
  11095. * };
  11096. * });
  11097. * ```
  11098. *
  11099. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11100. * @param {string} url URL of the request.
  11101. */
  11102. function $xhrFactoryProvider() {
  11103. this.$get = function() {
  11104. return function createXhr() {
  11105. return new window.XMLHttpRequest();
  11106. };
  11107. };
  11108. }
  11109. /**
  11110. * @ngdoc service
  11111. * @name $httpBackend
  11112. * @requires $jsonpCallbacks
  11113. * @requires $document
  11114. * @requires $xhrFactory
  11115. * @this
  11116. *
  11117. * @description
  11118. * HTTP backend used by the {@link ng.$http service} that delegates to
  11119. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11120. *
  11121. * You should never need to use this service directly, instead use the higher-level abstractions:
  11122. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11123. *
  11124. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11125. * $httpBackend} which can be trained with responses.
  11126. */
  11127. function $HttpBackendProvider() {
  11128. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11129. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11130. }];
  11131. }
  11132. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11133. // TODO(vojta): fix the signature
  11134. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11135. url = url || $browser.url();
  11136. if (lowercase(method) === 'jsonp') {
  11137. var callbackPath = callbacks.createCallback(url);
  11138. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11139. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11140. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11141. completeRequest(callback, status, response, '', text);
  11142. callbacks.removeCallback(callbackPath);
  11143. });
  11144. } else {
  11145. var xhr = createXhr(method, url);
  11146. xhr.open(method, url, true);
  11147. forEach(headers, function(value, key) {
  11148. if (isDefined(value)) {
  11149. xhr.setRequestHeader(key, value);
  11150. }
  11151. });
  11152. xhr.onload = function requestLoaded() {
  11153. var statusText = xhr.statusText || '';
  11154. // responseText is the old-school way of retrieving response (supported by IE9)
  11155. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11156. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11157. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11158. var status = xhr.status === 1223 ? 204 : xhr.status;
  11159. // fix status code when it is 0 (0 status is undocumented).
  11160. // Occurs when accessing file resources or on Android 4.1 stock browser
  11161. // while retrieving files from application cache.
  11162. if (status === 0) {
  11163. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11164. }
  11165. completeRequest(callback,
  11166. status,
  11167. response,
  11168. xhr.getAllResponseHeaders(),
  11169. statusText);
  11170. };
  11171. var requestError = function() {
  11172. // The response is always empty
  11173. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11174. completeRequest(callback, -1, null, null, '');
  11175. };
  11176. xhr.onerror = requestError;
  11177. xhr.onabort = requestError;
  11178. xhr.ontimeout = requestError;
  11179. forEach(eventHandlers, function(value, key) {
  11180. xhr.addEventListener(key, value);
  11181. });
  11182. forEach(uploadEventHandlers, function(value, key) {
  11183. xhr.upload.addEventListener(key, value);
  11184. });
  11185. if (withCredentials) {
  11186. xhr.withCredentials = true;
  11187. }
  11188. if (responseType) {
  11189. try {
  11190. xhr.responseType = responseType;
  11191. } catch (e) {
  11192. // WebKit added support for the json responseType value on 09/03/2013
  11193. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11194. // known to throw when setting the value "json" as the response type. Other older
  11195. // browsers implementing the responseType
  11196. //
  11197. // The json response type can be ignored if not supported, because JSON payloads are
  11198. // parsed on the client-side regardless.
  11199. if (responseType !== 'json') {
  11200. throw e;
  11201. }
  11202. }
  11203. }
  11204. xhr.send(isUndefined(post) ? null : post);
  11205. }
  11206. if (timeout > 0) {
  11207. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11208. } else if (isPromiseLike(timeout)) {
  11209. timeout.then(timeoutRequest);
  11210. }
  11211. function timeoutRequest() {
  11212. if (jsonpDone) {
  11213. jsonpDone();
  11214. }
  11215. if (xhr) {
  11216. xhr.abort();
  11217. }
  11218. }
  11219. function completeRequest(callback, status, response, headersString, statusText) {
  11220. // cancel timeout and subsequent timeout promise resolution
  11221. if (isDefined(timeoutId)) {
  11222. $browserDefer.cancel(timeoutId);
  11223. }
  11224. jsonpDone = xhr = null;
  11225. callback(status, response, headersString, statusText);
  11226. }
  11227. };
  11228. function jsonpReq(url, callbackPath, done) {
  11229. url = url.replace('JSON_CALLBACK', callbackPath);
  11230. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11231. // - fetches local scripts via XHR and evals them
  11232. // - adds and immediately removes script elements from the document
  11233. var script = rawDocument.createElement('script'), callback = null;
  11234. script.type = 'text/javascript';
  11235. script.src = url;
  11236. script.async = true;
  11237. callback = function(event) {
  11238. script.removeEventListener('load', callback);
  11239. script.removeEventListener('error', callback);
  11240. rawDocument.body.removeChild(script);
  11241. script = null;
  11242. var status = -1;
  11243. var text = 'unknown';
  11244. if (event) {
  11245. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11246. event = { type: 'error' };
  11247. }
  11248. text = event.type;
  11249. status = event.type === 'error' ? 404 : 200;
  11250. }
  11251. if (done) {
  11252. done(status, text);
  11253. }
  11254. };
  11255. script.addEventListener('load', callback);
  11256. script.addEventListener('error', callback);
  11257. rawDocument.body.appendChild(script);
  11258. return callback;
  11259. }
  11260. }
  11261. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11262. $interpolateMinErr.throwNoconcat = function(text) {
  11263. throw $interpolateMinErr('noconcat',
  11264. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11265. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11266. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11267. };
  11268. $interpolateMinErr.interr = function(text, err) {
  11269. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11270. };
  11271. /**
  11272. * @ngdoc provider
  11273. * @name $interpolateProvider
  11274. * @this
  11275. *
  11276. * @description
  11277. *
  11278. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11279. *
  11280. * <div class="alert alert-danger">
  11281. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11282. * template within a Python Jinja template (or any other template language). Mixing templating
  11283. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11284. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11285. * security bugs!
  11286. * </div>
  11287. *
  11288. * @example
  11289. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11290. <file name="index.html">
  11291. <script>
  11292. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11293. customInterpolationApp.config(function($interpolateProvider) {
  11294. $interpolateProvider.startSymbol('//');
  11295. $interpolateProvider.endSymbol('//');
  11296. });
  11297. customInterpolationApp.controller('DemoController', function() {
  11298. this.label = "This binding is brought you by // interpolation symbols.";
  11299. });
  11300. </script>
  11301. <div ng-controller="DemoController as demo">
  11302. //demo.label//
  11303. </div>
  11304. </file>
  11305. <file name="protractor.js" type="protractor">
  11306. it('should interpolate binding with custom symbols', function() {
  11307. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11308. });
  11309. </file>
  11310. </example>
  11311. */
  11312. function $InterpolateProvider() {
  11313. var startSymbol = '{{';
  11314. var endSymbol = '}}';
  11315. /**
  11316. * @ngdoc method
  11317. * @name $interpolateProvider#startSymbol
  11318. * @description
  11319. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11320. *
  11321. * @param {string=} value new value to set the starting symbol to.
  11322. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11323. */
  11324. this.startSymbol = function(value) {
  11325. if (value) {
  11326. startSymbol = value;
  11327. return this;
  11328. } else {
  11329. return startSymbol;
  11330. }
  11331. };
  11332. /**
  11333. * @ngdoc method
  11334. * @name $interpolateProvider#endSymbol
  11335. * @description
  11336. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11337. *
  11338. * @param {string=} value new value to set the ending symbol to.
  11339. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11340. */
  11341. this.endSymbol = function(value) {
  11342. if (value) {
  11343. endSymbol = value;
  11344. return this;
  11345. } else {
  11346. return endSymbol;
  11347. }
  11348. };
  11349. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11350. var startSymbolLength = startSymbol.length,
  11351. endSymbolLength = endSymbol.length,
  11352. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11353. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11354. function escape(ch) {
  11355. return '\\\\\\' + ch;
  11356. }
  11357. function unescapeText(text) {
  11358. return text.replace(escapedStartRegexp, startSymbol).
  11359. replace(escapedEndRegexp, endSymbol);
  11360. }
  11361. // TODO: this is the same as the constantWatchDelegate in parse.js
  11362. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11363. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11364. unwatch();
  11365. return constantInterp(scope);
  11366. }, listener, objectEquality);
  11367. return unwatch;
  11368. }
  11369. /**
  11370. * @ngdoc service
  11371. * @name $interpolate
  11372. * @kind function
  11373. *
  11374. * @requires $parse
  11375. * @requires $sce
  11376. *
  11377. * @description
  11378. *
  11379. * Compiles a string with markup into an interpolation function. This service is used by the
  11380. * HTML {@link ng.$compile $compile} service for data binding. See
  11381. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11382. * interpolation markup.
  11383. *
  11384. *
  11385. * ```js
  11386. * var $interpolate = ...; // injected
  11387. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11388. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11389. * ```
  11390. *
  11391. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11392. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11393. * evaluate to a value other than `undefined`.
  11394. *
  11395. * ```js
  11396. * var $interpolate = ...; // injected
  11397. * var context = {greeting: 'Hello', name: undefined };
  11398. *
  11399. * // default "forgiving" mode
  11400. * var exp = $interpolate('{{greeting}} {{name}}!');
  11401. * expect(exp(context)).toEqual('Hello !');
  11402. *
  11403. * // "allOrNothing" mode
  11404. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11405. * expect(exp(context)).toBeUndefined();
  11406. * context.name = 'Angular';
  11407. * expect(exp(context)).toEqual('Hello Angular!');
  11408. * ```
  11409. *
  11410. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11411. *
  11412. * #### Escaped Interpolation
  11413. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11414. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11415. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11416. * or binding.
  11417. *
  11418. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11419. * degree, while also enabling code examples to work without relying on the
  11420. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11421. *
  11422. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11423. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11424. * interpolation start/end markers with their escaped counterparts.**
  11425. *
  11426. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11427. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11428. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11429. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11430. * this is typically useful only when user-data is used in rendering a template from the server, or
  11431. * when otherwise untrusted data is used by a directive.
  11432. *
  11433. * <example name="interpolation">
  11434. * <file name="index.html">
  11435. * <div ng-init="username='A user'">
  11436. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11437. * </p>
  11438. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11439. * application, but fails to accomplish their task, because the server has correctly
  11440. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11441. * characters.</p>
  11442. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11443. * from the database by an administrator.</p>
  11444. * </div>
  11445. * </file>
  11446. * </example>
  11447. *
  11448. * @knownIssue
  11449. * It is currently not possible for an interpolated expression to contain the interpolation end
  11450. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11451. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11452. *
  11453. * @knownIssue
  11454. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11455. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11456. * service will attempt to denormalize the standard symbols to the custom symbols.
  11457. * The denormalization process is not clever enough to know not to replace instances of the standard
  11458. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11459. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11460. *
  11461. * ```
  11462. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11463. * ```
  11464. *
  11465. * The workaround is to ensure that such instances are separated by whitespace:
  11466. * ```
  11467. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11468. * ```
  11469. *
  11470. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11471. *
  11472. * @param {string} text The text with markup to interpolate.
  11473. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11474. * embedded expression in order to return an interpolation function. Strings with no
  11475. * embedded expression will return null for the interpolation function.
  11476. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11477. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11478. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11479. * provides Strict Contextual Escaping for details.
  11480. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11481. * unless all embedded expressions evaluate to a value other than `undefined`.
  11482. * @returns {function(context)} an interpolation function which is used to compute the
  11483. * interpolated string. The function has these parameters:
  11484. *
  11485. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11486. */
  11487. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11488. // Provide a quick exit and simplified result function for text with no interpolation
  11489. if (!text.length || text.indexOf(startSymbol) === -1) {
  11490. var constantInterp;
  11491. if (!mustHaveExpression) {
  11492. var unescapedText = unescapeText(text);
  11493. constantInterp = valueFn(unescapedText);
  11494. constantInterp.exp = text;
  11495. constantInterp.expressions = [];
  11496. constantInterp.$$watchDelegate = constantWatchDelegate;
  11497. }
  11498. return constantInterp;
  11499. }
  11500. allOrNothing = !!allOrNothing;
  11501. var startIndex,
  11502. endIndex,
  11503. index = 0,
  11504. expressions = [],
  11505. parseFns = [],
  11506. textLength = text.length,
  11507. exp,
  11508. concat = [],
  11509. expressionPositions = [];
  11510. while (index < textLength) {
  11511. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11512. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11513. if (index !== startIndex) {
  11514. concat.push(unescapeText(text.substring(index, startIndex)));
  11515. }
  11516. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11517. expressions.push(exp);
  11518. parseFns.push($parse(exp, parseStringifyInterceptor));
  11519. index = endIndex + endSymbolLength;
  11520. expressionPositions.push(concat.length);
  11521. concat.push('');
  11522. } else {
  11523. // we did not find an interpolation, so we have to add the remainder to the separators array
  11524. if (index !== textLength) {
  11525. concat.push(unescapeText(text.substring(index)));
  11526. }
  11527. break;
  11528. }
  11529. }
  11530. // Concatenating expressions makes it hard to reason about whether some combination of
  11531. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11532. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11533. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11534. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11535. // the load when auditing for XSS issues.
  11536. if (trustedContext && concat.length > 1) {
  11537. $interpolateMinErr.throwNoconcat(text);
  11538. }
  11539. if (!mustHaveExpression || expressions.length) {
  11540. var compute = function(values) {
  11541. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11542. if (allOrNothing && isUndefined(values[i])) return;
  11543. concat[expressionPositions[i]] = values[i];
  11544. }
  11545. return concat.join('');
  11546. };
  11547. var getValue = function(value) {
  11548. return trustedContext ?
  11549. $sce.getTrusted(trustedContext, value) :
  11550. $sce.valueOf(value);
  11551. };
  11552. return extend(function interpolationFn(context) {
  11553. var i = 0;
  11554. var ii = expressions.length;
  11555. var values = new Array(ii);
  11556. try {
  11557. for (; i < ii; i++) {
  11558. values[i] = parseFns[i](context);
  11559. }
  11560. return compute(values);
  11561. } catch (err) {
  11562. $exceptionHandler($interpolateMinErr.interr(text, err));
  11563. }
  11564. }, {
  11565. // all of these properties are undocumented for now
  11566. exp: text, //just for compatibility with regular watchers created via $watch
  11567. expressions: expressions,
  11568. $$watchDelegate: function(scope, listener) {
  11569. var lastValue;
  11570. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11571. var currValue = compute(values);
  11572. if (isFunction(listener)) {
  11573. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11574. }
  11575. lastValue = currValue;
  11576. });
  11577. }
  11578. });
  11579. }
  11580. function parseStringifyInterceptor(value) {
  11581. try {
  11582. value = getValue(value);
  11583. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11584. } catch (err) {
  11585. $exceptionHandler($interpolateMinErr.interr(text, err));
  11586. }
  11587. }
  11588. }
  11589. /**
  11590. * @ngdoc method
  11591. * @name $interpolate#startSymbol
  11592. * @description
  11593. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11594. *
  11595. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11596. * the symbol.
  11597. *
  11598. * @returns {string} start symbol.
  11599. */
  11600. $interpolate.startSymbol = function() {
  11601. return startSymbol;
  11602. };
  11603. /**
  11604. * @ngdoc method
  11605. * @name $interpolate#endSymbol
  11606. * @description
  11607. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11608. *
  11609. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11610. * the symbol.
  11611. *
  11612. * @returns {string} end symbol.
  11613. */
  11614. $interpolate.endSymbol = function() {
  11615. return endSymbol;
  11616. };
  11617. return $interpolate;
  11618. }];
  11619. }
  11620. /** @this */
  11621. function $IntervalProvider() {
  11622. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11623. function($rootScope, $window, $q, $$q, $browser) {
  11624. var intervals = {};
  11625. /**
  11626. * @ngdoc service
  11627. * @name $interval
  11628. *
  11629. * @description
  11630. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11631. * milliseconds.
  11632. *
  11633. * The return value of registering an interval function is a promise. This promise will be
  11634. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11635. * run indefinitely if `count` is not defined. The value of the notification will be the
  11636. * number of iterations that have run.
  11637. * To cancel an interval, call `$interval.cancel(promise)`.
  11638. *
  11639. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11640. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11641. * time.
  11642. *
  11643. * <div class="alert alert-warning">
  11644. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11645. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11646. * directive's element are destroyed.
  11647. * You should take this into consideration and make sure to always cancel the interval at the
  11648. * appropriate moment. See the example below for more details on how and when to do this.
  11649. * </div>
  11650. *
  11651. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  11652. * are passed (see below), the function is called with the current iteration count.
  11653. * @param {number} delay Number of milliseconds between each function call.
  11654. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11655. * indefinitely.
  11656. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11657. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11658. * @param {...*=} Pass additional parameters to the executed function.
  11659. * @returns {promise} A promise which will be notified on each iteration.
  11660. *
  11661. * @example
  11662. * <example module="intervalExample" name="interval-service">
  11663. * <file name="index.html">
  11664. * <script>
  11665. * angular.module('intervalExample', [])
  11666. * .controller('ExampleController', ['$scope', '$interval',
  11667. * function($scope, $interval) {
  11668. * $scope.format = 'M/d/yy h:mm:ss a';
  11669. * $scope.blood_1 = 100;
  11670. * $scope.blood_2 = 120;
  11671. *
  11672. * var stop;
  11673. * $scope.fight = function() {
  11674. * // Don't start a new fight if we are already fighting
  11675. * if ( angular.isDefined(stop) ) return;
  11676. *
  11677. * stop = $interval(function() {
  11678. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11679. * $scope.blood_1 = $scope.blood_1 - 3;
  11680. * $scope.blood_2 = $scope.blood_2 - 4;
  11681. * } else {
  11682. * $scope.stopFight();
  11683. * }
  11684. * }, 100);
  11685. * };
  11686. *
  11687. * $scope.stopFight = function() {
  11688. * if (angular.isDefined(stop)) {
  11689. * $interval.cancel(stop);
  11690. * stop = undefined;
  11691. * }
  11692. * };
  11693. *
  11694. * $scope.resetFight = function() {
  11695. * $scope.blood_1 = 100;
  11696. * $scope.blood_2 = 120;
  11697. * };
  11698. *
  11699. * $scope.$on('$destroy', function() {
  11700. * // Make sure that the interval is destroyed too
  11701. * $scope.stopFight();
  11702. * });
  11703. * }])
  11704. * // Register the 'myCurrentTime' directive factory method.
  11705. * // We inject $interval and dateFilter service since the factory method is DI.
  11706. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11707. * function($interval, dateFilter) {
  11708. * // return the directive link function. (compile function not needed)
  11709. * return function(scope, element, attrs) {
  11710. * var format, // date format
  11711. * stopTime; // so that we can cancel the time updates
  11712. *
  11713. * // used to update the UI
  11714. * function updateTime() {
  11715. * element.text(dateFilter(new Date(), format));
  11716. * }
  11717. *
  11718. * // watch the expression, and update the UI on change.
  11719. * scope.$watch(attrs.myCurrentTime, function(value) {
  11720. * format = value;
  11721. * updateTime();
  11722. * });
  11723. *
  11724. * stopTime = $interval(updateTime, 1000);
  11725. *
  11726. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11727. * // to prevent updating time after the DOM element was removed.
  11728. * element.on('$destroy', function() {
  11729. * $interval.cancel(stopTime);
  11730. * });
  11731. * }
  11732. * }]);
  11733. * </script>
  11734. *
  11735. * <div>
  11736. * <div ng-controller="ExampleController">
  11737. * <label>Date format: <input ng-model="format"></label> <hr/>
  11738. * Current time is: <span my-current-time="format"></span>
  11739. * <hr/>
  11740. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11741. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11742. * <button type="button" data-ng-click="fight()">Fight</button>
  11743. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11744. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11745. * </div>
  11746. * </div>
  11747. *
  11748. * </file>
  11749. * </example>
  11750. */
  11751. function interval(fn, delay, count, invokeApply) {
  11752. var hasParams = arguments.length > 4,
  11753. args = hasParams ? sliceArgs(arguments, 4) : [],
  11754. setInterval = $window.setInterval,
  11755. clearInterval = $window.clearInterval,
  11756. iteration = 0,
  11757. skipApply = (isDefined(invokeApply) && !invokeApply),
  11758. deferred = (skipApply ? $$q : $q).defer(),
  11759. promise = deferred.promise;
  11760. count = isDefined(count) ? count : 0;
  11761. promise.$$intervalId = setInterval(function tick() {
  11762. if (skipApply) {
  11763. $browser.defer(callback);
  11764. } else {
  11765. $rootScope.$evalAsync(callback);
  11766. }
  11767. deferred.notify(iteration++);
  11768. if (count > 0 && iteration >= count) {
  11769. deferred.resolve(iteration);
  11770. clearInterval(promise.$$intervalId);
  11771. delete intervals[promise.$$intervalId];
  11772. }
  11773. if (!skipApply) $rootScope.$apply();
  11774. }, delay);
  11775. intervals[promise.$$intervalId] = deferred;
  11776. return promise;
  11777. function callback() {
  11778. if (!hasParams) {
  11779. fn(iteration);
  11780. } else {
  11781. fn.apply(null, args);
  11782. }
  11783. }
  11784. }
  11785. /**
  11786. * @ngdoc method
  11787. * @name $interval#cancel
  11788. *
  11789. * @description
  11790. * Cancels a task associated with the `promise`.
  11791. *
  11792. * @param {Promise=} promise returned by the `$interval` function.
  11793. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11794. */
  11795. interval.cancel = function(promise) {
  11796. if (promise && promise.$$intervalId in intervals) {
  11797. // Interval cancels should not report as unhandled promise.
  11798. intervals[promise.$$intervalId].promise.catch(noop);
  11799. intervals[promise.$$intervalId].reject('canceled');
  11800. $window.clearInterval(promise.$$intervalId);
  11801. delete intervals[promise.$$intervalId];
  11802. return true;
  11803. }
  11804. return false;
  11805. };
  11806. return interval;
  11807. }];
  11808. }
  11809. /**
  11810. * @ngdoc service
  11811. * @name $jsonpCallbacks
  11812. * @requires $window
  11813. * @description
  11814. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11815. * Override this service if you wish to customise where the callbacks are stored and
  11816. * how they vary compared to the requested url.
  11817. */
  11818. var $jsonpCallbacksProvider = /** @this */ function() {
  11819. this.$get = ['$window', function($window) {
  11820. var callbacks = $window.angular.callbacks;
  11821. var callbackMap = {};
  11822. function createCallback(callbackId) {
  11823. var callback = function(data) {
  11824. callback.data = data;
  11825. callback.called = true;
  11826. };
  11827. callback.id = callbackId;
  11828. return callback;
  11829. }
  11830. return {
  11831. /**
  11832. * @ngdoc method
  11833. * @name $jsonpCallbacks#createCallback
  11834. * @param {string} url the url of the JSONP request
  11835. * @returns {string} the callback path to send to the server as part of the JSONP request
  11836. * @description
  11837. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11838. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  11839. */
  11840. createCallback: function(url) {
  11841. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  11842. var callbackPath = 'angular.callbacks.' + callbackId;
  11843. var callback = createCallback(callbackId);
  11844. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  11845. return callbackPath;
  11846. },
  11847. /**
  11848. * @ngdoc method
  11849. * @name $jsonpCallbacks#wasCalled
  11850. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11851. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  11852. * @description
  11853. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  11854. * callback that was passed in the request.
  11855. */
  11856. wasCalled: function(callbackPath) {
  11857. return callbackMap[callbackPath].called;
  11858. },
  11859. /**
  11860. * @ngdoc method
  11861. * @name $jsonpCallbacks#getResponse
  11862. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11863. * @returns {*} the data received from the response via the registered callback
  11864. * @description
  11865. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  11866. * in the JSONP response.
  11867. */
  11868. getResponse: function(callbackPath) {
  11869. return callbackMap[callbackPath].data;
  11870. },
  11871. /**
  11872. * @ngdoc method
  11873. * @name $jsonpCallbacks#removeCallback
  11874. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11875. * @description
  11876. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  11877. * completed or timed-out.
  11878. */
  11879. removeCallback: function(callbackPath) {
  11880. var callback = callbackMap[callbackPath];
  11881. delete callbacks[callback.id];
  11882. delete callbackMap[callbackPath];
  11883. }
  11884. };
  11885. }];
  11886. };
  11887. /**
  11888. * @ngdoc service
  11889. * @name $locale
  11890. *
  11891. * @description
  11892. * $locale service provides localization rules for various Angular components. As of right now the
  11893. * only public api is:
  11894. *
  11895. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11896. */
  11897. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  11898. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11899. var $locationMinErr = minErr('$location');
  11900. /**
  11901. * Encode path using encodeUriSegment, ignoring forward slashes
  11902. *
  11903. * @param {string} path Path to encode
  11904. * @returns {string}
  11905. */
  11906. function encodePath(path) {
  11907. var segments = path.split('/'),
  11908. i = segments.length;
  11909. while (i--) {
  11910. segments[i] = encodeUriSegment(segments[i]);
  11911. }
  11912. return segments.join('/');
  11913. }
  11914. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11915. var parsedUrl = urlResolve(absoluteUrl);
  11916. locationObj.$$protocol = parsedUrl.protocol;
  11917. locationObj.$$host = parsedUrl.hostname;
  11918. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11919. }
  11920. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  11921. function parseAppUrl(url, locationObj) {
  11922. if (DOUBLE_SLASH_REGEX.test(url)) {
  11923. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  11924. }
  11925. var prefixed = (url.charAt(0) !== '/');
  11926. if (prefixed) {
  11927. url = '/' + url;
  11928. }
  11929. var match = urlResolve(url);
  11930. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11931. match.pathname.substring(1) : match.pathname);
  11932. locationObj.$$search = parseKeyValue(match.search);
  11933. locationObj.$$hash = decodeURIComponent(match.hash);
  11934. // make sure path starts with '/';
  11935. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  11936. locationObj.$$path = '/' + locationObj.$$path;
  11937. }
  11938. }
  11939. function startsWith(str, search) {
  11940. return str.slice(0, search.length) === search;
  11941. }
  11942. /**
  11943. *
  11944. * @param {string} base
  11945. * @param {string} url
  11946. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  11947. * the expected string.
  11948. */
  11949. function stripBaseUrl(base, url) {
  11950. if (startsWith(url, base)) {
  11951. return url.substr(base.length);
  11952. }
  11953. }
  11954. function stripHash(url) {
  11955. var index = url.indexOf('#');
  11956. return index === -1 ? url : url.substr(0, index);
  11957. }
  11958. function trimEmptyHash(url) {
  11959. return url.replace(/(#.+)|#$/, '$1');
  11960. }
  11961. function stripFile(url) {
  11962. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11963. }
  11964. /* return the server only (scheme://host:port) */
  11965. function serverBase(url) {
  11966. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11967. }
  11968. /**
  11969. * LocationHtml5Url represents a URL
  11970. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11971. *
  11972. * @constructor
  11973. * @param {string} appBase application base URL
  11974. * @param {string} appBaseNoFile application base URL stripped of any filename
  11975. * @param {string} basePrefix URL path prefix
  11976. */
  11977. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11978. this.$$html5 = true;
  11979. basePrefix = basePrefix || '';
  11980. parseAbsoluteUrl(appBase, this);
  11981. /**
  11982. * Parse given HTML5 (regular) URL string into properties
  11983. * @param {string} url HTML5 URL
  11984. * @private
  11985. */
  11986. this.$$parse = function(url) {
  11987. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  11988. if (!isString(pathUrl)) {
  11989. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11990. appBaseNoFile);
  11991. }
  11992. parseAppUrl(pathUrl, this);
  11993. if (!this.$$path) {
  11994. this.$$path = '/';
  11995. }
  11996. this.$$compose();
  11997. };
  11998. /**
  11999. * Compose url and update `absUrl` property
  12000. * @private
  12001. */
  12002. this.$$compose = function() {
  12003. var search = toKeyValue(this.$$search),
  12004. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12005. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12006. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12007. };
  12008. this.$$parseLinkUrl = function(url, relHref) {
  12009. if (relHref && relHref[0] === '#') {
  12010. // special case for links to hash fragments:
  12011. // keep the old url and only replace the hash fragment
  12012. this.hash(relHref.slice(1));
  12013. return true;
  12014. }
  12015. var appUrl, prevAppUrl;
  12016. var rewrittenUrl;
  12017. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12018. prevAppUrl = appUrl;
  12019. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12020. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12021. } else {
  12022. rewrittenUrl = appBase + prevAppUrl;
  12023. }
  12024. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12025. rewrittenUrl = appBaseNoFile + appUrl;
  12026. } else if (appBaseNoFile === url + '/') {
  12027. rewrittenUrl = appBaseNoFile;
  12028. }
  12029. if (rewrittenUrl) {
  12030. this.$$parse(rewrittenUrl);
  12031. }
  12032. return !!rewrittenUrl;
  12033. };
  12034. }
  12035. /**
  12036. * LocationHashbangUrl represents URL
  12037. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12038. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12039. *
  12040. * @constructor
  12041. * @param {string} appBase application base URL
  12042. * @param {string} appBaseNoFile application base URL stripped of any filename
  12043. * @param {string} hashPrefix hashbang prefix
  12044. */
  12045. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12046. parseAbsoluteUrl(appBase, this);
  12047. /**
  12048. * Parse given hashbang URL into properties
  12049. * @param {string} url Hashbang URL
  12050. * @private
  12051. */
  12052. this.$$parse = function(url) {
  12053. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12054. var withoutHashUrl;
  12055. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12056. // The rest of the URL starts with a hash so we have
  12057. // got either a hashbang path or a plain hash fragment
  12058. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12059. if (isUndefined(withoutHashUrl)) {
  12060. // There was no hashbang prefix so we just have a hash fragment
  12061. withoutHashUrl = withoutBaseUrl;
  12062. }
  12063. } else {
  12064. // There was no hashbang path nor hash fragment:
  12065. // If we are in HTML5 mode we use what is left as the path;
  12066. // Otherwise we ignore what is left
  12067. if (this.$$html5) {
  12068. withoutHashUrl = withoutBaseUrl;
  12069. } else {
  12070. withoutHashUrl = '';
  12071. if (isUndefined(withoutBaseUrl)) {
  12072. appBase = url;
  12073. this.replace();
  12074. }
  12075. }
  12076. }
  12077. parseAppUrl(withoutHashUrl, this);
  12078. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12079. this.$$compose();
  12080. /*
  12081. * In Windows, on an anchor node on documents loaded from
  12082. * the filesystem, the browser will return a pathname
  12083. * prefixed with the drive name ('/C:/path') when a
  12084. * pathname without a drive is set:
  12085. * * a.setAttribute('href', '/foo')
  12086. * * a.pathname === '/C:/foo' //true
  12087. *
  12088. * Inside of Angular, we're always using pathnames that
  12089. * do not include drive names for routing.
  12090. */
  12091. function removeWindowsDriveName(path, url, base) {
  12092. /*
  12093. Matches paths for file protocol on windows,
  12094. such as /C:/foo/bar, and captures only /foo/bar.
  12095. */
  12096. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12097. var firstPathSegmentMatch;
  12098. //Get the relative path from the input URL.
  12099. if (startsWith(url, base)) {
  12100. url = url.replace(base, '');
  12101. }
  12102. // The input URL intentionally contains a first path segment that ends with a colon.
  12103. if (windowsFilePathExp.exec(url)) {
  12104. return path;
  12105. }
  12106. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12107. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12108. }
  12109. };
  12110. /**
  12111. * Compose hashbang URL and update `absUrl` property
  12112. * @private
  12113. */
  12114. this.$$compose = function() {
  12115. var search = toKeyValue(this.$$search),
  12116. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12117. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12118. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12119. };
  12120. this.$$parseLinkUrl = function(url, relHref) {
  12121. if (stripHash(appBase) === stripHash(url)) {
  12122. this.$$parse(url);
  12123. return true;
  12124. }
  12125. return false;
  12126. };
  12127. }
  12128. /**
  12129. * LocationHashbangUrl represents URL
  12130. * This object is exposed as $location service when html5 history api is enabled but the browser
  12131. * does not support it.
  12132. *
  12133. * @constructor
  12134. * @param {string} appBase application base URL
  12135. * @param {string} appBaseNoFile application base URL stripped of any filename
  12136. * @param {string} hashPrefix hashbang prefix
  12137. */
  12138. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12139. this.$$html5 = true;
  12140. LocationHashbangUrl.apply(this, arguments);
  12141. this.$$parseLinkUrl = function(url, relHref) {
  12142. if (relHref && relHref[0] === '#') {
  12143. // special case for links to hash fragments:
  12144. // keep the old url and only replace the hash fragment
  12145. this.hash(relHref.slice(1));
  12146. return true;
  12147. }
  12148. var rewrittenUrl;
  12149. var appUrl;
  12150. if (appBase === stripHash(url)) {
  12151. rewrittenUrl = url;
  12152. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12153. rewrittenUrl = appBase + hashPrefix + appUrl;
  12154. } else if (appBaseNoFile === url + '/') {
  12155. rewrittenUrl = appBaseNoFile;
  12156. }
  12157. if (rewrittenUrl) {
  12158. this.$$parse(rewrittenUrl);
  12159. }
  12160. return !!rewrittenUrl;
  12161. };
  12162. this.$$compose = function() {
  12163. var search = toKeyValue(this.$$search),
  12164. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12165. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12166. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12167. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12168. };
  12169. }
  12170. var locationPrototype = {
  12171. /**
  12172. * Ensure absolute URL is initialized.
  12173. * @private
  12174. */
  12175. $$absUrl:'',
  12176. /**
  12177. * Are we in html5 mode?
  12178. * @private
  12179. */
  12180. $$html5: false,
  12181. /**
  12182. * Has any change been replacing?
  12183. * @private
  12184. */
  12185. $$replace: false,
  12186. /**
  12187. * @ngdoc method
  12188. * @name $location#absUrl
  12189. *
  12190. * @description
  12191. * This method is getter only.
  12192. *
  12193. * Return full URL representation with all segments encoded according to rules specified in
  12194. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12195. *
  12196. *
  12197. * ```js
  12198. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12199. * var absUrl = $location.absUrl();
  12200. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12201. * ```
  12202. *
  12203. * @return {string} full URL
  12204. */
  12205. absUrl: locationGetter('$$absUrl'),
  12206. /**
  12207. * @ngdoc method
  12208. * @name $location#url
  12209. *
  12210. * @description
  12211. * This method is getter / setter.
  12212. *
  12213. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12214. *
  12215. * Change path, search and hash, when called with parameter and return `$location`.
  12216. *
  12217. *
  12218. * ```js
  12219. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12220. * var url = $location.url();
  12221. * // => "/some/path?foo=bar&baz=xoxo"
  12222. * ```
  12223. *
  12224. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12225. * @return {string} url
  12226. */
  12227. url: function(url) {
  12228. if (isUndefined(url)) {
  12229. return this.$$url;
  12230. }
  12231. var match = PATH_MATCH.exec(url);
  12232. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12233. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12234. this.hash(match[5] || '');
  12235. return this;
  12236. },
  12237. /**
  12238. * @ngdoc method
  12239. * @name $location#protocol
  12240. *
  12241. * @description
  12242. * This method is getter only.
  12243. *
  12244. * Return protocol of current URL.
  12245. *
  12246. *
  12247. * ```js
  12248. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12249. * var protocol = $location.protocol();
  12250. * // => "http"
  12251. * ```
  12252. *
  12253. * @return {string} protocol of current URL
  12254. */
  12255. protocol: locationGetter('$$protocol'),
  12256. /**
  12257. * @ngdoc method
  12258. * @name $location#host
  12259. *
  12260. * @description
  12261. * This method is getter only.
  12262. *
  12263. * Return host of current URL.
  12264. *
  12265. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12266. *
  12267. *
  12268. * ```js
  12269. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12270. * var host = $location.host();
  12271. * // => "example.com"
  12272. *
  12273. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12274. * host = $location.host();
  12275. * // => "example.com"
  12276. * host = location.host;
  12277. * // => "example.com:8080"
  12278. * ```
  12279. *
  12280. * @return {string} host of current URL.
  12281. */
  12282. host: locationGetter('$$host'),
  12283. /**
  12284. * @ngdoc method
  12285. * @name $location#port
  12286. *
  12287. * @description
  12288. * This method is getter only.
  12289. *
  12290. * Return port of current URL.
  12291. *
  12292. *
  12293. * ```js
  12294. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12295. * var port = $location.port();
  12296. * // => 80
  12297. * ```
  12298. *
  12299. * @return {Number} port
  12300. */
  12301. port: locationGetter('$$port'),
  12302. /**
  12303. * @ngdoc method
  12304. * @name $location#path
  12305. *
  12306. * @description
  12307. * This method is getter / setter.
  12308. *
  12309. * Return path of current URL when called without any parameter.
  12310. *
  12311. * Change path when called with parameter and return `$location`.
  12312. *
  12313. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12314. * if it is missing.
  12315. *
  12316. *
  12317. * ```js
  12318. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12319. * var path = $location.path();
  12320. * // => "/some/path"
  12321. * ```
  12322. *
  12323. * @param {(string|number)=} path New path
  12324. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12325. */
  12326. path: locationGetterSetter('$$path', function(path) {
  12327. path = path !== null ? path.toString() : '';
  12328. return path.charAt(0) === '/' ? path : '/' + path;
  12329. }),
  12330. /**
  12331. * @ngdoc method
  12332. * @name $location#search
  12333. *
  12334. * @description
  12335. * This method is getter / setter.
  12336. *
  12337. * Return search part (as object) of current URL when called without any parameter.
  12338. *
  12339. * Change search part when called with parameter and return `$location`.
  12340. *
  12341. *
  12342. * ```js
  12343. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12344. * var searchObject = $location.search();
  12345. * // => {foo: 'bar', baz: 'xoxo'}
  12346. *
  12347. * // set foo to 'yipee'
  12348. * $location.search('foo', 'yipee');
  12349. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12350. * ```
  12351. *
  12352. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12353. * hash object.
  12354. *
  12355. * When called with a single argument the method acts as a setter, setting the `search` component
  12356. * of `$location` to the specified value.
  12357. *
  12358. * If the argument is a hash object containing an array of values, these values will be encoded
  12359. * as duplicate search parameters in the URL.
  12360. *
  12361. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12362. * will override only a single search property.
  12363. *
  12364. * If `paramValue` is an array, it will override the property of the `search` component of
  12365. * `$location` specified via the first argument.
  12366. *
  12367. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12368. *
  12369. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12370. * value nor trailing equal sign.
  12371. *
  12372. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12373. * one or more arguments returns `$location` object itself.
  12374. */
  12375. search: function(search, paramValue) {
  12376. switch (arguments.length) {
  12377. case 0:
  12378. return this.$$search;
  12379. case 1:
  12380. if (isString(search) || isNumber(search)) {
  12381. search = search.toString();
  12382. this.$$search = parseKeyValue(search);
  12383. } else if (isObject(search)) {
  12384. search = copy(search, {});
  12385. // remove object undefined or null properties
  12386. forEach(search, function(value, key) {
  12387. if (value == null) delete search[key];
  12388. });
  12389. this.$$search = search;
  12390. } else {
  12391. throw $locationMinErr('isrcharg',
  12392. 'The first argument of the `$location#search()` call must be a string or an object.');
  12393. }
  12394. break;
  12395. default:
  12396. if (isUndefined(paramValue) || paramValue === null) {
  12397. delete this.$$search[search];
  12398. } else {
  12399. this.$$search[search] = paramValue;
  12400. }
  12401. }
  12402. this.$$compose();
  12403. return this;
  12404. },
  12405. /**
  12406. * @ngdoc method
  12407. * @name $location#hash
  12408. *
  12409. * @description
  12410. * This method is getter / setter.
  12411. *
  12412. * Returns the hash fragment when called without any parameters.
  12413. *
  12414. * Changes the hash fragment when called with a parameter and returns `$location`.
  12415. *
  12416. *
  12417. * ```js
  12418. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12419. * var hash = $location.hash();
  12420. * // => "hashValue"
  12421. * ```
  12422. *
  12423. * @param {(string|number)=} hash New hash fragment
  12424. * @return {string} hash
  12425. */
  12426. hash: locationGetterSetter('$$hash', function(hash) {
  12427. return hash !== null ? hash.toString() : '';
  12428. }),
  12429. /**
  12430. * @ngdoc method
  12431. * @name $location#replace
  12432. *
  12433. * @description
  12434. * If called, all changes to $location during the current `$digest` will replace the current history
  12435. * record, instead of adding a new one.
  12436. */
  12437. replace: function() {
  12438. this.$$replace = true;
  12439. return this;
  12440. }
  12441. };
  12442. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12443. Location.prototype = Object.create(locationPrototype);
  12444. /**
  12445. * @ngdoc method
  12446. * @name $location#state
  12447. *
  12448. * @description
  12449. * This method is getter / setter.
  12450. *
  12451. * Return the history state object when called without any parameter.
  12452. *
  12453. * Change the history state object when called with one parameter and return `$location`.
  12454. * The state object is later passed to `pushState` or `replaceState`.
  12455. *
  12456. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12457. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12458. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12459. *
  12460. * @param {object=} state State object for pushState or replaceState
  12461. * @return {object} state
  12462. */
  12463. Location.prototype.state = function(state) {
  12464. if (!arguments.length) {
  12465. return this.$$state;
  12466. }
  12467. if (Location !== LocationHtml5Url || !this.$$html5) {
  12468. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12469. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12470. }
  12471. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12472. // but we're changing the $$state reference to $browser.state() during the $digest
  12473. // so the modification window is narrow.
  12474. this.$$state = isUndefined(state) ? null : state;
  12475. return this;
  12476. };
  12477. });
  12478. function locationGetter(property) {
  12479. return /** @this */ function() {
  12480. return this[property];
  12481. };
  12482. }
  12483. function locationGetterSetter(property, preprocess) {
  12484. return /** @this */ function(value) {
  12485. if (isUndefined(value)) {
  12486. return this[property];
  12487. }
  12488. this[property] = preprocess(value);
  12489. this.$$compose();
  12490. return this;
  12491. };
  12492. }
  12493. /**
  12494. * @ngdoc service
  12495. * @name $location
  12496. *
  12497. * @requires $rootElement
  12498. *
  12499. * @description
  12500. * The $location service parses the URL in the browser address bar (based on the
  12501. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12502. * available to your application. Changes to the URL in the address bar are reflected into
  12503. * $location service and changes to $location are reflected into the browser address bar.
  12504. *
  12505. * **The $location service:**
  12506. *
  12507. * - Exposes the current URL in the browser address bar, so you can
  12508. * - Watch and observe the URL.
  12509. * - Change the URL.
  12510. * - Synchronizes the URL with the browser when the user
  12511. * - Changes the address bar.
  12512. * - Clicks the back or forward button (or clicks a History link).
  12513. * - Clicks on a link.
  12514. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12515. *
  12516. * For more information see {@link guide/$location Developer Guide: Using $location}
  12517. */
  12518. /**
  12519. * @ngdoc provider
  12520. * @name $locationProvider
  12521. * @this
  12522. *
  12523. * @description
  12524. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12525. */
  12526. function $LocationProvider() {
  12527. var hashPrefix = '!',
  12528. html5Mode = {
  12529. enabled: false,
  12530. requireBase: true,
  12531. rewriteLinks: true
  12532. };
  12533. /**
  12534. * @ngdoc method
  12535. * @name $locationProvider#hashPrefix
  12536. * @description
  12537. * The default value for the prefix is `'!'`.
  12538. * @param {string=} prefix Prefix for hash part (containing path and search)
  12539. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12540. */
  12541. this.hashPrefix = function(prefix) {
  12542. if (isDefined(prefix)) {
  12543. hashPrefix = prefix;
  12544. return this;
  12545. } else {
  12546. return hashPrefix;
  12547. }
  12548. };
  12549. /**
  12550. * @ngdoc method
  12551. * @name $locationProvider#html5Mode
  12552. * @description
  12553. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12554. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12555. * properties:
  12556. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12557. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12558. * support `pushState`.
  12559. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12560. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12561. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12562. * See the {@link guide/$location $location guide for more information}
  12563. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12564. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12565. * only happen on links with an attribute that matches the given string. For example, if set
  12566. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12567. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12568. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12569. *
  12570. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12571. */
  12572. this.html5Mode = function(mode) {
  12573. if (isBoolean(mode)) {
  12574. html5Mode.enabled = mode;
  12575. return this;
  12576. } else if (isObject(mode)) {
  12577. if (isBoolean(mode.enabled)) {
  12578. html5Mode.enabled = mode.enabled;
  12579. }
  12580. if (isBoolean(mode.requireBase)) {
  12581. html5Mode.requireBase = mode.requireBase;
  12582. }
  12583. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12584. html5Mode.rewriteLinks = mode.rewriteLinks;
  12585. }
  12586. return this;
  12587. } else {
  12588. return html5Mode;
  12589. }
  12590. };
  12591. /**
  12592. * @ngdoc event
  12593. * @name $location#$locationChangeStart
  12594. * @eventType broadcast on root scope
  12595. * @description
  12596. * Broadcasted before a URL will change.
  12597. *
  12598. * This change can be prevented by calling
  12599. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12600. * details about event object. Upon successful change
  12601. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12602. *
  12603. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12604. * the browser supports the HTML5 History API.
  12605. *
  12606. * @param {Object} angularEvent Synthetic event object.
  12607. * @param {string} newUrl New URL
  12608. * @param {string=} oldUrl URL that was before it was changed.
  12609. * @param {string=} newState New history state object
  12610. * @param {string=} oldState History state object that was before it was changed.
  12611. */
  12612. /**
  12613. * @ngdoc event
  12614. * @name $location#$locationChangeSuccess
  12615. * @eventType broadcast on root scope
  12616. * @description
  12617. * Broadcasted after a URL was changed.
  12618. *
  12619. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12620. * the browser supports the HTML5 History API.
  12621. *
  12622. * @param {Object} angularEvent Synthetic event object.
  12623. * @param {string} newUrl New URL
  12624. * @param {string=} oldUrl URL that was before it was changed.
  12625. * @param {string=} newState New history state object
  12626. * @param {string=} oldState History state object that was before it was changed.
  12627. */
  12628. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12629. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12630. var $location,
  12631. LocationMode,
  12632. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12633. initialUrl = $browser.url(),
  12634. appBase;
  12635. if (html5Mode.enabled) {
  12636. if (!baseHref && html5Mode.requireBase) {
  12637. throw $locationMinErr('nobase',
  12638. '$location in HTML5 mode requires a <base> tag to be present!');
  12639. }
  12640. appBase = serverBase(initialUrl) + (baseHref || '/');
  12641. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12642. } else {
  12643. appBase = stripHash(initialUrl);
  12644. LocationMode = LocationHashbangUrl;
  12645. }
  12646. var appBaseNoFile = stripFile(appBase);
  12647. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12648. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12649. $location.$$state = $browser.state();
  12650. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12651. function setBrowserUrlWithFallback(url, replace, state) {
  12652. var oldUrl = $location.url();
  12653. var oldState = $location.$$state;
  12654. try {
  12655. $browser.url(url, replace, state);
  12656. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12657. // state object; this makes possible quick checking if the state changed in the digest
  12658. // loop. Checking deep equality would be too expensive.
  12659. $location.$$state = $browser.state();
  12660. } catch (e) {
  12661. // Restore old values if pushState fails
  12662. $location.url(oldUrl);
  12663. $location.$$state = oldState;
  12664. throw e;
  12665. }
  12666. }
  12667. $rootElement.on('click', function(event) {
  12668. var rewriteLinks = html5Mode.rewriteLinks;
  12669. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12670. // currently we open nice url link and redirect then
  12671. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12672. var elm = jqLite(event.target);
  12673. // traverse the DOM up to find first A tag
  12674. while (nodeName_(elm[0]) !== 'a') {
  12675. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12676. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12677. }
  12678. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  12679. var absHref = elm.prop('href');
  12680. // get the actual href attribute - see
  12681. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12682. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12683. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12684. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12685. // an animation.
  12686. absHref = urlResolve(absHref.animVal).href;
  12687. }
  12688. // Ignore when url is started with javascript: or mailto:
  12689. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12690. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12691. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12692. // We do a preventDefault for all urls that are part of the angular application,
  12693. // in html5mode and also without, so that we are able to abort navigation without
  12694. // getting double entries in the location history.
  12695. event.preventDefault();
  12696. // update location manually
  12697. if ($location.absUrl() !== $browser.url()) {
  12698. $rootScope.$apply();
  12699. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12700. $window.angular['ff-684208-preventDefault'] = true;
  12701. }
  12702. }
  12703. }
  12704. });
  12705. // rewrite hashbang url <> html5 url
  12706. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  12707. $browser.url($location.absUrl(), true);
  12708. }
  12709. var initializing = true;
  12710. // update $location when $browser url changes
  12711. $browser.onUrlChange(function(newUrl, newState) {
  12712. if (!startsWith(newUrl, appBaseNoFile)) {
  12713. // If we are navigating outside of the app then force a reload
  12714. $window.location.href = newUrl;
  12715. return;
  12716. }
  12717. $rootScope.$evalAsync(function() {
  12718. var oldUrl = $location.absUrl();
  12719. var oldState = $location.$$state;
  12720. var defaultPrevented;
  12721. newUrl = trimEmptyHash(newUrl);
  12722. $location.$$parse(newUrl);
  12723. $location.$$state = newState;
  12724. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12725. newState, oldState).defaultPrevented;
  12726. // if the location was changed by a `$locationChangeStart` handler then stop
  12727. // processing this location change
  12728. if ($location.absUrl() !== newUrl) return;
  12729. if (defaultPrevented) {
  12730. $location.$$parse(oldUrl);
  12731. $location.$$state = oldState;
  12732. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12733. } else {
  12734. initializing = false;
  12735. afterLocationChange(oldUrl, oldState);
  12736. }
  12737. });
  12738. if (!$rootScope.$$phase) $rootScope.$digest();
  12739. });
  12740. // update browser
  12741. $rootScope.$watch(function $locationWatch() {
  12742. var oldUrl = trimEmptyHash($browser.url());
  12743. var newUrl = trimEmptyHash($location.absUrl());
  12744. var oldState = $browser.state();
  12745. var currentReplace = $location.$$replace;
  12746. var urlOrStateChanged = oldUrl !== newUrl ||
  12747. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12748. if (initializing || urlOrStateChanged) {
  12749. initializing = false;
  12750. $rootScope.$evalAsync(function() {
  12751. var newUrl = $location.absUrl();
  12752. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12753. $location.$$state, oldState).defaultPrevented;
  12754. // if the location was changed by a `$locationChangeStart` handler then stop
  12755. // processing this location change
  12756. if ($location.absUrl() !== newUrl) return;
  12757. if (defaultPrevented) {
  12758. $location.$$parse(oldUrl);
  12759. $location.$$state = oldState;
  12760. } else {
  12761. if (urlOrStateChanged) {
  12762. setBrowserUrlWithFallback(newUrl, currentReplace,
  12763. oldState === $location.$$state ? null : $location.$$state);
  12764. }
  12765. afterLocationChange(oldUrl, oldState);
  12766. }
  12767. });
  12768. }
  12769. $location.$$replace = false;
  12770. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12771. // there is a change
  12772. });
  12773. return $location;
  12774. function afterLocationChange(oldUrl, oldState) {
  12775. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12776. $location.$$state, oldState);
  12777. }
  12778. }];
  12779. }
  12780. /**
  12781. * @ngdoc service
  12782. * @name $log
  12783. * @requires $window
  12784. *
  12785. * @description
  12786. * Simple service for logging. Default implementation safely writes the message
  12787. * into the browser's console (if present).
  12788. *
  12789. * The main purpose of this service is to simplify debugging and troubleshooting.
  12790. *
  12791. * The default is to log `debug` messages. You can use
  12792. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12793. *
  12794. * @example
  12795. <example module="logExample" name="log-service">
  12796. <file name="script.js">
  12797. angular.module('logExample', [])
  12798. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12799. $scope.$log = $log;
  12800. $scope.message = 'Hello World!';
  12801. }]);
  12802. </file>
  12803. <file name="index.html">
  12804. <div ng-controller="LogController">
  12805. <p>Reload this page with open console, enter text and hit the log button...</p>
  12806. <label>Message:
  12807. <input type="text" ng-model="message" /></label>
  12808. <button ng-click="$log.log(message)">log</button>
  12809. <button ng-click="$log.warn(message)">warn</button>
  12810. <button ng-click="$log.info(message)">info</button>
  12811. <button ng-click="$log.error(message)">error</button>
  12812. <button ng-click="$log.debug(message)">debug</button>
  12813. </div>
  12814. </file>
  12815. </example>
  12816. */
  12817. /**
  12818. * @ngdoc provider
  12819. * @name $logProvider
  12820. * @this
  12821. *
  12822. * @description
  12823. * Use the `$logProvider` to configure how the application logs messages
  12824. */
  12825. function $LogProvider() {
  12826. var debug = true,
  12827. self = this;
  12828. /**
  12829. * @ngdoc method
  12830. * @name $logProvider#debugEnabled
  12831. * @description
  12832. * @param {boolean=} flag enable or disable debug level messages
  12833. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12834. */
  12835. this.debugEnabled = function(flag) {
  12836. if (isDefined(flag)) {
  12837. debug = flag;
  12838. return this;
  12839. } else {
  12840. return debug;
  12841. }
  12842. };
  12843. this.$get = ['$window', function($window) {
  12844. return {
  12845. /**
  12846. * @ngdoc method
  12847. * @name $log#log
  12848. *
  12849. * @description
  12850. * Write a log message
  12851. */
  12852. log: consoleLog('log'),
  12853. /**
  12854. * @ngdoc method
  12855. * @name $log#info
  12856. *
  12857. * @description
  12858. * Write an information message
  12859. */
  12860. info: consoleLog('info'),
  12861. /**
  12862. * @ngdoc method
  12863. * @name $log#warn
  12864. *
  12865. * @description
  12866. * Write a warning message
  12867. */
  12868. warn: consoleLog('warn'),
  12869. /**
  12870. * @ngdoc method
  12871. * @name $log#error
  12872. *
  12873. * @description
  12874. * Write an error message
  12875. */
  12876. error: consoleLog('error'),
  12877. /**
  12878. * @ngdoc method
  12879. * @name $log#debug
  12880. *
  12881. * @description
  12882. * Write a debug message
  12883. */
  12884. debug: (function() {
  12885. var fn = consoleLog('debug');
  12886. return function() {
  12887. if (debug) {
  12888. fn.apply(self, arguments);
  12889. }
  12890. };
  12891. })()
  12892. };
  12893. function formatError(arg) {
  12894. if (arg instanceof Error) {
  12895. if (arg.stack) {
  12896. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12897. ? 'Error: ' + arg.message + '\n' + arg.stack
  12898. : arg.stack;
  12899. } else if (arg.sourceURL) {
  12900. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12901. }
  12902. }
  12903. return arg;
  12904. }
  12905. function consoleLog(type) {
  12906. var console = $window.console || {},
  12907. logFn = console[type] || console.log || noop,
  12908. hasApply = false;
  12909. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12910. // The reason behind this is that console.log has type "object" in IE8...
  12911. try {
  12912. hasApply = !!logFn.apply;
  12913. } catch (e) { /* empty */ }
  12914. if (hasApply) {
  12915. return function() {
  12916. var args = [];
  12917. forEach(arguments, function(arg) {
  12918. args.push(formatError(arg));
  12919. });
  12920. return logFn.apply(console, args);
  12921. };
  12922. }
  12923. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12924. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12925. return function(arg1, arg2) {
  12926. logFn(arg1, arg2 == null ? '' : arg2);
  12927. };
  12928. }
  12929. }];
  12930. }
  12931. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12932. * Any commits to this file should be reviewed with security in mind. *
  12933. * Changes to this file can potentially create security vulnerabilities. *
  12934. * An approval from 2 Core members with history of modifying *
  12935. * this file is required. *
  12936. * *
  12937. * Does the change somehow allow for arbitrary javascript to be executed? *
  12938. * Or allows for someone to change the prototype of built-in objects? *
  12939. * Or gives undesired access to variables likes document or window? *
  12940. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12941. var $parseMinErr = minErr('$parse');
  12942. var objectValueOf = {}.constructor.prototype.valueOf;
  12943. // Sandboxing Angular Expressions
  12944. // ------------------------------
  12945. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  12946. // various means such as obtaining a reference to native JS functions like the Function constructor.
  12947. //
  12948. // As an example, consider the following Angular expression:
  12949. //
  12950. // {}.toString.constructor('alert("evil JS code")')
  12951. //
  12952. // It is important to realize that if you create an expression from a string that contains user provided
  12953. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  12954. //
  12955. // See https://docs.angularjs.org/guide/security
  12956. function getStringValue(name) {
  12957. // Property names must be strings. This means that non-string objects cannot be used
  12958. // as keys in an object. Any non-string object, including a number, is typecasted
  12959. // into a string via the toString method.
  12960. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12961. //
  12962. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12963. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12964. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12965. //
  12966. // TypeError: Cannot convert object to primitive value
  12967. //
  12968. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12969. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12970. // such a 'broken' object as a key.
  12971. return name + '';
  12972. }
  12973. var OPERATORS = createMap();
  12974. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12975. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  12976. /////////////////////////////////////////
  12977. /**
  12978. * @constructor
  12979. */
  12980. var Lexer = function Lexer(options) {
  12981. this.options = options;
  12982. };
  12983. Lexer.prototype = {
  12984. constructor: Lexer,
  12985. lex: function(text) {
  12986. this.text = text;
  12987. this.index = 0;
  12988. this.tokens = [];
  12989. while (this.index < this.text.length) {
  12990. var ch = this.text.charAt(this.index);
  12991. if (ch === '"' || ch === '\'') {
  12992. this.readString(ch);
  12993. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12994. this.readNumber();
  12995. } else if (this.isIdentifierStart(this.peekMultichar())) {
  12996. this.readIdent();
  12997. } else if (this.is(ch, '(){}[].,;:?')) {
  12998. this.tokens.push({index: this.index, text: ch});
  12999. this.index++;
  13000. } else if (this.isWhitespace(ch)) {
  13001. this.index++;
  13002. } else {
  13003. var ch2 = ch + this.peek();
  13004. var ch3 = ch2 + this.peek(2);
  13005. var op1 = OPERATORS[ch];
  13006. var op2 = OPERATORS[ch2];
  13007. var op3 = OPERATORS[ch3];
  13008. if (op1 || op2 || op3) {
  13009. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13010. this.tokens.push({index: this.index, text: token, operator: true});
  13011. this.index += token.length;
  13012. } else {
  13013. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13014. }
  13015. }
  13016. }
  13017. return this.tokens;
  13018. },
  13019. is: function(ch, chars) {
  13020. return chars.indexOf(ch) !== -1;
  13021. },
  13022. peek: function(i) {
  13023. var num = i || 1;
  13024. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13025. },
  13026. isNumber: function(ch) {
  13027. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13028. },
  13029. isWhitespace: function(ch) {
  13030. // IE treats non-breaking space as \u00A0
  13031. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13032. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13033. },
  13034. isIdentifierStart: function(ch) {
  13035. return this.options.isIdentifierStart ?
  13036. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13037. this.isValidIdentifierStart(ch);
  13038. },
  13039. isValidIdentifierStart: function(ch) {
  13040. return ('a' <= ch && ch <= 'z' ||
  13041. 'A' <= ch && ch <= 'Z' ||
  13042. '_' === ch || ch === '$');
  13043. },
  13044. isIdentifierContinue: function(ch) {
  13045. return this.options.isIdentifierContinue ?
  13046. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13047. this.isValidIdentifierContinue(ch);
  13048. },
  13049. isValidIdentifierContinue: function(ch, cp) {
  13050. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13051. },
  13052. codePointAt: function(ch) {
  13053. if (ch.length === 1) return ch.charCodeAt(0);
  13054. // eslint-disable-next-line no-bitwise
  13055. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13056. },
  13057. peekMultichar: function() {
  13058. var ch = this.text.charAt(this.index);
  13059. var peek = this.peek();
  13060. if (!peek) {
  13061. return ch;
  13062. }
  13063. var cp1 = ch.charCodeAt(0);
  13064. var cp2 = peek.charCodeAt(0);
  13065. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13066. return ch + peek;
  13067. }
  13068. return ch;
  13069. },
  13070. isExpOperator: function(ch) {
  13071. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13072. },
  13073. throwError: function(error, start, end) {
  13074. end = end || this.index;
  13075. var colStr = (isDefined(start)
  13076. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13077. : ' ' + end);
  13078. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13079. error, colStr, this.text);
  13080. },
  13081. readNumber: function() {
  13082. var number = '';
  13083. var start = this.index;
  13084. while (this.index < this.text.length) {
  13085. var ch = lowercase(this.text.charAt(this.index));
  13086. if (ch === '.' || this.isNumber(ch)) {
  13087. number += ch;
  13088. } else {
  13089. var peekCh = this.peek();
  13090. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13091. number += ch;
  13092. } else if (this.isExpOperator(ch) &&
  13093. peekCh && this.isNumber(peekCh) &&
  13094. number.charAt(number.length - 1) === 'e') {
  13095. number += ch;
  13096. } else if (this.isExpOperator(ch) &&
  13097. (!peekCh || !this.isNumber(peekCh)) &&
  13098. number.charAt(number.length - 1) === 'e') {
  13099. this.throwError('Invalid exponent');
  13100. } else {
  13101. break;
  13102. }
  13103. }
  13104. this.index++;
  13105. }
  13106. this.tokens.push({
  13107. index: start,
  13108. text: number,
  13109. constant: true,
  13110. value: Number(number)
  13111. });
  13112. },
  13113. readIdent: function() {
  13114. var start = this.index;
  13115. this.index += this.peekMultichar().length;
  13116. while (this.index < this.text.length) {
  13117. var ch = this.peekMultichar();
  13118. if (!this.isIdentifierContinue(ch)) {
  13119. break;
  13120. }
  13121. this.index += ch.length;
  13122. }
  13123. this.tokens.push({
  13124. index: start,
  13125. text: this.text.slice(start, this.index),
  13126. identifier: true
  13127. });
  13128. },
  13129. readString: function(quote) {
  13130. var start = this.index;
  13131. this.index++;
  13132. var string = '';
  13133. var rawString = quote;
  13134. var escape = false;
  13135. while (this.index < this.text.length) {
  13136. var ch = this.text.charAt(this.index);
  13137. rawString += ch;
  13138. if (escape) {
  13139. if (ch === 'u') {
  13140. var hex = this.text.substring(this.index + 1, this.index + 5);
  13141. if (!hex.match(/[\da-f]{4}/i)) {
  13142. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13143. }
  13144. this.index += 4;
  13145. string += String.fromCharCode(parseInt(hex, 16));
  13146. } else {
  13147. var rep = ESCAPE[ch];
  13148. string = string + (rep || ch);
  13149. }
  13150. escape = false;
  13151. } else if (ch === '\\') {
  13152. escape = true;
  13153. } else if (ch === quote) {
  13154. this.index++;
  13155. this.tokens.push({
  13156. index: start,
  13157. text: rawString,
  13158. constant: true,
  13159. value: string
  13160. });
  13161. return;
  13162. } else {
  13163. string += ch;
  13164. }
  13165. this.index++;
  13166. }
  13167. this.throwError('Unterminated quote', start);
  13168. }
  13169. };
  13170. var AST = function AST(lexer, options) {
  13171. this.lexer = lexer;
  13172. this.options = options;
  13173. };
  13174. AST.Program = 'Program';
  13175. AST.ExpressionStatement = 'ExpressionStatement';
  13176. AST.AssignmentExpression = 'AssignmentExpression';
  13177. AST.ConditionalExpression = 'ConditionalExpression';
  13178. AST.LogicalExpression = 'LogicalExpression';
  13179. AST.BinaryExpression = 'BinaryExpression';
  13180. AST.UnaryExpression = 'UnaryExpression';
  13181. AST.CallExpression = 'CallExpression';
  13182. AST.MemberExpression = 'MemberExpression';
  13183. AST.Identifier = 'Identifier';
  13184. AST.Literal = 'Literal';
  13185. AST.ArrayExpression = 'ArrayExpression';
  13186. AST.Property = 'Property';
  13187. AST.ObjectExpression = 'ObjectExpression';
  13188. AST.ThisExpression = 'ThisExpression';
  13189. AST.LocalsExpression = 'LocalsExpression';
  13190. // Internal use only
  13191. AST.NGValueParameter = 'NGValueParameter';
  13192. AST.prototype = {
  13193. ast: function(text) {
  13194. this.text = text;
  13195. this.tokens = this.lexer.lex(text);
  13196. var value = this.program();
  13197. if (this.tokens.length !== 0) {
  13198. this.throwError('is an unexpected token', this.tokens[0]);
  13199. }
  13200. return value;
  13201. },
  13202. program: function() {
  13203. var body = [];
  13204. while (true) {
  13205. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13206. body.push(this.expressionStatement());
  13207. if (!this.expect(';')) {
  13208. return { type: AST.Program, body: body};
  13209. }
  13210. }
  13211. },
  13212. expressionStatement: function() {
  13213. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13214. },
  13215. filterChain: function() {
  13216. var left = this.expression();
  13217. while (this.expect('|')) {
  13218. left = this.filter(left);
  13219. }
  13220. return left;
  13221. },
  13222. expression: function() {
  13223. return this.assignment();
  13224. },
  13225. assignment: function() {
  13226. var result = this.ternary();
  13227. if (this.expect('=')) {
  13228. if (!isAssignable(result)) {
  13229. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13230. }
  13231. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13232. }
  13233. return result;
  13234. },
  13235. ternary: function() {
  13236. var test = this.logicalOR();
  13237. var alternate;
  13238. var consequent;
  13239. if (this.expect('?')) {
  13240. alternate = this.expression();
  13241. if (this.consume(':')) {
  13242. consequent = this.expression();
  13243. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13244. }
  13245. }
  13246. return test;
  13247. },
  13248. logicalOR: function() {
  13249. var left = this.logicalAND();
  13250. while (this.expect('||')) {
  13251. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13252. }
  13253. return left;
  13254. },
  13255. logicalAND: function() {
  13256. var left = this.equality();
  13257. while (this.expect('&&')) {
  13258. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13259. }
  13260. return left;
  13261. },
  13262. equality: function() {
  13263. var left = this.relational();
  13264. var token;
  13265. while ((token = this.expect('==','!=','===','!=='))) {
  13266. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13267. }
  13268. return left;
  13269. },
  13270. relational: function() {
  13271. var left = this.additive();
  13272. var token;
  13273. while ((token = this.expect('<', '>', '<=', '>='))) {
  13274. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13275. }
  13276. return left;
  13277. },
  13278. additive: function() {
  13279. var left = this.multiplicative();
  13280. var token;
  13281. while ((token = this.expect('+','-'))) {
  13282. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13283. }
  13284. return left;
  13285. },
  13286. multiplicative: function() {
  13287. var left = this.unary();
  13288. var token;
  13289. while ((token = this.expect('*','/','%'))) {
  13290. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13291. }
  13292. return left;
  13293. },
  13294. unary: function() {
  13295. var token;
  13296. if ((token = this.expect('+', '-', '!'))) {
  13297. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13298. } else {
  13299. return this.primary();
  13300. }
  13301. },
  13302. primary: function() {
  13303. var primary;
  13304. if (this.expect('(')) {
  13305. primary = this.filterChain();
  13306. this.consume(')');
  13307. } else if (this.expect('[')) {
  13308. primary = this.arrayDeclaration();
  13309. } else if (this.expect('{')) {
  13310. primary = this.object();
  13311. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13312. primary = copy(this.selfReferential[this.consume().text]);
  13313. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13314. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13315. } else if (this.peek().identifier) {
  13316. primary = this.identifier();
  13317. } else if (this.peek().constant) {
  13318. primary = this.constant();
  13319. } else {
  13320. this.throwError('not a primary expression', this.peek());
  13321. }
  13322. var next;
  13323. while ((next = this.expect('(', '[', '.'))) {
  13324. if (next.text === '(') {
  13325. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13326. this.consume(')');
  13327. } else if (next.text === '[') {
  13328. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13329. this.consume(']');
  13330. } else if (next.text === '.') {
  13331. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13332. } else {
  13333. this.throwError('IMPOSSIBLE');
  13334. }
  13335. }
  13336. return primary;
  13337. },
  13338. filter: function(baseExpression) {
  13339. var args = [baseExpression];
  13340. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13341. while (this.expect(':')) {
  13342. args.push(this.expression());
  13343. }
  13344. return result;
  13345. },
  13346. parseArguments: function() {
  13347. var args = [];
  13348. if (this.peekToken().text !== ')') {
  13349. do {
  13350. args.push(this.filterChain());
  13351. } while (this.expect(','));
  13352. }
  13353. return args;
  13354. },
  13355. identifier: function() {
  13356. var token = this.consume();
  13357. if (!token.identifier) {
  13358. this.throwError('is not a valid identifier', token);
  13359. }
  13360. return { type: AST.Identifier, name: token.text };
  13361. },
  13362. constant: function() {
  13363. // TODO check that it is a constant
  13364. return { type: AST.Literal, value: this.consume().value };
  13365. },
  13366. arrayDeclaration: function() {
  13367. var elements = [];
  13368. if (this.peekToken().text !== ']') {
  13369. do {
  13370. if (this.peek(']')) {
  13371. // Support trailing commas per ES5.1.
  13372. break;
  13373. }
  13374. elements.push(this.expression());
  13375. } while (this.expect(','));
  13376. }
  13377. this.consume(']');
  13378. return { type: AST.ArrayExpression, elements: elements };
  13379. },
  13380. object: function() {
  13381. var properties = [], property;
  13382. if (this.peekToken().text !== '}') {
  13383. do {
  13384. if (this.peek('}')) {
  13385. // Support trailing commas per ES5.1.
  13386. break;
  13387. }
  13388. property = {type: AST.Property, kind: 'init'};
  13389. if (this.peek().constant) {
  13390. property.key = this.constant();
  13391. property.computed = false;
  13392. this.consume(':');
  13393. property.value = this.expression();
  13394. } else if (this.peek().identifier) {
  13395. property.key = this.identifier();
  13396. property.computed = false;
  13397. if (this.peek(':')) {
  13398. this.consume(':');
  13399. property.value = this.expression();
  13400. } else {
  13401. property.value = property.key;
  13402. }
  13403. } else if (this.peek('[')) {
  13404. this.consume('[');
  13405. property.key = this.expression();
  13406. this.consume(']');
  13407. property.computed = true;
  13408. this.consume(':');
  13409. property.value = this.expression();
  13410. } else {
  13411. this.throwError('invalid key', this.peek());
  13412. }
  13413. properties.push(property);
  13414. } while (this.expect(','));
  13415. }
  13416. this.consume('}');
  13417. return {type: AST.ObjectExpression, properties: properties };
  13418. },
  13419. throwError: function(msg, token) {
  13420. throw $parseMinErr('syntax',
  13421. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13422. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13423. },
  13424. consume: function(e1) {
  13425. if (this.tokens.length === 0) {
  13426. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13427. }
  13428. var token = this.expect(e1);
  13429. if (!token) {
  13430. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13431. }
  13432. return token;
  13433. },
  13434. peekToken: function() {
  13435. if (this.tokens.length === 0) {
  13436. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13437. }
  13438. return this.tokens[0];
  13439. },
  13440. peek: function(e1, e2, e3, e4) {
  13441. return this.peekAhead(0, e1, e2, e3, e4);
  13442. },
  13443. peekAhead: function(i, e1, e2, e3, e4) {
  13444. if (this.tokens.length > i) {
  13445. var token = this.tokens[i];
  13446. var t = token.text;
  13447. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13448. (!e1 && !e2 && !e3 && !e4)) {
  13449. return token;
  13450. }
  13451. }
  13452. return false;
  13453. },
  13454. expect: function(e1, e2, e3, e4) {
  13455. var token = this.peek(e1, e2, e3, e4);
  13456. if (token) {
  13457. this.tokens.shift();
  13458. return token;
  13459. }
  13460. return false;
  13461. },
  13462. selfReferential: {
  13463. 'this': {type: AST.ThisExpression },
  13464. '$locals': {type: AST.LocalsExpression }
  13465. }
  13466. };
  13467. function ifDefined(v, d) {
  13468. return typeof v !== 'undefined' ? v : d;
  13469. }
  13470. function plusFn(l, r) {
  13471. if (typeof l === 'undefined') return r;
  13472. if (typeof r === 'undefined') return l;
  13473. return l + r;
  13474. }
  13475. function isStateless($filter, filterName) {
  13476. var fn = $filter(filterName);
  13477. return !fn.$stateful;
  13478. }
  13479. function findConstantAndWatchExpressions(ast, $filter) {
  13480. var allConstants;
  13481. var argsToWatch;
  13482. var isStatelessFilter;
  13483. switch (ast.type) {
  13484. case AST.Program:
  13485. allConstants = true;
  13486. forEach(ast.body, function(expr) {
  13487. findConstantAndWatchExpressions(expr.expression, $filter);
  13488. allConstants = allConstants && expr.expression.constant;
  13489. });
  13490. ast.constant = allConstants;
  13491. break;
  13492. case AST.Literal:
  13493. ast.constant = true;
  13494. ast.toWatch = [];
  13495. break;
  13496. case AST.UnaryExpression:
  13497. findConstantAndWatchExpressions(ast.argument, $filter);
  13498. ast.constant = ast.argument.constant;
  13499. ast.toWatch = ast.argument.toWatch;
  13500. break;
  13501. case AST.BinaryExpression:
  13502. findConstantAndWatchExpressions(ast.left, $filter);
  13503. findConstantAndWatchExpressions(ast.right, $filter);
  13504. ast.constant = ast.left.constant && ast.right.constant;
  13505. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13506. break;
  13507. case AST.LogicalExpression:
  13508. findConstantAndWatchExpressions(ast.left, $filter);
  13509. findConstantAndWatchExpressions(ast.right, $filter);
  13510. ast.constant = ast.left.constant && ast.right.constant;
  13511. ast.toWatch = ast.constant ? [] : [ast];
  13512. break;
  13513. case AST.ConditionalExpression:
  13514. findConstantAndWatchExpressions(ast.test, $filter);
  13515. findConstantAndWatchExpressions(ast.alternate, $filter);
  13516. findConstantAndWatchExpressions(ast.consequent, $filter);
  13517. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13518. ast.toWatch = ast.constant ? [] : [ast];
  13519. break;
  13520. case AST.Identifier:
  13521. ast.constant = false;
  13522. ast.toWatch = [ast];
  13523. break;
  13524. case AST.MemberExpression:
  13525. findConstantAndWatchExpressions(ast.object, $filter);
  13526. if (ast.computed) {
  13527. findConstantAndWatchExpressions(ast.property, $filter);
  13528. }
  13529. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13530. ast.toWatch = [ast];
  13531. break;
  13532. case AST.CallExpression:
  13533. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13534. allConstants = isStatelessFilter;
  13535. argsToWatch = [];
  13536. forEach(ast.arguments, function(expr) {
  13537. findConstantAndWatchExpressions(expr, $filter);
  13538. allConstants = allConstants && expr.constant;
  13539. if (!expr.constant) {
  13540. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13541. }
  13542. });
  13543. ast.constant = allConstants;
  13544. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13545. break;
  13546. case AST.AssignmentExpression:
  13547. findConstantAndWatchExpressions(ast.left, $filter);
  13548. findConstantAndWatchExpressions(ast.right, $filter);
  13549. ast.constant = ast.left.constant && ast.right.constant;
  13550. ast.toWatch = [ast];
  13551. break;
  13552. case AST.ArrayExpression:
  13553. allConstants = true;
  13554. argsToWatch = [];
  13555. forEach(ast.elements, function(expr) {
  13556. findConstantAndWatchExpressions(expr, $filter);
  13557. allConstants = allConstants && expr.constant;
  13558. if (!expr.constant) {
  13559. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13560. }
  13561. });
  13562. ast.constant = allConstants;
  13563. ast.toWatch = argsToWatch;
  13564. break;
  13565. case AST.ObjectExpression:
  13566. allConstants = true;
  13567. argsToWatch = [];
  13568. forEach(ast.properties, function(property) {
  13569. findConstantAndWatchExpressions(property.value, $filter);
  13570. allConstants = allConstants && property.value.constant && !property.computed;
  13571. if (!property.value.constant) {
  13572. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13573. }
  13574. });
  13575. ast.constant = allConstants;
  13576. ast.toWatch = argsToWatch;
  13577. break;
  13578. case AST.ThisExpression:
  13579. ast.constant = false;
  13580. ast.toWatch = [];
  13581. break;
  13582. case AST.LocalsExpression:
  13583. ast.constant = false;
  13584. ast.toWatch = [];
  13585. break;
  13586. }
  13587. }
  13588. function getInputs(body) {
  13589. if (body.length !== 1) return;
  13590. var lastExpression = body[0].expression;
  13591. var candidate = lastExpression.toWatch;
  13592. if (candidate.length !== 1) return candidate;
  13593. return candidate[0] !== lastExpression ? candidate : undefined;
  13594. }
  13595. function isAssignable(ast) {
  13596. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13597. }
  13598. function assignableAST(ast) {
  13599. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13600. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13601. }
  13602. }
  13603. function isLiteral(ast) {
  13604. return ast.body.length === 0 ||
  13605. ast.body.length === 1 && (
  13606. ast.body[0].expression.type === AST.Literal ||
  13607. ast.body[0].expression.type === AST.ArrayExpression ||
  13608. ast.body[0].expression.type === AST.ObjectExpression);
  13609. }
  13610. function isConstant(ast) {
  13611. return ast.constant;
  13612. }
  13613. function ASTCompiler(astBuilder, $filter) {
  13614. this.astBuilder = astBuilder;
  13615. this.$filter = $filter;
  13616. }
  13617. ASTCompiler.prototype = {
  13618. compile: function(expression) {
  13619. var self = this;
  13620. var ast = this.astBuilder.ast(expression);
  13621. this.state = {
  13622. nextId: 0,
  13623. filters: {},
  13624. fn: {vars: [], body: [], own: {}},
  13625. assign: {vars: [], body: [], own: {}},
  13626. inputs: []
  13627. };
  13628. findConstantAndWatchExpressions(ast, self.$filter);
  13629. var extra = '';
  13630. var assignable;
  13631. this.stage = 'assign';
  13632. if ((assignable = assignableAST(ast))) {
  13633. this.state.computing = 'assign';
  13634. var result = this.nextId();
  13635. this.recurse(assignable, result);
  13636. this.return_(result);
  13637. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13638. }
  13639. var toWatch = getInputs(ast.body);
  13640. self.stage = 'inputs';
  13641. forEach(toWatch, function(watch, key) {
  13642. var fnKey = 'fn' + key;
  13643. self.state[fnKey] = {vars: [], body: [], own: {}};
  13644. self.state.computing = fnKey;
  13645. var intoId = self.nextId();
  13646. self.recurse(watch, intoId);
  13647. self.return_(intoId);
  13648. self.state.inputs.push(fnKey);
  13649. watch.watchId = key;
  13650. });
  13651. this.state.computing = 'fn';
  13652. this.stage = 'main';
  13653. this.recurse(ast);
  13654. var fnString =
  13655. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13656. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13657. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13658. this.filterPrefix() +
  13659. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13660. extra +
  13661. this.watchFns() +
  13662. 'return fn;';
  13663. // eslint-disable-next-line no-new-func
  13664. var fn = (new Function('$filter',
  13665. 'getStringValue',
  13666. 'ifDefined',
  13667. 'plus',
  13668. fnString))(
  13669. this.$filter,
  13670. getStringValue,
  13671. ifDefined,
  13672. plusFn);
  13673. this.state = this.stage = undefined;
  13674. fn.literal = isLiteral(ast);
  13675. fn.constant = isConstant(ast);
  13676. return fn;
  13677. },
  13678. USE: 'use',
  13679. STRICT: 'strict',
  13680. watchFns: function() {
  13681. var result = [];
  13682. var fns = this.state.inputs;
  13683. var self = this;
  13684. forEach(fns, function(name) {
  13685. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13686. });
  13687. if (fns.length) {
  13688. result.push('fn.inputs=[' + fns.join(',') + '];');
  13689. }
  13690. return result.join('');
  13691. },
  13692. generateFunction: function(name, params) {
  13693. return 'function(' + params + '){' +
  13694. this.varsPrefix(name) +
  13695. this.body(name) +
  13696. '};';
  13697. },
  13698. filterPrefix: function() {
  13699. var parts = [];
  13700. var self = this;
  13701. forEach(this.state.filters, function(id, filter) {
  13702. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13703. });
  13704. if (parts.length) return 'var ' + parts.join(',') + ';';
  13705. return '';
  13706. },
  13707. varsPrefix: function(section) {
  13708. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13709. },
  13710. body: function(section) {
  13711. return this.state[section].body.join('');
  13712. },
  13713. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13714. var left, right, self = this, args, expression, computed;
  13715. recursionFn = recursionFn || noop;
  13716. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13717. intoId = intoId || this.nextId();
  13718. this.if_('i',
  13719. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13720. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13721. );
  13722. return;
  13723. }
  13724. switch (ast.type) {
  13725. case AST.Program:
  13726. forEach(ast.body, function(expression, pos) {
  13727. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13728. if (pos !== ast.body.length - 1) {
  13729. self.current().body.push(right, ';');
  13730. } else {
  13731. self.return_(right);
  13732. }
  13733. });
  13734. break;
  13735. case AST.Literal:
  13736. expression = this.escape(ast.value);
  13737. this.assign(intoId, expression);
  13738. recursionFn(intoId || expression);
  13739. break;
  13740. case AST.UnaryExpression:
  13741. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13742. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13743. this.assign(intoId, expression);
  13744. recursionFn(expression);
  13745. break;
  13746. case AST.BinaryExpression:
  13747. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13748. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13749. if (ast.operator === '+') {
  13750. expression = this.plus(left, right);
  13751. } else if (ast.operator === '-') {
  13752. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13753. } else {
  13754. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13755. }
  13756. this.assign(intoId, expression);
  13757. recursionFn(expression);
  13758. break;
  13759. case AST.LogicalExpression:
  13760. intoId = intoId || this.nextId();
  13761. self.recurse(ast.left, intoId);
  13762. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13763. recursionFn(intoId);
  13764. break;
  13765. case AST.ConditionalExpression:
  13766. intoId = intoId || this.nextId();
  13767. self.recurse(ast.test, intoId);
  13768. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13769. recursionFn(intoId);
  13770. break;
  13771. case AST.Identifier:
  13772. intoId = intoId || this.nextId();
  13773. if (nameId) {
  13774. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13775. nameId.computed = false;
  13776. nameId.name = ast.name;
  13777. }
  13778. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13779. function() {
  13780. self.if_(self.stage === 'inputs' || 's', function() {
  13781. if (create && create !== 1) {
  13782. self.if_(
  13783. self.isNull(self.nonComputedMember('s', ast.name)),
  13784. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13785. }
  13786. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13787. });
  13788. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13789. );
  13790. recursionFn(intoId);
  13791. break;
  13792. case AST.MemberExpression:
  13793. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13794. intoId = intoId || this.nextId();
  13795. self.recurse(ast.object, left, undefined, function() {
  13796. self.if_(self.notNull(left), function() {
  13797. if (ast.computed) {
  13798. right = self.nextId();
  13799. self.recurse(ast.property, right);
  13800. self.getStringValue(right);
  13801. if (create && create !== 1) {
  13802. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13803. }
  13804. expression = self.computedMember(left, right);
  13805. self.assign(intoId, expression);
  13806. if (nameId) {
  13807. nameId.computed = true;
  13808. nameId.name = right;
  13809. }
  13810. } else {
  13811. if (create && create !== 1) {
  13812. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13813. }
  13814. expression = self.nonComputedMember(left, ast.property.name);
  13815. self.assign(intoId, expression);
  13816. if (nameId) {
  13817. nameId.computed = false;
  13818. nameId.name = ast.property.name;
  13819. }
  13820. }
  13821. }, function() {
  13822. self.assign(intoId, 'undefined');
  13823. });
  13824. recursionFn(intoId);
  13825. }, !!create);
  13826. break;
  13827. case AST.CallExpression:
  13828. intoId = intoId || this.nextId();
  13829. if (ast.filter) {
  13830. right = self.filter(ast.callee.name);
  13831. args = [];
  13832. forEach(ast.arguments, function(expr) {
  13833. var argument = self.nextId();
  13834. self.recurse(expr, argument);
  13835. args.push(argument);
  13836. });
  13837. expression = right + '(' + args.join(',') + ')';
  13838. self.assign(intoId, expression);
  13839. recursionFn(intoId);
  13840. } else {
  13841. right = self.nextId();
  13842. left = {};
  13843. args = [];
  13844. self.recurse(ast.callee, right, left, function() {
  13845. self.if_(self.notNull(right), function() {
  13846. forEach(ast.arguments, function(expr) {
  13847. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13848. args.push(argument);
  13849. });
  13850. });
  13851. if (left.name) {
  13852. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13853. } else {
  13854. expression = right + '(' + args.join(',') + ')';
  13855. }
  13856. self.assign(intoId, expression);
  13857. }, function() {
  13858. self.assign(intoId, 'undefined');
  13859. });
  13860. recursionFn(intoId);
  13861. });
  13862. }
  13863. break;
  13864. case AST.AssignmentExpression:
  13865. right = this.nextId();
  13866. left = {};
  13867. this.recurse(ast.left, undefined, left, function() {
  13868. self.if_(self.notNull(left.context), function() {
  13869. self.recurse(ast.right, right);
  13870. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13871. self.assign(intoId, expression);
  13872. recursionFn(intoId || expression);
  13873. });
  13874. }, 1);
  13875. break;
  13876. case AST.ArrayExpression:
  13877. args = [];
  13878. forEach(ast.elements, function(expr) {
  13879. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13880. args.push(argument);
  13881. });
  13882. });
  13883. expression = '[' + args.join(',') + ']';
  13884. this.assign(intoId, expression);
  13885. recursionFn(intoId || expression);
  13886. break;
  13887. case AST.ObjectExpression:
  13888. args = [];
  13889. computed = false;
  13890. forEach(ast.properties, function(property) {
  13891. if (property.computed) {
  13892. computed = true;
  13893. }
  13894. });
  13895. if (computed) {
  13896. intoId = intoId || this.nextId();
  13897. this.assign(intoId, '{}');
  13898. forEach(ast.properties, function(property) {
  13899. if (property.computed) {
  13900. left = self.nextId();
  13901. self.recurse(property.key, left);
  13902. } else {
  13903. left = property.key.type === AST.Identifier ?
  13904. property.key.name :
  13905. ('' + property.key.value);
  13906. }
  13907. right = self.nextId();
  13908. self.recurse(property.value, right);
  13909. self.assign(self.member(intoId, left, property.computed), right);
  13910. });
  13911. } else {
  13912. forEach(ast.properties, function(property) {
  13913. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  13914. args.push(self.escape(
  13915. property.key.type === AST.Identifier ? property.key.name :
  13916. ('' + property.key.value)) +
  13917. ':' + expr);
  13918. });
  13919. });
  13920. expression = '{' + args.join(',') + '}';
  13921. this.assign(intoId, expression);
  13922. }
  13923. recursionFn(intoId || expression);
  13924. break;
  13925. case AST.ThisExpression:
  13926. this.assign(intoId, 's');
  13927. recursionFn(intoId || 's');
  13928. break;
  13929. case AST.LocalsExpression:
  13930. this.assign(intoId, 'l');
  13931. recursionFn(intoId || 'l');
  13932. break;
  13933. case AST.NGValueParameter:
  13934. this.assign(intoId, 'v');
  13935. recursionFn(intoId || 'v');
  13936. break;
  13937. }
  13938. },
  13939. getHasOwnProperty: function(element, property) {
  13940. var key = element + '.' + property;
  13941. var own = this.current().own;
  13942. if (!own.hasOwnProperty(key)) {
  13943. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13944. }
  13945. return own[key];
  13946. },
  13947. assign: function(id, value) {
  13948. if (!id) return;
  13949. this.current().body.push(id, '=', value, ';');
  13950. return id;
  13951. },
  13952. filter: function(filterName) {
  13953. if (!this.state.filters.hasOwnProperty(filterName)) {
  13954. this.state.filters[filterName] = this.nextId(true);
  13955. }
  13956. return this.state.filters[filterName];
  13957. },
  13958. ifDefined: function(id, defaultValue) {
  13959. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13960. },
  13961. plus: function(left, right) {
  13962. return 'plus(' + left + ',' + right + ')';
  13963. },
  13964. return_: function(id) {
  13965. this.current().body.push('return ', id, ';');
  13966. },
  13967. if_: function(test, alternate, consequent) {
  13968. if (test === true) {
  13969. alternate();
  13970. } else {
  13971. var body = this.current().body;
  13972. body.push('if(', test, '){');
  13973. alternate();
  13974. body.push('}');
  13975. if (consequent) {
  13976. body.push('else{');
  13977. consequent();
  13978. body.push('}');
  13979. }
  13980. }
  13981. },
  13982. not: function(expression) {
  13983. return '!(' + expression + ')';
  13984. },
  13985. isNull: function(expression) {
  13986. return expression + '==null';
  13987. },
  13988. notNull: function(expression) {
  13989. return expression + '!=null';
  13990. },
  13991. nonComputedMember: function(left, right) {
  13992. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  13993. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  13994. if (SAFE_IDENTIFIER.test(right)) {
  13995. return left + '.' + right;
  13996. } else {
  13997. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  13998. }
  13999. },
  14000. computedMember: function(left, right) {
  14001. return left + '[' + right + ']';
  14002. },
  14003. member: function(left, right, computed) {
  14004. if (computed) return this.computedMember(left, right);
  14005. return this.nonComputedMember(left, right);
  14006. },
  14007. getStringValue: function(item) {
  14008. this.assign(item, 'getStringValue(' + item + ')');
  14009. },
  14010. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14011. var self = this;
  14012. return function() {
  14013. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14014. };
  14015. },
  14016. lazyAssign: function(id, value) {
  14017. var self = this;
  14018. return function() {
  14019. self.assign(id, value);
  14020. };
  14021. },
  14022. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14023. stringEscapeFn: function(c) {
  14024. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14025. },
  14026. escape: function(value) {
  14027. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14028. if (isNumber(value)) return value.toString();
  14029. if (value === true) return 'true';
  14030. if (value === false) return 'false';
  14031. if (value === null) return 'null';
  14032. if (typeof value === 'undefined') return 'undefined';
  14033. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14034. },
  14035. nextId: function(skip, init) {
  14036. var id = 'v' + (this.state.nextId++);
  14037. if (!skip) {
  14038. this.current().vars.push(id + (init ? '=' + init : ''));
  14039. }
  14040. return id;
  14041. },
  14042. current: function() {
  14043. return this.state[this.state.computing];
  14044. }
  14045. };
  14046. function ASTInterpreter(astBuilder, $filter) {
  14047. this.astBuilder = astBuilder;
  14048. this.$filter = $filter;
  14049. }
  14050. ASTInterpreter.prototype = {
  14051. compile: function(expression) {
  14052. var self = this;
  14053. var ast = this.astBuilder.ast(expression);
  14054. findConstantAndWatchExpressions(ast, self.$filter);
  14055. var assignable;
  14056. var assign;
  14057. if ((assignable = assignableAST(ast))) {
  14058. assign = this.recurse(assignable);
  14059. }
  14060. var toWatch = getInputs(ast.body);
  14061. var inputs;
  14062. if (toWatch) {
  14063. inputs = [];
  14064. forEach(toWatch, function(watch, key) {
  14065. var input = self.recurse(watch);
  14066. watch.input = input;
  14067. inputs.push(input);
  14068. watch.watchId = key;
  14069. });
  14070. }
  14071. var expressions = [];
  14072. forEach(ast.body, function(expression) {
  14073. expressions.push(self.recurse(expression.expression));
  14074. });
  14075. var fn = ast.body.length === 0 ? noop :
  14076. ast.body.length === 1 ? expressions[0] :
  14077. function(scope, locals) {
  14078. var lastValue;
  14079. forEach(expressions, function(exp) {
  14080. lastValue = exp(scope, locals);
  14081. });
  14082. return lastValue;
  14083. };
  14084. if (assign) {
  14085. fn.assign = function(scope, value, locals) {
  14086. return assign(scope, locals, value);
  14087. };
  14088. }
  14089. if (inputs) {
  14090. fn.inputs = inputs;
  14091. }
  14092. fn.literal = isLiteral(ast);
  14093. fn.constant = isConstant(ast);
  14094. return fn;
  14095. },
  14096. recurse: function(ast, context, create) {
  14097. var left, right, self = this, args;
  14098. if (ast.input) {
  14099. return this.inputs(ast.input, ast.watchId);
  14100. }
  14101. switch (ast.type) {
  14102. case AST.Literal:
  14103. return this.value(ast.value, context);
  14104. case AST.UnaryExpression:
  14105. right = this.recurse(ast.argument);
  14106. return this['unary' + ast.operator](right, context);
  14107. case AST.BinaryExpression:
  14108. left = this.recurse(ast.left);
  14109. right = this.recurse(ast.right);
  14110. return this['binary' + ast.operator](left, right, context);
  14111. case AST.LogicalExpression:
  14112. left = this.recurse(ast.left);
  14113. right = this.recurse(ast.right);
  14114. return this['binary' + ast.operator](left, right, context);
  14115. case AST.ConditionalExpression:
  14116. return this['ternary?:'](
  14117. this.recurse(ast.test),
  14118. this.recurse(ast.alternate),
  14119. this.recurse(ast.consequent),
  14120. context
  14121. );
  14122. case AST.Identifier:
  14123. return self.identifier(ast.name, context, create);
  14124. case AST.MemberExpression:
  14125. left = this.recurse(ast.object, false, !!create);
  14126. if (!ast.computed) {
  14127. right = ast.property.name;
  14128. }
  14129. if (ast.computed) right = this.recurse(ast.property);
  14130. return ast.computed ?
  14131. this.computedMember(left, right, context, create) :
  14132. this.nonComputedMember(left, right, context, create);
  14133. case AST.CallExpression:
  14134. args = [];
  14135. forEach(ast.arguments, function(expr) {
  14136. args.push(self.recurse(expr));
  14137. });
  14138. if (ast.filter) right = this.$filter(ast.callee.name);
  14139. if (!ast.filter) right = this.recurse(ast.callee, true);
  14140. return ast.filter ?
  14141. function(scope, locals, assign, inputs) {
  14142. var values = [];
  14143. for (var i = 0; i < args.length; ++i) {
  14144. values.push(args[i](scope, locals, assign, inputs));
  14145. }
  14146. var value = right.apply(undefined, values, inputs);
  14147. return context ? {context: undefined, name: undefined, value: value} : value;
  14148. } :
  14149. function(scope, locals, assign, inputs) {
  14150. var rhs = right(scope, locals, assign, inputs);
  14151. var value;
  14152. if (rhs.value != null) {
  14153. var values = [];
  14154. for (var i = 0; i < args.length; ++i) {
  14155. values.push(args[i](scope, locals, assign, inputs));
  14156. }
  14157. value = rhs.value.apply(rhs.context, values);
  14158. }
  14159. return context ? {value: value} : value;
  14160. };
  14161. case AST.AssignmentExpression:
  14162. left = this.recurse(ast.left, true, 1);
  14163. right = this.recurse(ast.right);
  14164. return function(scope, locals, assign, inputs) {
  14165. var lhs = left(scope, locals, assign, inputs);
  14166. var rhs = right(scope, locals, assign, inputs);
  14167. lhs.context[lhs.name] = rhs;
  14168. return context ? {value: rhs} : rhs;
  14169. };
  14170. case AST.ArrayExpression:
  14171. args = [];
  14172. forEach(ast.elements, function(expr) {
  14173. args.push(self.recurse(expr));
  14174. });
  14175. return function(scope, locals, assign, inputs) {
  14176. var value = [];
  14177. for (var i = 0; i < args.length; ++i) {
  14178. value.push(args[i](scope, locals, assign, inputs));
  14179. }
  14180. return context ? {value: value} : value;
  14181. };
  14182. case AST.ObjectExpression:
  14183. args = [];
  14184. forEach(ast.properties, function(property) {
  14185. if (property.computed) {
  14186. args.push({key: self.recurse(property.key),
  14187. computed: true,
  14188. value: self.recurse(property.value)
  14189. });
  14190. } else {
  14191. args.push({key: property.key.type === AST.Identifier ?
  14192. property.key.name :
  14193. ('' + property.key.value),
  14194. computed: false,
  14195. value: self.recurse(property.value)
  14196. });
  14197. }
  14198. });
  14199. return function(scope, locals, assign, inputs) {
  14200. var value = {};
  14201. for (var i = 0; i < args.length; ++i) {
  14202. if (args[i].computed) {
  14203. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14204. } else {
  14205. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14206. }
  14207. }
  14208. return context ? {value: value} : value;
  14209. };
  14210. case AST.ThisExpression:
  14211. return function(scope) {
  14212. return context ? {value: scope} : scope;
  14213. };
  14214. case AST.LocalsExpression:
  14215. return function(scope, locals) {
  14216. return context ? {value: locals} : locals;
  14217. };
  14218. case AST.NGValueParameter:
  14219. return function(scope, locals, assign) {
  14220. return context ? {value: assign} : assign;
  14221. };
  14222. }
  14223. },
  14224. 'unary+': function(argument, context) {
  14225. return function(scope, locals, assign, inputs) {
  14226. var arg = argument(scope, locals, assign, inputs);
  14227. if (isDefined(arg)) {
  14228. arg = +arg;
  14229. } else {
  14230. arg = 0;
  14231. }
  14232. return context ? {value: arg} : arg;
  14233. };
  14234. },
  14235. 'unary-': function(argument, context) {
  14236. return function(scope, locals, assign, inputs) {
  14237. var arg = argument(scope, locals, assign, inputs);
  14238. if (isDefined(arg)) {
  14239. arg = -arg;
  14240. } else {
  14241. arg = -0;
  14242. }
  14243. return context ? {value: arg} : arg;
  14244. };
  14245. },
  14246. 'unary!': function(argument, context) {
  14247. return function(scope, locals, assign, inputs) {
  14248. var arg = !argument(scope, locals, assign, inputs);
  14249. return context ? {value: arg} : arg;
  14250. };
  14251. },
  14252. 'binary+': function(left, right, context) {
  14253. return function(scope, locals, assign, inputs) {
  14254. var lhs = left(scope, locals, assign, inputs);
  14255. var rhs = right(scope, locals, assign, inputs);
  14256. var arg = plusFn(lhs, rhs);
  14257. return context ? {value: arg} : arg;
  14258. };
  14259. },
  14260. 'binary-': function(left, right, context) {
  14261. return function(scope, locals, assign, inputs) {
  14262. var lhs = left(scope, locals, assign, inputs);
  14263. var rhs = right(scope, locals, assign, inputs);
  14264. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14265. return context ? {value: arg} : arg;
  14266. };
  14267. },
  14268. 'binary*': function(left, right, context) {
  14269. return function(scope, locals, assign, inputs) {
  14270. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14271. return context ? {value: arg} : arg;
  14272. };
  14273. },
  14274. 'binary/': function(left, right, context) {
  14275. return function(scope, locals, assign, inputs) {
  14276. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14277. return context ? {value: arg} : arg;
  14278. };
  14279. },
  14280. 'binary%': function(left, right, context) {
  14281. return function(scope, locals, assign, inputs) {
  14282. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14283. return context ? {value: arg} : arg;
  14284. };
  14285. },
  14286. 'binary===': function(left, right, context) {
  14287. return function(scope, locals, assign, inputs) {
  14288. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14289. return context ? {value: arg} : arg;
  14290. };
  14291. },
  14292. 'binary!==': function(left, right, context) {
  14293. return function(scope, locals, assign, inputs) {
  14294. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14295. return context ? {value: arg} : arg;
  14296. };
  14297. },
  14298. 'binary==': function(left, right, context) {
  14299. return function(scope, locals, assign, inputs) {
  14300. // eslint-disable-next-line eqeqeq
  14301. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14302. return context ? {value: arg} : arg;
  14303. };
  14304. },
  14305. 'binary!=': function(left, right, context) {
  14306. return function(scope, locals, assign, inputs) {
  14307. // eslint-disable-next-line eqeqeq
  14308. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14309. return context ? {value: arg} : arg;
  14310. };
  14311. },
  14312. 'binary<': function(left, right, context) {
  14313. return function(scope, locals, assign, inputs) {
  14314. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14315. return context ? {value: arg} : arg;
  14316. };
  14317. },
  14318. 'binary>': function(left, right, context) {
  14319. return function(scope, locals, assign, inputs) {
  14320. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14321. return context ? {value: arg} : arg;
  14322. };
  14323. },
  14324. 'binary<=': function(left, right, context) {
  14325. return function(scope, locals, assign, inputs) {
  14326. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14327. return context ? {value: arg} : arg;
  14328. };
  14329. },
  14330. 'binary>=': function(left, right, context) {
  14331. return function(scope, locals, assign, inputs) {
  14332. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14333. return context ? {value: arg} : arg;
  14334. };
  14335. },
  14336. 'binary&&': function(left, right, context) {
  14337. return function(scope, locals, assign, inputs) {
  14338. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14339. return context ? {value: arg} : arg;
  14340. };
  14341. },
  14342. 'binary||': function(left, right, context) {
  14343. return function(scope, locals, assign, inputs) {
  14344. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14345. return context ? {value: arg} : arg;
  14346. };
  14347. },
  14348. 'ternary?:': function(test, alternate, consequent, context) {
  14349. return function(scope, locals, assign, inputs) {
  14350. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14351. return context ? {value: arg} : arg;
  14352. };
  14353. },
  14354. value: function(value, context) {
  14355. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14356. },
  14357. identifier: function(name, context, create) {
  14358. return function(scope, locals, assign, inputs) {
  14359. var base = locals && (name in locals) ? locals : scope;
  14360. if (create && create !== 1 && base && base[name] == null) {
  14361. base[name] = {};
  14362. }
  14363. var value = base ? base[name] : undefined;
  14364. if (context) {
  14365. return {context: base, name: name, value: value};
  14366. } else {
  14367. return value;
  14368. }
  14369. };
  14370. },
  14371. computedMember: function(left, right, context, create) {
  14372. return function(scope, locals, assign, inputs) {
  14373. var lhs = left(scope, locals, assign, inputs);
  14374. var rhs;
  14375. var value;
  14376. if (lhs != null) {
  14377. rhs = right(scope, locals, assign, inputs);
  14378. rhs = getStringValue(rhs);
  14379. if (create && create !== 1) {
  14380. if (lhs && !(lhs[rhs])) {
  14381. lhs[rhs] = {};
  14382. }
  14383. }
  14384. value = lhs[rhs];
  14385. }
  14386. if (context) {
  14387. return {context: lhs, name: rhs, value: value};
  14388. } else {
  14389. return value;
  14390. }
  14391. };
  14392. },
  14393. nonComputedMember: function(left, right, context, create) {
  14394. return function(scope, locals, assign, inputs) {
  14395. var lhs = left(scope, locals, assign, inputs);
  14396. if (create && create !== 1) {
  14397. if (lhs && lhs[right] == null) {
  14398. lhs[right] = {};
  14399. }
  14400. }
  14401. var value = lhs != null ? lhs[right] : undefined;
  14402. if (context) {
  14403. return {context: lhs, name: right, value: value};
  14404. } else {
  14405. return value;
  14406. }
  14407. };
  14408. },
  14409. inputs: function(input, watchId) {
  14410. return function(scope, value, locals, inputs) {
  14411. if (inputs) return inputs[watchId];
  14412. return input(scope, value, locals);
  14413. };
  14414. }
  14415. };
  14416. /**
  14417. * @constructor
  14418. */
  14419. var Parser = function Parser(lexer, $filter, options) {
  14420. this.lexer = lexer;
  14421. this.$filter = $filter;
  14422. this.options = options;
  14423. this.ast = new AST(lexer, options);
  14424. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  14425. new ASTCompiler(this.ast, $filter);
  14426. };
  14427. Parser.prototype = {
  14428. constructor: Parser,
  14429. parse: function(text) {
  14430. return this.astCompiler.compile(text);
  14431. }
  14432. };
  14433. function getValueOf(value) {
  14434. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14435. }
  14436. ///////////////////////////////////
  14437. /**
  14438. * @ngdoc service
  14439. * @name $parse
  14440. * @kind function
  14441. *
  14442. * @description
  14443. *
  14444. * Converts Angular {@link guide/expression expression} into a function.
  14445. *
  14446. * ```js
  14447. * var getter = $parse('user.name');
  14448. * var setter = getter.assign;
  14449. * var context = {user:{name:'angular'}};
  14450. * var locals = {user:{name:'local'}};
  14451. *
  14452. * expect(getter(context)).toEqual('angular');
  14453. * setter(context, 'newValue');
  14454. * expect(context.user.name).toEqual('newValue');
  14455. * expect(getter(context, locals)).toEqual('local');
  14456. * ```
  14457. *
  14458. *
  14459. * @param {string} expression String expression to compile.
  14460. * @returns {function(context, locals)} a function which represents the compiled expression:
  14461. *
  14462. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14463. * are evaluated against (typically a scope object).
  14464. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14465. * `context`.
  14466. *
  14467. * The returned function also has the following properties:
  14468. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14469. * literal.
  14470. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14471. * constant literals.
  14472. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14473. * set to a function to change its value on the given context.
  14474. *
  14475. */
  14476. /**
  14477. * @ngdoc provider
  14478. * @name $parseProvider
  14479. * @this
  14480. *
  14481. * @description
  14482. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14483. * service.
  14484. */
  14485. function $ParseProvider() {
  14486. var cache = createMap();
  14487. var literals = {
  14488. 'true': true,
  14489. 'false': false,
  14490. 'null': null,
  14491. 'undefined': undefined
  14492. };
  14493. var identStart, identContinue;
  14494. /**
  14495. * @ngdoc method
  14496. * @name $parseProvider#addLiteral
  14497. * @description
  14498. *
  14499. * Configure $parse service to add literal values that will be present as literal at expressions.
  14500. *
  14501. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14502. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14503. *
  14504. **/
  14505. this.addLiteral = function(literalName, literalValue) {
  14506. literals[literalName] = literalValue;
  14507. };
  14508. /**
  14509. * @ngdoc method
  14510. * @name $parseProvider#setIdentifierFns
  14511. *
  14512. * @description
  14513. *
  14514. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14515. * `identifierStart` will get called to know if a given character is a valid character to be the
  14516. * first character for an identifier. The function `identifierContinue` will get called to know if
  14517. * a given character is a valid character to be a follow-up identifier character. The functions
  14518. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14519. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14520. * mind that the `string` parameter can be two characters long depending on the character
  14521. * representation. It is expected for the function to return `true` or `false`, whether that
  14522. * character is allowed or not.
  14523. *
  14524. * Since this function will be called extensively, keep the implementation of these functions fast,
  14525. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14526. *
  14527. * @param {function=} identifierStart The function that will decide whether the given character is
  14528. * a valid identifier start character.
  14529. * @param {function=} identifierContinue The function that will decide whether the given character is
  14530. * a valid identifier continue character.
  14531. */
  14532. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14533. identStart = identifierStart;
  14534. identContinue = identifierContinue;
  14535. return this;
  14536. };
  14537. this.$get = ['$filter', function($filter) {
  14538. var noUnsafeEval = csp().noUnsafeEval;
  14539. var $parseOptions = {
  14540. csp: noUnsafeEval,
  14541. literals: copy(literals),
  14542. isIdentifierStart: isFunction(identStart) && identStart,
  14543. isIdentifierContinue: isFunction(identContinue) && identContinue
  14544. };
  14545. return $parse;
  14546. function $parse(exp, interceptorFn) {
  14547. var parsedExpression, oneTime, cacheKey;
  14548. switch (typeof exp) {
  14549. case 'string':
  14550. exp = exp.trim();
  14551. cacheKey = exp;
  14552. parsedExpression = cache[cacheKey];
  14553. if (!parsedExpression) {
  14554. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14555. oneTime = true;
  14556. exp = exp.substring(2);
  14557. }
  14558. var lexer = new Lexer($parseOptions);
  14559. var parser = new Parser(lexer, $filter, $parseOptions);
  14560. parsedExpression = parser.parse(exp);
  14561. if (parsedExpression.constant) {
  14562. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14563. } else if (oneTime) {
  14564. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14565. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14566. } else if (parsedExpression.inputs) {
  14567. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14568. }
  14569. cache[cacheKey] = parsedExpression;
  14570. }
  14571. return addInterceptor(parsedExpression, interceptorFn);
  14572. case 'function':
  14573. return addInterceptor(exp, interceptorFn);
  14574. default:
  14575. return addInterceptor(noop, interceptorFn);
  14576. }
  14577. }
  14578. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  14579. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14580. return newValue === oldValueOfValue;
  14581. }
  14582. if (typeof newValue === 'object') {
  14583. // attempt to convert the value to a primitive type
  14584. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14585. // be cheaply dirty-checked
  14586. newValue = getValueOf(newValue);
  14587. if (typeof newValue === 'object') {
  14588. // objects/arrays are not supported - deep-watching them would be too expensive
  14589. return false;
  14590. }
  14591. // fall-through to the primitive equality check
  14592. }
  14593. //Primitive or NaN
  14594. // eslint-disable-next-line no-self-compare
  14595. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14596. }
  14597. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14598. var inputExpressions = parsedExpression.inputs;
  14599. var lastResult;
  14600. if (inputExpressions.length === 1) {
  14601. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14602. inputExpressions = inputExpressions[0];
  14603. return scope.$watch(function expressionInputWatch(scope) {
  14604. var newInputValue = inputExpressions(scope);
  14605. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  14606. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14607. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14608. }
  14609. return lastResult;
  14610. }, listener, objectEquality, prettyPrintExpression);
  14611. }
  14612. var oldInputValueOfValues = [];
  14613. var oldInputValues = [];
  14614. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14615. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14616. oldInputValues[i] = null;
  14617. }
  14618. return scope.$watch(function expressionInputsWatch(scope) {
  14619. var changed = false;
  14620. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14621. var newInputValue = inputExpressions[i](scope);
  14622. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  14623. oldInputValues[i] = newInputValue;
  14624. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14625. }
  14626. }
  14627. if (changed) {
  14628. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14629. }
  14630. return lastResult;
  14631. }, listener, objectEquality, prettyPrintExpression);
  14632. }
  14633. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14634. var unwatch, lastValue;
  14635. if (parsedExpression.inputs) {
  14636. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14637. } else {
  14638. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14639. }
  14640. return unwatch;
  14641. function oneTimeWatch(scope) {
  14642. return parsedExpression(scope);
  14643. }
  14644. function oneTimeListener(value, old, scope) {
  14645. lastValue = value;
  14646. if (isFunction(listener)) {
  14647. listener(value, old, scope);
  14648. }
  14649. if (isDefined(value)) {
  14650. scope.$$postDigest(function() {
  14651. if (isDefined(lastValue)) {
  14652. unwatch();
  14653. }
  14654. });
  14655. }
  14656. }
  14657. }
  14658. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14659. var unwatch, lastValue;
  14660. unwatch = scope.$watch(function oneTimeWatch(scope) {
  14661. return parsedExpression(scope);
  14662. }, function oneTimeListener(value, old, scope) {
  14663. lastValue = value;
  14664. if (isFunction(listener)) {
  14665. listener(value, old, scope);
  14666. }
  14667. if (isAllDefined(value)) {
  14668. scope.$$postDigest(function() {
  14669. if (isAllDefined(lastValue)) unwatch();
  14670. });
  14671. }
  14672. }, objectEquality);
  14673. return unwatch;
  14674. function isAllDefined(value) {
  14675. var allDefined = true;
  14676. forEach(value, function(val) {
  14677. if (!isDefined(val)) allDefined = false;
  14678. });
  14679. return allDefined;
  14680. }
  14681. }
  14682. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14683. var unwatch = scope.$watch(function constantWatch(scope) {
  14684. unwatch();
  14685. return parsedExpression(scope);
  14686. }, listener, objectEquality);
  14687. return unwatch;
  14688. }
  14689. function addInterceptor(parsedExpression, interceptorFn) {
  14690. if (!interceptorFn) return parsedExpression;
  14691. var watchDelegate = parsedExpression.$$watchDelegate;
  14692. var useInputs = false;
  14693. var regularWatch =
  14694. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14695. watchDelegate !== oneTimeWatchDelegate;
  14696. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14697. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14698. return interceptorFn(value, scope, locals);
  14699. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14700. var value = parsedExpression(scope, locals, assign, inputs);
  14701. var result = interceptorFn(value, scope, locals);
  14702. // we only return the interceptor's result if the
  14703. // initial value is defined (for bind-once)
  14704. return isDefined(value) ? result : value;
  14705. };
  14706. // Propagate $$watchDelegates other then inputsWatchDelegate
  14707. useInputs = !parsedExpression.inputs;
  14708. if (parsedExpression.$$watchDelegate &&
  14709. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14710. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14711. fn.inputs = parsedExpression.inputs;
  14712. } else if (!interceptorFn.$stateful) {
  14713. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14714. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14715. fn.$$watchDelegate = inputsWatchDelegate;
  14716. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14717. }
  14718. return fn;
  14719. }
  14720. }];
  14721. }
  14722. /**
  14723. * @ngdoc service
  14724. * @name $q
  14725. * @requires $rootScope
  14726. *
  14727. * @description
  14728. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14729. * when they are done processing.
  14730. *
  14731. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  14732. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  14733. *
  14734. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14735. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14736. *
  14737. * # $q constructor
  14738. *
  14739. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14740. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14741. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14742. *
  14743. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14744. * available yet.
  14745. *
  14746. * It can be used like so:
  14747. *
  14748. * ```js
  14749. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14750. * // are available in the current lexical scope (they could have been injected or passed in).
  14751. *
  14752. * function asyncGreet(name) {
  14753. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14754. * return $q(function(resolve, reject) {
  14755. * setTimeout(function() {
  14756. * if (okToGreet(name)) {
  14757. * resolve('Hello, ' + name + '!');
  14758. * } else {
  14759. * reject('Greeting ' + name + ' is not allowed.');
  14760. * }
  14761. * }, 1000);
  14762. * });
  14763. * }
  14764. *
  14765. * var promise = asyncGreet('Robin Hood');
  14766. * promise.then(function(greeting) {
  14767. * alert('Success: ' + greeting);
  14768. * }, function(reason) {
  14769. * alert('Failed: ' + reason);
  14770. * });
  14771. * ```
  14772. *
  14773. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14774. *
  14775. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14776. *
  14777. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14778. *
  14779. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14780. * interface for interacting with an object that represents the result of an action that is
  14781. * performed asynchronously, and may or may not be finished at any given point in time.
  14782. *
  14783. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14784. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14785. *
  14786. * ```js
  14787. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14788. * // are available in the current lexical scope (they could have been injected or passed in).
  14789. *
  14790. * function asyncGreet(name) {
  14791. * var deferred = $q.defer();
  14792. *
  14793. * setTimeout(function() {
  14794. * deferred.notify('About to greet ' + name + '.');
  14795. *
  14796. * if (okToGreet(name)) {
  14797. * deferred.resolve('Hello, ' + name + '!');
  14798. * } else {
  14799. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14800. * }
  14801. * }, 1000);
  14802. *
  14803. * return deferred.promise;
  14804. * }
  14805. *
  14806. * var promise = asyncGreet('Robin Hood');
  14807. * promise.then(function(greeting) {
  14808. * alert('Success: ' + greeting);
  14809. * }, function(reason) {
  14810. * alert('Failed: ' + reason);
  14811. * }, function(update) {
  14812. * alert('Got notification: ' + update);
  14813. * });
  14814. * ```
  14815. *
  14816. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14817. * comes in the way of guarantees that promise and deferred APIs make, see
  14818. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14819. *
  14820. * Additionally the promise api allows for composition that is very hard to do with the
  14821. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14822. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14823. * section on serial or parallel joining of promises.
  14824. *
  14825. * # The Deferred API
  14826. *
  14827. * A new instance of deferred is constructed by calling `$q.defer()`.
  14828. *
  14829. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14830. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14831. * of the task.
  14832. *
  14833. * **Methods**
  14834. *
  14835. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14836. * constructed via `$q.reject`, the promise will be rejected instead.
  14837. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14838. * resolving it with a rejection constructed via `$q.reject`.
  14839. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14840. * multiple times before the promise is either resolved or rejected.
  14841. *
  14842. * **Properties**
  14843. *
  14844. * - promise – `{Promise}` – promise object associated with this deferred.
  14845. *
  14846. *
  14847. * # The Promise API
  14848. *
  14849. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14850. * calling `deferred.promise`.
  14851. *
  14852. * The purpose of the promise object is to allow for interested parties to get access to the result
  14853. * of the deferred task when it completes.
  14854. *
  14855. * **Methods**
  14856. *
  14857. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  14858. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14859. * as soon as the result is available. The callbacks are called with a single argument: the result
  14860. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14861. * provide a progress indication, before the promise is resolved or rejected.
  14862. *
  14863. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14864. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14865. * with the value which is resolved in that promise using
  14866. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14867. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14868. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  14869. * arguments are optional.
  14870. *
  14871. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14872. *
  14873. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14874. * but to do so without modifying the final value. This is useful to release resources or do some
  14875. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14876. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14877. * more information.
  14878. *
  14879. * # Chaining promises
  14880. *
  14881. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14882. * possible to create a chain of promises:
  14883. *
  14884. * ```js
  14885. * promiseB = promiseA.then(function(result) {
  14886. * return result + 1;
  14887. * });
  14888. *
  14889. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14890. * // will be the result of promiseA incremented by 1
  14891. * ```
  14892. *
  14893. * It is possible to create chains of any length and since a promise can be resolved with another
  14894. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14895. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14896. * $http's response interceptors.
  14897. *
  14898. *
  14899. * # Differences between Kris Kowal's Q and $q
  14900. *
  14901. * There are two main differences:
  14902. *
  14903. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14904. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14905. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14906. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14907. * all the important functionality needed for common async tasks.
  14908. *
  14909. * # Testing
  14910. *
  14911. * ```js
  14912. * it('should simulate promise', inject(function($q, $rootScope) {
  14913. * var deferred = $q.defer();
  14914. * var promise = deferred.promise;
  14915. * var resolvedValue;
  14916. *
  14917. * promise.then(function(value) { resolvedValue = value; });
  14918. * expect(resolvedValue).toBeUndefined();
  14919. *
  14920. * // Simulate resolving of promise
  14921. * deferred.resolve(123);
  14922. * // Note that the 'then' function does not get called synchronously.
  14923. * // This is because we want the promise API to always be async, whether or not
  14924. * // it got called synchronously or asynchronously.
  14925. * expect(resolvedValue).toBeUndefined();
  14926. *
  14927. * // Propagate promise resolution to 'then' functions using $apply().
  14928. * $rootScope.$apply();
  14929. * expect(resolvedValue).toEqual(123);
  14930. * }));
  14931. * ```
  14932. *
  14933. * @param {function(function, function)} resolver Function which is responsible for resolving or
  14934. * rejecting the newly created promise. The first parameter is a function which resolves the
  14935. * promise, the second parameter is a function which rejects the promise.
  14936. *
  14937. * @returns {Promise} The newly created promise.
  14938. */
  14939. /**
  14940. * @ngdoc provider
  14941. * @name $qProvider
  14942. * @this
  14943. *
  14944. * @description
  14945. */
  14946. function $QProvider() {
  14947. var errorOnUnhandledRejections = true;
  14948. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  14949. return qFactory(function(callback) {
  14950. $rootScope.$evalAsync(callback);
  14951. }, $exceptionHandler, errorOnUnhandledRejections);
  14952. }];
  14953. /**
  14954. * @ngdoc method
  14955. * @name $qProvider#errorOnUnhandledRejections
  14956. * @kind function
  14957. *
  14958. * @description
  14959. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  14960. * This feature is enabled by default.
  14961. *
  14962. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  14963. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  14964. * chaining otherwise.
  14965. */
  14966. this.errorOnUnhandledRejections = function(value) {
  14967. if (isDefined(value)) {
  14968. errorOnUnhandledRejections = value;
  14969. return this;
  14970. } else {
  14971. return errorOnUnhandledRejections;
  14972. }
  14973. };
  14974. }
  14975. /** @this */
  14976. function $$QProvider() {
  14977. var errorOnUnhandledRejections = true;
  14978. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  14979. return qFactory(function(callback) {
  14980. $browser.defer(callback);
  14981. }, $exceptionHandler, errorOnUnhandledRejections);
  14982. }];
  14983. this.errorOnUnhandledRejections = function(value) {
  14984. if (isDefined(value)) {
  14985. errorOnUnhandledRejections = value;
  14986. return this;
  14987. } else {
  14988. return errorOnUnhandledRejections;
  14989. }
  14990. };
  14991. }
  14992. /**
  14993. * Constructs a promise manager.
  14994. *
  14995. * @param {function(function)} nextTick Function for executing functions in the next turn.
  14996. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  14997. * debugging purposes.
  14998. @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
  14999. * promises rejections.
  15000. * @returns {object} Promise manager.
  15001. */
  15002. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15003. var $qMinErr = minErr('$q', TypeError);
  15004. var queueSize = 0;
  15005. var checkQueue = [];
  15006. /**
  15007. * @ngdoc method
  15008. * @name ng.$q#defer
  15009. * @kind function
  15010. *
  15011. * @description
  15012. * Creates a `Deferred` object which represents a task which will finish in the future.
  15013. *
  15014. * @returns {Deferred} Returns a new instance of deferred.
  15015. */
  15016. function defer() {
  15017. return new Deferred();
  15018. }
  15019. function Deferred() {
  15020. var promise = this.promise = new Promise();
  15021. //Non prototype methods necessary to support unbound execution :/
  15022. this.resolve = function(val) { resolvePromise(promise, val); };
  15023. this.reject = function(reason) { rejectPromise(promise, reason); };
  15024. this.notify = function(progress) { notifyPromise(promise, progress); };
  15025. }
  15026. function Promise() {
  15027. this.$$state = { status: 0 };
  15028. }
  15029. extend(Promise.prototype, {
  15030. then: function(onFulfilled, onRejected, progressBack) {
  15031. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15032. return this;
  15033. }
  15034. var result = new Promise();
  15035. this.$$state.pending = this.$$state.pending || [];
  15036. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15037. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15038. return result;
  15039. },
  15040. 'catch': function(callback) {
  15041. return this.then(null, callback);
  15042. },
  15043. 'finally': function(callback, progressBack) {
  15044. return this.then(function(value) {
  15045. return handleCallback(value, resolve, callback);
  15046. }, function(error) {
  15047. return handleCallback(error, reject, callback);
  15048. }, progressBack);
  15049. }
  15050. });
  15051. function processQueue(state) {
  15052. var fn, promise, pending;
  15053. pending = state.pending;
  15054. state.processScheduled = false;
  15055. state.pending = undefined;
  15056. try {
  15057. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15058. state.pur = true;
  15059. promise = pending[i][0];
  15060. fn = pending[i][state.status];
  15061. try {
  15062. if (isFunction(fn)) {
  15063. resolvePromise(promise, fn(state.value));
  15064. } else if (state.status === 1) {
  15065. resolvePromise(promise, state.value);
  15066. } else {
  15067. rejectPromise(promise, state.value);
  15068. }
  15069. } catch (e) {
  15070. rejectPromise(promise, e);
  15071. }
  15072. }
  15073. } finally {
  15074. --queueSize;
  15075. if (errorOnUnhandledRejections && queueSize === 0) {
  15076. nextTick(processChecks);
  15077. }
  15078. }
  15079. }
  15080. function processChecks() {
  15081. // eslint-disable-next-line no-unmodified-loop-condition
  15082. while (!queueSize && checkQueue.length) {
  15083. var toCheck = checkQueue.shift();
  15084. if (!toCheck.pur) {
  15085. toCheck.pur = true;
  15086. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15087. if (toCheck.value instanceof Error) {
  15088. exceptionHandler(toCheck.value, errorMessage);
  15089. } else {
  15090. exceptionHandler(errorMessage);
  15091. }
  15092. }
  15093. }
  15094. }
  15095. function scheduleProcessQueue(state) {
  15096. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
  15097. if (queueSize === 0 && checkQueue.length === 0) {
  15098. nextTick(processChecks);
  15099. }
  15100. checkQueue.push(state);
  15101. }
  15102. if (state.processScheduled || !state.pending) return;
  15103. state.processScheduled = true;
  15104. ++queueSize;
  15105. nextTick(function() { processQueue(state); });
  15106. }
  15107. function resolvePromise(promise, val) {
  15108. if (promise.$$state.status) return;
  15109. if (val === promise) {
  15110. $$reject(promise, $qMinErr(
  15111. 'qcycle',
  15112. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15113. val));
  15114. } else {
  15115. $$resolve(promise, val);
  15116. }
  15117. }
  15118. function $$resolve(promise, val) {
  15119. var then;
  15120. var done = false;
  15121. try {
  15122. if (isObject(val) || isFunction(val)) then = val.then;
  15123. if (isFunction(then)) {
  15124. promise.$$state.status = -1;
  15125. then.call(val, doResolve, doReject, doNotify);
  15126. } else {
  15127. promise.$$state.value = val;
  15128. promise.$$state.status = 1;
  15129. scheduleProcessQueue(promise.$$state);
  15130. }
  15131. } catch (e) {
  15132. doReject(e);
  15133. }
  15134. function doResolve(val) {
  15135. if (done) return;
  15136. done = true;
  15137. $$resolve(promise, val);
  15138. }
  15139. function doReject(val) {
  15140. if (done) return;
  15141. done = true;
  15142. $$reject(promise, val);
  15143. }
  15144. function doNotify(progress) {
  15145. notifyPromise(promise, progress);
  15146. }
  15147. }
  15148. function rejectPromise(promise, reason) {
  15149. if (promise.$$state.status) return;
  15150. $$reject(promise, reason);
  15151. }
  15152. function $$reject(promise, reason) {
  15153. promise.$$state.value = reason;
  15154. promise.$$state.status = 2;
  15155. scheduleProcessQueue(promise.$$state);
  15156. }
  15157. function notifyPromise(promise, progress) {
  15158. var callbacks = promise.$$state.pending;
  15159. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15160. nextTick(function() {
  15161. var callback, result;
  15162. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15163. result = callbacks[i][0];
  15164. callback = callbacks[i][3];
  15165. try {
  15166. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15167. } catch (e) {
  15168. exceptionHandler(e);
  15169. }
  15170. }
  15171. });
  15172. }
  15173. }
  15174. /**
  15175. * @ngdoc method
  15176. * @name $q#reject
  15177. * @kind function
  15178. *
  15179. * @description
  15180. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15181. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15182. * a promise chain, you don't need to worry about it.
  15183. *
  15184. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15185. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15186. * a promise error callback and you want to forward the error to the promise derived from the
  15187. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15188. * `reject`.
  15189. *
  15190. * ```js
  15191. * promiseB = promiseA.then(function(result) {
  15192. * // success: do something and resolve promiseB
  15193. * // with the old or a new result
  15194. * return result;
  15195. * }, function(reason) {
  15196. * // error: handle the error if possible and
  15197. * // resolve promiseB with newPromiseOrValue,
  15198. * // otherwise forward the rejection to promiseB
  15199. * if (canHandle(reason)) {
  15200. * // handle the error and recover
  15201. * return newPromiseOrValue;
  15202. * }
  15203. * return $q.reject(reason);
  15204. * });
  15205. * ```
  15206. *
  15207. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15208. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15209. */
  15210. function reject(reason) {
  15211. var result = new Promise();
  15212. rejectPromise(result, reason);
  15213. return result;
  15214. }
  15215. function handleCallback(value, resolver, callback) {
  15216. var callbackOutput = null;
  15217. try {
  15218. if (isFunction(callback)) callbackOutput = callback();
  15219. } catch (e) {
  15220. return reject(e);
  15221. }
  15222. if (isPromiseLike(callbackOutput)) {
  15223. return callbackOutput.then(function() {
  15224. return resolver(value);
  15225. }, reject);
  15226. } else {
  15227. return resolver(value);
  15228. }
  15229. }
  15230. /**
  15231. * @ngdoc method
  15232. * @name $q#when
  15233. * @kind function
  15234. *
  15235. * @description
  15236. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15237. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15238. * the promise comes from a source that can't be trusted.
  15239. *
  15240. * @param {*} value Value or a promise
  15241. * @param {Function=} successCallback
  15242. * @param {Function=} errorCallback
  15243. * @param {Function=} progressCallback
  15244. * @returns {Promise} Returns a promise of the passed value or promise
  15245. */
  15246. function when(value, callback, errback, progressBack) {
  15247. var result = new Promise();
  15248. resolvePromise(result, value);
  15249. return result.then(callback, errback, progressBack);
  15250. }
  15251. /**
  15252. * @ngdoc method
  15253. * @name $q#resolve
  15254. * @kind function
  15255. *
  15256. * @description
  15257. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15258. *
  15259. * @param {*} value Value or a promise
  15260. * @param {Function=} successCallback
  15261. * @param {Function=} errorCallback
  15262. * @param {Function=} progressCallback
  15263. * @returns {Promise} Returns a promise of the passed value or promise
  15264. */
  15265. var resolve = when;
  15266. /**
  15267. * @ngdoc method
  15268. * @name $q#all
  15269. * @kind function
  15270. *
  15271. * @description
  15272. * Combines multiple promises into a single promise that is resolved when all of the input
  15273. * promises are resolved.
  15274. *
  15275. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15276. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15277. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15278. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15279. * with the same rejection value.
  15280. */
  15281. function all(promises) {
  15282. var result = new Promise(),
  15283. counter = 0,
  15284. results = isArray(promises) ? [] : {};
  15285. forEach(promises, function(promise, key) {
  15286. counter++;
  15287. when(promise).then(function(value) {
  15288. results[key] = value;
  15289. if (!(--counter)) resolvePromise(result, results);
  15290. }, function(reason) {
  15291. rejectPromise(result, reason);
  15292. });
  15293. });
  15294. if (counter === 0) {
  15295. resolvePromise(result, results);
  15296. }
  15297. return result;
  15298. }
  15299. /**
  15300. * @ngdoc method
  15301. * @name $q#race
  15302. * @kind function
  15303. *
  15304. * @description
  15305. * Returns a promise that resolves or rejects as soon as one of those promises
  15306. * resolves or rejects, with the value or reason from that promise.
  15307. *
  15308. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15309. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15310. * resolves or rejects, with the value or reason from that promise.
  15311. */
  15312. function race(promises) {
  15313. var deferred = defer();
  15314. forEach(promises, function(promise) {
  15315. when(promise).then(deferred.resolve, deferred.reject);
  15316. });
  15317. return deferred.promise;
  15318. }
  15319. function $Q(resolver) {
  15320. if (!isFunction(resolver)) {
  15321. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15322. }
  15323. var promise = new Promise();
  15324. function resolveFn(value) {
  15325. resolvePromise(promise, value);
  15326. }
  15327. function rejectFn(reason) {
  15328. rejectPromise(promise, reason);
  15329. }
  15330. resolver(resolveFn, rejectFn);
  15331. return promise;
  15332. }
  15333. // Let's make the instanceof operator work for promises, so that
  15334. // `new $q(fn) instanceof $q` would evaluate to true.
  15335. $Q.prototype = Promise.prototype;
  15336. $Q.defer = defer;
  15337. $Q.reject = reject;
  15338. $Q.when = when;
  15339. $Q.resolve = resolve;
  15340. $Q.all = all;
  15341. $Q.race = race;
  15342. return $Q;
  15343. }
  15344. /** @this */
  15345. function $$RAFProvider() { //rAF
  15346. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15347. var requestAnimationFrame = $window.requestAnimationFrame ||
  15348. $window.webkitRequestAnimationFrame;
  15349. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15350. $window.webkitCancelAnimationFrame ||
  15351. $window.webkitCancelRequestAnimationFrame;
  15352. var rafSupported = !!requestAnimationFrame;
  15353. var raf = rafSupported
  15354. ? function(fn) {
  15355. var id = requestAnimationFrame(fn);
  15356. return function() {
  15357. cancelAnimationFrame(id);
  15358. };
  15359. }
  15360. : function(fn) {
  15361. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15362. return function() {
  15363. $timeout.cancel(timer);
  15364. };
  15365. };
  15366. raf.supported = rafSupported;
  15367. return raf;
  15368. }];
  15369. }
  15370. /**
  15371. * DESIGN NOTES
  15372. *
  15373. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15374. *
  15375. * The typical use of scope is to watch the expressions, which most of the time return the same
  15376. * value as last time so we optimize the operation.
  15377. *
  15378. * Closures construction is expensive in terms of speed as well as memory:
  15379. * - No closures, instead use prototypical inheritance for API
  15380. * - Internal state needs to be stored on scope directly, which means that private state is
  15381. * exposed as $$____ properties
  15382. *
  15383. * Loop operations are optimized by using while(count--) { ... }
  15384. * - This means that in order to keep the same order of execution as addition we have to add
  15385. * items to the array at the beginning (unshift) instead of at the end (push)
  15386. *
  15387. * Child scopes are created and removed often
  15388. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15389. *
  15390. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15391. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15392. * to construct.
  15393. */
  15394. /**
  15395. * @ngdoc provider
  15396. * @name $rootScopeProvider
  15397. * @description
  15398. *
  15399. * Provider for the $rootScope service.
  15400. */
  15401. /**
  15402. * @ngdoc method
  15403. * @name $rootScopeProvider#digestTtl
  15404. * @description
  15405. *
  15406. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15407. * assuming that the model is unstable.
  15408. *
  15409. * The current default is 10 iterations.
  15410. *
  15411. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15412. * several digest iterations. However if an application needs more than the default 10 digest
  15413. * iterations for its model to stabilize then you should investigate what is causing the model to
  15414. * continuously change during the digest.
  15415. *
  15416. * Increasing the TTL could have performance implications, so you should not change it without
  15417. * proper justification.
  15418. *
  15419. * @param {number} limit The number of digest iterations.
  15420. */
  15421. /**
  15422. * @ngdoc service
  15423. * @name $rootScope
  15424. * @this
  15425. *
  15426. * @description
  15427. *
  15428. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15429. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15430. * between the model and the view, via a mechanism for watching the model for changes.
  15431. * They also provide event emission/broadcast and subscription facility. See the
  15432. * {@link guide/scope developer guide on scopes}.
  15433. */
  15434. function $RootScopeProvider() {
  15435. var TTL = 10;
  15436. var $rootScopeMinErr = minErr('$rootScope');
  15437. var lastDirtyWatch = null;
  15438. var applyAsyncId = null;
  15439. this.digestTtl = function(value) {
  15440. if (arguments.length) {
  15441. TTL = value;
  15442. }
  15443. return TTL;
  15444. };
  15445. function createChildScopeClass(parent) {
  15446. function ChildScope() {
  15447. this.$$watchers = this.$$nextSibling =
  15448. this.$$childHead = this.$$childTail = null;
  15449. this.$$listeners = {};
  15450. this.$$listenerCount = {};
  15451. this.$$watchersCount = 0;
  15452. this.$id = nextUid();
  15453. this.$$ChildScope = null;
  15454. }
  15455. ChildScope.prototype = parent;
  15456. return ChildScope;
  15457. }
  15458. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15459. function($exceptionHandler, $parse, $browser) {
  15460. function destroyChildScope($event) {
  15461. $event.currentScope.$$destroyed = true;
  15462. }
  15463. function cleanUpScope($scope) {
  15464. // Support: IE 9 only
  15465. if (msie === 9) {
  15466. // There is a memory leak in IE9 if all child scopes are not disconnected
  15467. // completely when a scope is destroyed. So this code will recurse up through
  15468. // all this scopes children
  15469. //
  15470. // See issue https://github.com/angular/angular.js/issues/10706
  15471. if ($scope.$$childHead) {
  15472. cleanUpScope($scope.$$childHead);
  15473. }
  15474. if ($scope.$$nextSibling) {
  15475. cleanUpScope($scope.$$nextSibling);
  15476. }
  15477. }
  15478. // The code below works around IE9 and V8's memory leaks
  15479. //
  15480. // See:
  15481. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15482. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15483. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15484. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15485. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15486. }
  15487. /**
  15488. * @ngdoc type
  15489. * @name $rootScope.Scope
  15490. *
  15491. * @description
  15492. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15493. * {@link auto.$injector $injector}. Child scopes are created using the
  15494. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15495. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15496. * an in-depth introduction and usage examples.
  15497. *
  15498. *
  15499. * # Inheritance
  15500. * A scope can inherit from a parent scope, as in this example:
  15501. * ```js
  15502. var parent = $rootScope;
  15503. var child = parent.$new();
  15504. parent.salutation = "Hello";
  15505. expect(child.salutation).toEqual('Hello');
  15506. child.salutation = "Welcome";
  15507. expect(child.salutation).toEqual('Welcome');
  15508. expect(parent.salutation).toEqual('Hello');
  15509. * ```
  15510. *
  15511. * When interacting with `Scope` in tests, additional helper methods are available on the
  15512. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15513. * details.
  15514. *
  15515. *
  15516. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15517. * provided for the current scope. Defaults to {@link ng}.
  15518. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15519. * append/override services provided by `providers`. This is handy
  15520. * when unit-testing and having the need to override a default
  15521. * service.
  15522. * @returns {Object} Newly created scope.
  15523. *
  15524. */
  15525. function Scope() {
  15526. this.$id = nextUid();
  15527. this.$$phase = this.$parent = this.$$watchers =
  15528. this.$$nextSibling = this.$$prevSibling =
  15529. this.$$childHead = this.$$childTail = null;
  15530. this.$root = this;
  15531. this.$$destroyed = false;
  15532. this.$$listeners = {};
  15533. this.$$listenerCount = {};
  15534. this.$$watchersCount = 0;
  15535. this.$$isolateBindings = null;
  15536. }
  15537. /**
  15538. * @ngdoc property
  15539. * @name $rootScope.Scope#$id
  15540. *
  15541. * @description
  15542. * Unique scope ID (monotonically increasing) useful for debugging.
  15543. */
  15544. /**
  15545. * @ngdoc property
  15546. * @name $rootScope.Scope#$parent
  15547. *
  15548. * @description
  15549. * Reference to the parent scope.
  15550. */
  15551. /**
  15552. * @ngdoc property
  15553. * @name $rootScope.Scope#$root
  15554. *
  15555. * @description
  15556. * Reference to the root scope.
  15557. */
  15558. Scope.prototype = {
  15559. constructor: Scope,
  15560. /**
  15561. * @ngdoc method
  15562. * @name $rootScope.Scope#$new
  15563. * @kind function
  15564. *
  15565. * @description
  15566. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15567. *
  15568. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15569. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15570. *
  15571. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15572. * desired for the scope and its child scopes to be permanently detached from the parent and
  15573. * thus stop participating in model change detection and listener notification by invoking.
  15574. *
  15575. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15576. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15577. * When creating widgets, it is useful for the widget to not accidentally read parent
  15578. * state.
  15579. *
  15580. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15581. * of the newly created scope. Defaults to `this` scope if not provided.
  15582. * This is used when creating a transclude scope to correctly place it
  15583. * in the scope hierarchy while maintaining the correct prototypical
  15584. * inheritance.
  15585. *
  15586. * @returns {Object} The newly created child scope.
  15587. *
  15588. */
  15589. $new: function(isolate, parent) {
  15590. var child;
  15591. parent = parent || this;
  15592. if (isolate) {
  15593. child = new Scope();
  15594. child.$root = this.$root;
  15595. } else {
  15596. // Only create a child scope class if somebody asks for one,
  15597. // but cache it to allow the VM to optimize lookups.
  15598. if (!this.$$ChildScope) {
  15599. this.$$ChildScope = createChildScopeClass(this);
  15600. }
  15601. child = new this.$$ChildScope();
  15602. }
  15603. child.$parent = parent;
  15604. child.$$prevSibling = parent.$$childTail;
  15605. if (parent.$$childHead) {
  15606. parent.$$childTail.$$nextSibling = child;
  15607. parent.$$childTail = child;
  15608. } else {
  15609. parent.$$childHead = parent.$$childTail = child;
  15610. }
  15611. // When the new scope is not isolated or we inherit from `this`, and
  15612. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15613. // prototypically. In all other cases, this property needs to be set
  15614. // when the parent scope is destroyed.
  15615. // The listener needs to be added after the parent is set
  15616. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15617. return child;
  15618. },
  15619. /**
  15620. * @ngdoc method
  15621. * @name $rootScope.Scope#$watch
  15622. * @kind function
  15623. *
  15624. * @description
  15625. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15626. *
  15627. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15628. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15629. * its value when executed multiple times with the same input because it may be executed multiple
  15630. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15631. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  15632. * - The `listener` is called only when the value from the current `watchExpression` and the
  15633. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15634. * see below). Inequality is determined according to reference inequality,
  15635. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15636. * via the `!==` Javascript operator, unless `objectEquality == true`
  15637. * (see next point)
  15638. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15639. * according to the {@link angular.equals} function. To save the value of the object for
  15640. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15641. * watching complex objects will have adverse memory and performance implications.
  15642. * - This should not be used to watch for changes in objects that are
  15643. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  15644. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15645. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15646. * iteration limit is 10 to prevent an infinite loop deadlock.
  15647. *
  15648. *
  15649. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15650. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15651. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15652. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15653. *
  15654. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15655. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15656. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15657. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15658. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15659. * listener was called due to initialization.
  15660. *
  15661. *
  15662. *
  15663. * # Example
  15664. * ```js
  15665. // let's assume that scope was dependency injected as the $rootScope
  15666. var scope = $rootScope;
  15667. scope.name = 'misko';
  15668. scope.counter = 0;
  15669. expect(scope.counter).toEqual(0);
  15670. scope.$watch('name', function(newValue, oldValue) {
  15671. scope.counter = scope.counter + 1;
  15672. });
  15673. expect(scope.counter).toEqual(0);
  15674. scope.$digest();
  15675. // the listener is always called during the first $digest loop after it was registered
  15676. expect(scope.counter).toEqual(1);
  15677. scope.$digest();
  15678. // but now it will not be called unless the value changes
  15679. expect(scope.counter).toEqual(1);
  15680. scope.name = 'adam';
  15681. scope.$digest();
  15682. expect(scope.counter).toEqual(2);
  15683. // Using a function as a watchExpression
  15684. var food;
  15685. scope.foodCounter = 0;
  15686. expect(scope.foodCounter).toEqual(0);
  15687. scope.$watch(
  15688. // This function returns the value being watched. It is called for each turn of the $digest loop
  15689. function() { return food; },
  15690. // This is the change listener, called when the value returned from the above function changes
  15691. function(newValue, oldValue) {
  15692. if ( newValue !== oldValue ) {
  15693. // Only increment the counter if the value changed
  15694. scope.foodCounter = scope.foodCounter + 1;
  15695. }
  15696. }
  15697. );
  15698. // No digest has been run so the counter will be zero
  15699. expect(scope.foodCounter).toEqual(0);
  15700. // Run the digest but since food has not changed count will still be zero
  15701. scope.$digest();
  15702. expect(scope.foodCounter).toEqual(0);
  15703. // Update food and run digest. Now the counter will increment
  15704. food = 'cheeseburger';
  15705. scope.$digest();
  15706. expect(scope.foodCounter).toEqual(1);
  15707. * ```
  15708. *
  15709. *
  15710. *
  15711. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15712. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15713. * a call to the `listener`.
  15714. *
  15715. * - `string`: Evaluated as {@link guide/expression expression}
  15716. * - `function(scope)`: called with current `scope` as a parameter.
  15717. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15718. * of `watchExpression` changes.
  15719. *
  15720. * - `newVal` contains the current value of the `watchExpression`
  15721. * - `oldVal` contains the previous value of the `watchExpression`
  15722. * - `scope` refers to the current scope
  15723. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15724. * comparing for reference equality.
  15725. * @returns {function()} Returns a deregistration function for this listener.
  15726. */
  15727. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15728. var get = $parse(watchExp);
  15729. if (get.$$watchDelegate) {
  15730. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15731. }
  15732. var scope = this,
  15733. array = scope.$$watchers,
  15734. watcher = {
  15735. fn: listener,
  15736. last: initWatchVal,
  15737. get: get,
  15738. exp: prettyPrintExpression || watchExp,
  15739. eq: !!objectEquality
  15740. };
  15741. lastDirtyWatch = null;
  15742. if (!isFunction(listener)) {
  15743. watcher.fn = noop;
  15744. }
  15745. if (!array) {
  15746. array = scope.$$watchers = [];
  15747. array.$$digestWatchIndex = -1;
  15748. }
  15749. // we use unshift since we use a while loop in $digest for speed.
  15750. // the while loop reads in reverse order.
  15751. array.unshift(watcher);
  15752. array.$$digestWatchIndex++;
  15753. incrementWatchersCount(this, 1);
  15754. return function deregisterWatch() {
  15755. var index = arrayRemove(array, watcher);
  15756. if (index >= 0) {
  15757. incrementWatchersCount(scope, -1);
  15758. if (index < array.$$digestWatchIndex) {
  15759. array.$$digestWatchIndex--;
  15760. }
  15761. }
  15762. lastDirtyWatch = null;
  15763. };
  15764. },
  15765. /**
  15766. * @ngdoc method
  15767. * @name $rootScope.Scope#$watchGroup
  15768. * @kind function
  15769. *
  15770. * @description
  15771. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15772. * If any one expression in the collection changes the `listener` is executed.
  15773. *
  15774. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  15775. * values are examined for changes on every call to `$digest`.
  15776. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15777. *
  15778. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15779. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15780. *
  15781. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15782. * expression in `watchExpressions` changes
  15783. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15784. * those of `watchExpression`
  15785. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15786. * those of `watchExpression`
  15787. * The `scope` refers to the current scope.
  15788. * @returns {function()} Returns a de-registration function for all listeners.
  15789. */
  15790. $watchGroup: function(watchExpressions, listener) {
  15791. var oldValues = new Array(watchExpressions.length);
  15792. var newValues = new Array(watchExpressions.length);
  15793. var deregisterFns = [];
  15794. var self = this;
  15795. var changeReactionScheduled = false;
  15796. var firstRun = true;
  15797. if (!watchExpressions.length) {
  15798. // No expressions means we call the listener ASAP
  15799. var shouldCall = true;
  15800. self.$evalAsync(function() {
  15801. if (shouldCall) listener(newValues, newValues, self);
  15802. });
  15803. return function deregisterWatchGroup() {
  15804. shouldCall = false;
  15805. };
  15806. }
  15807. if (watchExpressions.length === 1) {
  15808. // Special case size of one
  15809. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15810. newValues[0] = value;
  15811. oldValues[0] = oldValue;
  15812. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15813. });
  15814. }
  15815. forEach(watchExpressions, function(expr, i) {
  15816. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15817. newValues[i] = value;
  15818. oldValues[i] = oldValue;
  15819. if (!changeReactionScheduled) {
  15820. changeReactionScheduled = true;
  15821. self.$evalAsync(watchGroupAction);
  15822. }
  15823. });
  15824. deregisterFns.push(unwatchFn);
  15825. });
  15826. function watchGroupAction() {
  15827. changeReactionScheduled = false;
  15828. if (firstRun) {
  15829. firstRun = false;
  15830. listener(newValues, newValues, self);
  15831. } else {
  15832. listener(newValues, oldValues, self);
  15833. }
  15834. }
  15835. return function deregisterWatchGroup() {
  15836. while (deregisterFns.length) {
  15837. deregisterFns.shift()();
  15838. }
  15839. };
  15840. },
  15841. /**
  15842. * @ngdoc method
  15843. * @name $rootScope.Scope#$watchCollection
  15844. * @kind function
  15845. *
  15846. * @description
  15847. * Shallow watches the properties of an object and fires whenever any of the properties change
  15848. * (for arrays, this implies watching the array items; for object maps, this implies watching
  15849. * the properties). If a change is detected, the `listener` callback is fired.
  15850. *
  15851. * - The `obj` collection is observed via standard $watch operation and is examined on every
  15852. * call to $digest() to see if any items have been added, removed, or moved.
  15853. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  15854. * adding, removing, and moving items belonging to an object or array.
  15855. *
  15856. *
  15857. * # Example
  15858. * ```js
  15859. $scope.names = ['igor', 'matias', 'misko', 'james'];
  15860. $scope.dataCount = 4;
  15861. $scope.$watchCollection('names', function(newNames, oldNames) {
  15862. $scope.dataCount = newNames.length;
  15863. });
  15864. expect($scope.dataCount).toEqual(4);
  15865. $scope.$digest();
  15866. //still at 4 ... no changes
  15867. expect($scope.dataCount).toEqual(4);
  15868. $scope.names.pop();
  15869. $scope.$digest();
  15870. //now there's been a change
  15871. expect($scope.dataCount).toEqual(3);
  15872. * ```
  15873. *
  15874. *
  15875. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15876. * expression value should evaluate to an object or an array which is observed on each
  15877. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15878. * collection will trigger a call to the `listener`.
  15879. *
  15880. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15881. * when a change is detected.
  15882. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15883. * - The `oldCollection` object is a copy of the former collection data.
  15884. * Due to performance considerations, the`oldCollection` value is computed only if the
  15885. * `listener` function declares two or more arguments.
  15886. * - The `scope` argument refers to the current scope.
  15887. *
  15888. * @returns {function()} Returns a de-registration function for this listener. When the
  15889. * de-registration function is executed, the internal watch operation is terminated.
  15890. */
  15891. $watchCollection: function(obj, listener) {
  15892. $watchCollectionInterceptor.$stateful = true;
  15893. var self = this;
  15894. // the current value, updated on each dirty-check run
  15895. var newValue;
  15896. // a shallow copy of the newValue from the last dirty-check run,
  15897. // updated to match newValue during dirty-check run
  15898. var oldValue;
  15899. // a shallow copy of the newValue from when the last change happened
  15900. var veryOldValue;
  15901. // only track veryOldValue if the listener is asking for it
  15902. var trackVeryOldValue = (listener.length > 1);
  15903. var changeDetected = 0;
  15904. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15905. var internalArray = [];
  15906. var internalObject = {};
  15907. var initRun = true;
  15908. var oldLength = 0;
  15909. function $watchCollectionInterceptor(_value) {
  15910. newValue = _value;
  15911. var newLength, key, bothNaN, newItem, oldItem;
  15912. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15913. if (isUndefined(newValue)) return;
  15914. if (!isObject(newValue)) { // if primitive
  15915. if (oldValue !== newValue) {
  15916. oldValue = newValue;
  15917. changeDetected++;
  15918. }
  15919. } else if (isArrayLike(newValue)) {
  15920. if (oldValue !== internalArray) {
  15921. // we are transitioning from something which was not an array into array.
  15922. oldValue = internalArray;
  15923. oldLength = oldValue.length = 0;
  15924. changeDetected++;
  15925. }
  15926. newLength = newValue.length;
  15927. if (oldLength !== newLength) {
  15928. // if lengths do not match we need to trigger change notification
  15929. changeDetected++;
  15930. oldValue.length = oldLength = newLength;
  15931. }
  15932. // copy the items to oldValue and look for changes.
  15933. for (var i = 0; i < newLength; i++) {
  15934. oldItem = oldValue[i];
  15935. newItem = newValue[i];
  15936. // eslint-disable-next-line no-self-compare
  15937. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15938. if (!bothNaN && (oldItem !== newItem)) {
  15939. changeDetected++;
  15940. oldValue[i] = newItem;
  15941. }
  15942. }
  15943. } else {
  15944. if (oldValue !== internalObject) {
  15945. // we are transitioning from something which was not an object into object.
  15946. oldValue = internalObject = {};
  15947. oldLength = 0;
  15948. changeDetected++;
  15949. }
  15950. // copy the items to oldValue and look for changes.
  15951. newLength = 0;
  15952. for (key in newValue) {
  15953. if (hasOwnProperty.call(newValue, key)) {
  15954. newLength++;
  15955. newItem = newValue[key];
  15956. oldItem = oldValue[key];
  15957. if (key in oldValue) {
  15958. // eslint-disable-next-line no-self-compare
  15959. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15960. if (!bothNaN && (oldItem !== newItem)) {
  15961. changeDetected++;
  15962. oldValue[key] = newItem;
  15963. }
  15964. } else {
  15965. oldLength++;
  15966. oldValue[key] = newItem;
  15967. changeDetected++;
  15968. }
  15969. }
  15970. }
  15971. if (oldLength > newLength) {
  15972. // we used to have more keys, need to find them and destroy them.
  15973. changeDetected++;
  15974. for (key in oldValue) {
  15975. if (!hasOwnProperty.call(newValue, key)) {
  15976. oldLength--;
  15977. delete oldValue[key];
  15978. }
  15979. }
  15980. }
  15981. }
  15982. return changeDetected;
  15983. }
  15984. function $watchCollectionAction() {
  15985. if (initRun) {
  15986. initRun = false;
  15987. listener(newValue, newValue, self);
  15988. } else {
  15989. listener(newValue, veryOldValue, self);
  15990. }
  15991. // make a copy for the next time a collection is changed
  15992. if (trackVeryOldValue) {
  15993. if (!isObject(newValue)) {
  15994. //primitive
  15995. veryOldValue = newValue;
  15996. } else if (isArrayLike(newValue)) {
  15997. veryOldValue = new Array(newValue.length);
  15998. for (var i = 0; i < newValue.length; i++) {
  15999. veryOldValue[i] = newValue[i];
  16000. }
  16001. } else { // if object
  16002. veryOldValue = {};
  16003. for (var key in newValue) {
  16004. if (hasOwnProperty.call(newValue, key)) {
  16005. veryOldValue[key] = newValue[key];
  16006. }
  16007. }
  16008. }
  16009. }
  16010. }
  16011. return this.$watch(changeDetector, $watchCollectionAction);
  16012. },
  16013. /**
  16014. * @ngdoc method
  16015. * @name $rootScope.Scope#$digest
  16016. * @kind function
  16017. *
  16018. * @description
  16019. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16020. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16021. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16022. * until no more listeners are firing. This means that it is possible to get into an infinite
  16023. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16024. * iterations exceeds 10.
  16025. *
  16026. * Usually, you don't call `$digest()` directly in
  16027. * {@link ng.directive:ngController controllers} or in
  16028. * {@link ng.$compileProvider#directive directives}.
  16029. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16030. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16031. *
  16032. * If you want to be notified whenever `$digest()` is called,
  16033. * you can register a `watchExpression` function with
  16034. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16035. *
  16036. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16037. *
  16038. * # Example
  16039. * ```js
  16040. var scope = ...;
  16041. scope.name = 'misko';
  16042. scope.counter = 0;
  16043. expect(scope.counter).toEqual(0);
  16044. scope.$watch('name', function(newValue, oldValue) {
  16045. scope.counter = scope.counter + 1;
  16046. });
  16047. expect(scope.counter).toEqual(0);
  16048. scope.$digest();
  16049. // the listener is always called during the first $digest loop after it was registered
  16050. expect(scope.counter).toEqual(1);
  16051. scope.$digest();
  16052. // but now it will not be called unless the value changes
  16053. expect(scope.counter).toEqual(1);
  16054. scope.name = 'adam';
  16055. scope.$digest();
  16056. expect(scope.counter).toEqual(2);
  16057. * ```
  16058. *
  16059. */
  16060. $digest: function() {
  16061. var watch, value, last, fn, get,
  16062. watchers,
  16063. dirty, ttl = TTL,
  16064. next, current, target = this,
  16065. watchLog = [],
  16066. logIdx, asyncTask;
  16067. beginPhase('$digest');
  16068. // Check for changes to browser url that happened in sync before the call to $digest
  16069. $browser.$$checkUrlChange();
  16070. if (this === $rootScope && applyAsyncId !== null) {
  16071. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16072. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16073. $browser.defer.cancel(applyAsyncId);
  16074. flushApplyAsync();
  16075. }
  16076. lastDirtyWatch = null;
  16077. do { // "while dirty" loop
  16078. dirty = false;
  16079. current = target;
  16080. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16081. // be reentered recursively. Calling $digest from a function passed to $applyAsync would
  16082. // lead to a '$digest already in progress' error.
  16083. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16084. try {
  16085. asyncTask = asyncQueue[asyncQueuePosition];
  16086. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  16087. } catch (e) {
  16088. $exceptionHandler(e);
  16089. }
  16090. lastDirtyWatch = null;
  16091. }
  16092. asyncQueue.length = 0;
  16093. traverseScopesLoop:
  16094. do { // "traverse the scopes" loop
  16095. if ((watchers = current.$$watchers)) {
  16096. // process our watches
  16097. watchers.$$digestWatchIndex = watchers.length;
  16098. while (watchers.$$digestWatchIndex--) {
  16099. try {
  16100. watch = watchers[watchers.$$digestWatchIndex];
  16101. // Most common watches are on primitives, in which case we can short
  16102. // circuit it with === operator, only when === fails do we use .equals
  16103. if (watch) {
  16104. get = watch.get;
  16105. if ((value = get(current)) !== (last = watch.last) &&
  16106. !(watch.eq
  16107. ? equals(value, last)
  16108. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16109. dirty = true;
  16110. lastDirtyWatch = watch;
  16111. watch.last = watch.eq ? copy(value, null) : value;
  16112. fn = watch.fn;
  16113. fn(value, ((last === initWatchVal) ? value : last), current);
  16114. if (ttl < 5) {
  16115. logIdx = 4 - ttl;
  16116. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16117. watchLog[logIdx].push({
  16118. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16119. newVal: value,
  16120. oldVal: last
  16121. });
  16122. }
  16123. } else if (watch === lastDirtyWatch) {
  16124. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16125. // have already been tested.
  16126. dirty = false;
  16127. break traverseScopesLoop;
  16128. }
  16129. }
  16130. } catch (e) {
  16131. $exceptionHandler(e);
  16132. }
  16133. }
  16134. }
  16135. // Insanity Warning: scope depth-first traversal
  16136. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16137. // this piece should be kept in sync with the traversal in $broadcast
  16138. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16139. (current !== target && current.$$nextSibling)))) {
  16140. while (current !== target && !(next = current.$$nextSibling)) {
  16141. current = current.$parent;
  16142. }
  16143. }
  16144. } while ((current = next));
  16145. // `break traverseScopesLoop;` takes us to here
  16146. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16147. clearPhase();
  16148. throw $rootScopeMinErr('infdig',
  16149. '{0} $digest() iterations reached. Aborting!\n' +
  16150. 'Watchers fired in the last 5 iterations: {1}',
  16151. TTL, watchLog);
  16152. }
  16153. } while (dirty || asyncQueue.length);
  16154. clearPhase();
  16155. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16156. while (postDigestQueuePosition < postDigestQueue.length) {
  16157. try {
  16158. postDigestQueue[postDigestQueuePosition++]();
  16159. } catch (e) {
  16160. $exceptionHandler(e);
  16161. }
  16162. }
  16163. postDigestQueue.length = postDigestQueuePosition = 0;
  16164. },
  16165. /**
  16166. * @ngdoc event
  16167. * @name $rootScope.Scope#$destroy
  16168. * @eventType broadcast on scope being destroyed
  16169. *
  16170. * @description
  16171. * Broadcasted when a scope and its children are being destroyed.
  16172. *
  16173. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16174. * clean up DOM bindings before an element is removed from the DOM.
  16175. */
  16176. /**
  16177. * @ngdoc method
  16178. * @name $rootScope.Scope#$destroy
  16179. * @kind function
  16180. *
  16181. * @description
  16182. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16183. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16184. * propagate to the current scope and its children. Removal also implies that the current
  16185. * scope is eligible for garbage collection.
  16186. *
  16187. * The `$destroy()` is usually used by directives such as
  16188. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16189. * unrolling of the loop.
  16190. *
  16191. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16192. * Application code can register a `$destroy` event handler that will give it a chance to
  16193. * perform any necessary cleanup.
  16194. *
  16195. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16196. * clean up DOM bindings before an element is removed from the DOM.
  16197. */
  16198. $destroy: function() {
  16199. // We can't destroy a scope that has been already destroyed.
  16200. if (this.$$destroyed) return;
  16201. var parent = this.$parent;
  16202. this.$broadcast('$destroy');
  16203. this.$$destroyed = true;
  16204. if (this === $rootScope) {
  16205. //Remove handlers attached to window when $rootScope is removed
  16206. $browser.$$applicationDestroyed();
  16207. }
  16208. incrementWatchersCount(this, -this.$$watchersCount);
  16209. for (var eventName in this.$$listenerCount) {
  16210. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16211. }
  16212. // sever all the references to parent scopes (after this cleanup, the current scope should
  16213. // not be retained by any of our references and should be eligible for garbage collection)
  16214. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16215. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16216. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16217. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16218. // Disable listeners, watchers and apply/digest methods
  16219. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16220. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16221. this.$$listeners = {};
  16222. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16223. this.$$nextSibling = null;
  16224. cleanUpScope(this);
  16225. },
  16226. /**
  16227. * @ngdoc method
  16228. * @name $rootScope.Scope#$eval
  16229. * @kind function
  16230. *
  16231. * @description
  16232. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16233. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16234. * expressions.
  16235. *
  16236. * # Example
  16237. * ```js
  16238. var scope = ng.$rootScope.Scope();
  16239. scope.a = 1;
  16240. scope.b = 2;
  16241. expect(scope.$eval('a+b')).toEqual(3);
  16242. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16243. * ```
  16244. *
  16245. * @param {(string|function())=} expression An angular expression to be executed.
  16246. *
  16247. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16248. * - `function(scope)`: execute the function with the current `scope` parameter.
  16249. *
  16250. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16251. * @returns {*} The result of evaluating the expression.
  16252. */
  16253. $eval: function(expr, locals) {
  16254. return $parse(expr)(this, locals);
  16255. },
  16256. /**
  16257. * @ngdoc method
  16258. * @name $rootScope.Scope#$evalAsync
  16259. * @kind function
  16260. *
  16261. * @description
  16262. * Executes the expression on the current scope at a later point in time.
  16263. *
  16264. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16265. * that:
  16266. *
  16267. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16268. * rendering).
  16269. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16270. * `expression` execution.
  16271. *
  16272. * Any exceptions from the execution of the expression are forwarded to the
  16273. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16274. *
  16275. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16276. * will be scheduled. However, it is encouraged to always call code that changes the model
  16277. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16278. *
  16279. * @param {(string|function())=} expression An angular expression to be executed.
  16280. *
  16281. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16282. * - `function(scope)`: execute the function with the current `scope` parameter.
  16283. *
  16284. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16285. */
  16286. $evalAsync: function(expr, locals) {
  16287. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16288. // task also schedule async auto-flush
  16289. if (!$rootScope.$$phase && !asyncQueue.length) {
  16290. $browser.defer(function() {
  16291. if (asyncQueue.length) {
  16292. $rootScope.$digest();
  16293. }
  16294. });
  16295. }
  16296. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  16297. },
  16298. $$postDigest: function(fn) {
  16299. postDigestQueue.push(fn);
  16300. },
  16301. /**
  16302. * @ngdoc method
  16303. * @name $rootScope.Scope#$apply
  16304. * @kind function
  16305. *
  16306. * @description
  16307. * `$apply()` is used to execute an expression in angular from outside of the angular
  16308. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16309. * Because we are calling into the angular framework we need to perform proper scope life
  16310. * cycle of {@link ng.$exceptionHandler exception handling},
  16311. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16312. *
  16313. * ## Life cycle
  16314. *
  16315. * # Pseudo-Code of `$apply()`
  16316. * ```js
  16317. function $apply(expr) {
  16318. try {
  16319. return $eval(expr);
  16320. } catch (e) {
  16321. $exceptionHandler(e);
  16322. } finally {
  16323. $root.$digest();
  16324. }
  16325. }
  16326. * ```
  16327. *
  16328. *
  16329. * Scope's `$apply()` method transitions through the following stages:
  16330. *
  16331. * 1. The {@link guide/expression expression} is executed using the
  16332. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16333. * 2. Any exceptions from the execution of the expression are forwarded to the
  16334. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16335. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16336. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16337. *
  16338. *
  16339. * @param {(string|function())=} exp An angular expression to be executed.
  16340. *
  16341. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16342. * - `function(scope)`: execute the function with current `scope` parameter.
  16343. *
  16344. * @returns {*} The result of evaluating the expression.
  16345. */
  16346. $apply: function(expr) {
  16347. try {
  16348. beginPhase('$apply');
  16349. try {
  16350. return this.$eval(expr);
  16351. } finally {
  16352. clearPhase();
  16353. }
  16354. } catch (e) {
  16355. $exceptionHandler(e);
  16356. } finally {
  16357. try {
  16358. $rootScope.$digest();
  16359. } catch (e) {
  16360. $exceptionHandler(e);
  16361. // eslint-disable-next-line no-unsafe-finally
  16362. throw e;
  16363. }
  16364. }
  16365. },
  16366. /**
  16367. * @ngdoc method
  16368. * @name $rootScope.Scope#$applyAsync
  16369. * @kind function
  16370. *
  16371. * @description
  16372. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16373. * varies across browsers, but is typically around ~10 milliseconds.
  16374. *
  16375. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16376. * digest.
  16377. *
  16378. * @param {(string|function())=} exp An angular expression to be executed.
  16379. *
  16380. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16381. * - `function(scope)`: execute the function with current `scope` parameter.
  16382. */
  16383. $applyAsync: function(expr) {
  16384. var scope = this;
  16385. if (expr) {
  16386. applyAsyncQueue.push($applyAsyncExpression);
  16387. }
  16388. expr = $parse(expr);
  16389. scheduleApplyAsync();
  16390. function $applyAsyncExpression() {
  16391. scope.$eval(expr);
  16392. }
  16393. },
  16394. /**
  16395. * @ngdoc method
  16396. * @name $rootScope.Scope#$on
  16397. * @kind function
  16398. *
  16399. * @description
  16400. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16401. * discussion of event life cycle.
  16402. *
  16403. * The event listener function format is: `function(event, args...)`. The `event` object
  16404. * passed into the listener has the following attributes:
  16405. *
  16406. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16407. * `$broadcast`-ed.
  16408. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16409. * event propagates through the scope hierarchy, this property is set to null.
  16410. * - `name` - `{string}`: name of the event.
  16411. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16412. * further event propagation (available only for events that were `$emit`-ed).
  16413. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16414. * to true.
  16415. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16416. *
  16417. * @param {string} name Event name to listen on.
  16418. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16419. * @returns {function()} Returns a deregistration function for this listener.
  16420. */
  16421. $on: function(name, listener) {
  16422. var namedListeners = this.$$listeners[name];
  16423. if (!namedListeners) {
  16424. this.$$listeners[name] = namedListeners = [];
  16425. }
  16426. namedListeners.push(listener);
  16427. var current = this;
  16428. do {
  16429. if (!current.$$listenerCount[name]) {
  16430. current.$$listenerCount[name] = 0;
  16431. }
  16432. current.$$listenerCount[name]++;
  16433. } while ((current = current.$parent));
  16434. var self = this;
  16435. return function() {
  16436. var indexOfListener = namedListeners.indexOf(listener);
  16437. if (indexOfListener !== -1) {
  16438. namedListeners[indexOfListener] = null;
  16439. decrementListenerCount(self, 1, name);
  16440. }
  16441. };
  16442. },
  16443. /**
  16444. * @ngdoc method
  16445. * @name $rootScope.Scope#$emit
  16446. * @kind function
  16447. *
  16448. * @description
  16449. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16450. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16451. *
  16452. * The event life cycle starts at the scope on which `$emit` was called. All
  16453. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16454. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16455. * registered listeners along the way. The event will stop propagating if one of the listeners
  16456. * cancels it.
  16457. *
  16458. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16459. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16460. *
  16461. * @param {string} name Event name to emit.
  16462. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16463. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16464. */
  16465. $emit: function(name, args) {
  16466. var empty = [],
  16467. namedListeners,
  16468. scope = this,
  16469. stopPropagation = false,
  16470. event = {
  16471. name: name,
  16472. targetScope: scope,
  16473. stopPropagation: function() {stopPropagation = true;},
  16474. preventDefault: function() {
  16475. event.defaultPrevented = true;
  16476. },
  16477. defaultPrevented: false
  16478. },
  16479. listenerArgs = concat([event], arguments, 1),
  16480. i, length;
  16481. do {
  16482. namedListeners = scope.$$listeners[name] || empty;
  16483. event.currentScope = scope;
  16484. for (i = 0, length = namedListeners.length; i < length; i++) {
  16485. // if listeners were deregistered, defragment the array
  16486. if (!namedListeners[i]) {
  16487. namedListeners.splice(i, 1);
  16488. i--;
  16489. length--;
  16490. continue;
  16491. }
  16492. try {
  16493. //allow all listeners attached to the current scope to run
  16494. namedListeners[i].apply(null, listenerArgs);
  16495. } catch (e) {
  16496. $exceptionHandler(e);
  16497. }
  16498. }
  16499. //if any listener on the current scope stops propagation, prevent bubbling
  16500. if (stopPropagation) {
  16501. event.currentScope = null;
  16502. return event;
  16503. }
  16504. //traverse upwards
  16505. scope = scope.$parent;
  16506. } while (scope);
  16507. event.currentScope = null;
  16508. return event;
  16509. },
  16510. /**
  16511. * @ngdoc method
  16512. * @name $rootScope.Scope#$broadcast
  16513. * @kind function
  16514. *
  16515. * @description
  16516. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16517. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16518. *
  16519. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16520. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16521. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16522. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16523. *
  16524. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16525. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16526. *
  16527. * @param {string} name Event name to broadcast.
  16528. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16529. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16530. */
  16531. $broadcast: function(name, args) {
  16532. var target = this,
  16533. current = target,
  16534. next = target,
  16535. event = {
  16536. name: name,
  16537. targetScope: target,
  16538. preventDefault: function() {
  16539. event.defaultPrevented = true;
  16540. },
  16541. defaultPrevented: false
  16542. };
  16543. if (!target.$$listenerCount[name]) return event;
  16544. var listenerArgs = concat([event], arguments, 1),
  16545. listeners, i, length;
  16546. //down while you can, then up and next sibling or up and next sibling until back at root
  16547. while ((current = next)) {
  16548. event.currentScope = current;
  16549. listeners = current.$$listeners[name] || [];
  16550. for (i = 0, length = listeners.length; i < length; i++) {
  16551. // if listeners were deregistered, defragment the array
  16552. if (!listeners[i]) {
  16553. listeners.splice(i, 1);
  16554. i--;
  16555. length--;
  16556. continue;
  16557. }
  16558. try {
  16559. listeners[i].apply(null, listenerArgs);
  16560. } catch (e) {
  16561. $exceptionHandler(e);
  16562. }
  16563. }
  16564. // Insanity Warning: scope depth-first traversal
  16565. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16566. // this piece should be kept in sync with the traversal in $digest
  16567. // (though it differs due to having the extra check for $$listenerCount)
  16568. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16569. (current !== target && current.$$nextSibling)))) {
  16570. while (current !== target && !(next = current.$$nextSibling)) {
  16571. current = current.$parent;
  16572. }
  16573. }
  16574. }
  16575. event.currentScope = null;
  16576. return event;
  16577. }
  16578. };
  16579. var $rootScope = new Scope();
  16580. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16581. var asyncQueue = $rootScope.$$asyncQueue = [];
  16582. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16583. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16584. var postDigestQueuePosition = 0;
  16585. return $rootScope;
  16586. function beginPhase(phase) {
  16587. if ($rootScope.$$phase) {
  16588. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16589. }
  16590. $rootScope.$$phase = phase;
  16591. }
  16592. function clearPhase() {
  16593. $rootScope.$$phase = null;
  16594. }
  16595. function incrementWatchersCount(current, count) {
  16596. do {
  16597. current.$$watchersCount += count;
  16598. } while ((current = current.$parent));
  16599. }
  16600. function decrementListenerCount(current, count, name) {
  16601. do {
  16602. current.$$listenerCount[name] -= count;
  16603. if (current.$$listenerCount[name] === 0) {
  16604. delete current.$$listenerCount[name];
  16605. }
  16606. } while ((current = current.$parent));
  16607. }
  16608. /**
  16609. * function used as an initial value for watchers.
  16610. * because it's unique we can easily tell it apart from other values
  16611. */
  16612. function initWatchVal() {}
  16613. function flushApplyAsync() {
  16614. while (applyAsyncQueue.length) {
  16615. try {
  16616. applyAsyncQueue.shift()();
  16617. } catch (e) {
  16618. $exceptionHandler(e);
  16619. }
  16620. }
  16621. applyAsyncId = null;
  16622. }
  16623. function scheduleApplyAsync() {
  16624. if (applyAsyncId === null) {
  16625. applyAsyncId = $browser.defer(function() {
  16626. $rootScope.$apply(flushApplyAsync);
  16627. });
  16628. }
  16629. }
  16630. }];
  16631. }
  16632. /**
  16633. * @ngdoc service
  16634. * @name $rootElement
  16635. *
  16636. * @description
  16637. * The root element of Angular application. This is either the element where {@link
  16638. * ng.directive:ngApp ngApp} was declared or the element passed into
  16639. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16640. * location where the application's {@link auto.$injector $injector} service gets
  16641. * published, and can be retrieved using `$rootElement.injector()`.
  16642. */
  16643. // the implementation is in angular.bootstrap
  16644. /**
  16645. * @this
  16646. * @description
  16647. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16648. */
  16649. function $$SanitizeUriProvider() {
  16650. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16651. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16652. /**
  16653. * @description
  16654. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16655. * urls during a[href] sanitization.
  16656. *
  16657. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16658. *
  16659. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16660. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16661. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16662. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16663. *
  16664. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16665. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16666. * chaining otherwise.
  16667. */
  16668. this.aHrefSanitizationWhitelist = function(regexp) {
  16669. if (isDefined(regexp)) {
  16670. aHrefSanitizationWhitelist = regexp;
  16671. return this;
  16672. }
  16673. return aHrefSanitizationWhitelist;
  16674. };
  16675. /**
  16676. * @description
  16677. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16678. * urls during img[src] sanitization.
  16679. *
  16680. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16681. *
  16682. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16683. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16684. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16685. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16686. *
  16687. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16688. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16689. * chaining otherwise.
  16690. */
  16691. this.imgSrcSanitizationWhitelist = function(regexp) {
  16692. if (isDefined(regexp)) {
  16693. imgSrcSanitizationWhitelist = regexp;
  16694. return this;
  16695. }
  16696. return imgSrcSanitizationWhitelist;
  16697. };
  16698. this.$get = function() {
  16699. return function sanitizeUri(uri, isImage) {
  16700. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16701. var normalizedVal;
  16702. normalizedVal = urlResolve(uri).href;
  16703. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16704. return 'unsafe:' + normalizedVal;
  16705. }
  16706. return uri;
  16707. };
  16708. };
  16709. }
  16710. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16711. * Any commits to this file should be reviewed with security in mind. *
  16712. * Changes to this file can potentially create security vulnerabilities. *
  16713. * An approval from 2 Core members with history of modifying *
  16714. * this file is required. *
  16715. * *
  16716. * Does the change somehow allow for arbitrary javascript to be executed? *
  16717. * Or allows for someone to change the prototype of built-in objects? *
  16718. * Or gives undesired access to variables likes document or window? *
  16719. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16720. /* exported $SceProvider, $SceDelegateProvider */
  16721. var $sceMinErr = minErr('$sce');
  16722. var SCE_CONTEXTS = {
  16723. HTML: 'html',
  16724. CSS: 'css',
  16725. URL: 'url',
  16726. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16727. // url. (e.g. ng-include, script src, templateUrl)
  16728. RESOURCE_URL: 'resourceUrl',
  16729. JS: 'js'
  16730. };
  16731. // Helper functions follow.
  16732. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  16733. function snakeToCamel(name) {
  16734. return name
  16735. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  16736. }
  16737. function adjustMatcher(matcher) {
  16738. if (matcher === 'self') {
  16739. return matcher;
  16740. } else if (isString(matcher)) {
  16741. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16742. // '*' matches any character except those from the set ':/.?&'.
  16743. // '**' matches any character (like .* in a RegExp).
  16744. // More than 2 *'s raises an error as it's ill defined.
  16745. if (matcher.indexOf('***') > -1) {
  16746. throw $sceMinErr('iwcard',
  16747. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16748. }
  16749. matcher = escapeForRegexp(matcher).
  16750. replace(/\\\*\\\*/g, '.*').
  16751. replace(/\\\*/g, '[^:/.?&;]*');
  16752. return new RegExp('^' + matcher + '$');
  16753. } else if (isRegExp(matcher)) {
  16754. // The only other type of matcher allowed is a Regexp.
  16755. // Match entire URL / disallow partial matches.
  16756. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16757. return new RegExp('^' + matcher.source + '$');
  16758. } else {
  16759. throw $sceMinErr('imatcher',
  16760. 'Matchers may only be "self", string patterns or RegExp objects');
  16761. }
  16762. }
  16763. function adjustMatchers(matchers) {
  16764. var adjustedMatchers = [];
  16765. if (isDefined(matchers)) {
  16766. forEach(matchers, function(matcher) {
  16767. adjustedMatchers.push(adjustMatcher(matcher));
  16768. });
  16769. }
  16770. return adjustedMatchers;
  16771. }
  16772. /**
  16773. * @ngdoc service
  16774. * @name $sceDelegate
  16775. * @kind function
  16776. *
  16777. * @description
  16778. *
  16779. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16780. * Contextual Escaping (SCE)} services to AngularJS.
  16781. *
  16782. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16783. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16784. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16785. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16786. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16787. *
  16788. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16789. *
  16790. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16791. * can override it completely to change the behavior of `$sce`, the common case would
  16792. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16793. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16794. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16795. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16796. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16797. */
  16798. /**
  16799. * @ngdoc provider
  16800. * @name $sceDelegateProvider
  16801. * @this
  16802. *
  16803. * @description
  16804. *
  16805. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16806. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16807. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16808. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16809. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16810. *
  16811. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16812. * Strict Contextual Escaping (SCE)}.
  16813. *
  16814. * **Example**: Consider the following case. <a name="example"></a>
  16815. *
  16816. * - your app is hosted at url `http://myapp.example.com/`
  16817. * - but some of your templates are hosted on other domains you control such as
  16818. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  16819. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16820. *
  16821. * Here is what a secure configuration for this scenario might look like:
  16822. *
  16823. * ```
  16824. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  16825. * $sceDelegateProvider.resourceUrlWhitelist([
  16826. * // Allow same origin resource loads.
  16827. * 'self',
  16828. * // Allow loading from our assets domain. Notice the difference between * and **.
  16829. * 'http://srv*.assets.example.com/**'
  16830. * ]);
  16831. *
  16832. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  16833. * $sceDelegateProvider.resourceUrlBlacklist([
  16834. * 'http://myapp.example.com/clickThru**'
  16835. * ]);
  16836. * });
  16837. * ```
  16838. */
  16839. function $SceDelegateProvider() {
  16840. this.SCE_CONTEXTS = SCE_CONTEXTS;
  16841. // Resource URLs can also be trusted by policy.
  16842. var resourceUrlWhitelist = ['self'],
  16843. resourceUrlBlacklist = [];
  16844. /**
  16845. * @ngdoc method
  16846. * @name $sceDelegateProvider#resourceUrlWhitelist
  16847. * @kind function
  16848. *
  16849. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  16850. * provided. This must be an array or null. A snapshot of this array is used so further
  16851. * changes to the array are ignored.
  16852. *
  16853. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16854. * allowed in this array.
  16855. *
  16856. * <div class="alert alert-warning">
  16857. * **Note:** an empty whitelist array will block all URLs!
  16858. * </div>
  16859. *
  16860. * @return {Array} the currently set whitelist array.
  16861. *
  16862. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  16863. * same origin resource requests.
  16864. *
  16865. * @description
  16866. * Sets/Gets the whitelist of trusted resource URLs.
  16867. */
  16868. this.resourceUrlWhitelist = function(value) {
  16869. if (arguments.length) {
  16870. resourceUrlWhitelist = adjustMatchers(value);
  16871. }
  16872. return resourceUrlWhitelist;
  16873. };
  16874. /**
  16875. * @ngdoc method
  16876. * @name $sceDelegateProvider#resourceUrlBlacklist
  16877. * @kind function
  16878. *
  16879. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  16880. * provided. This must be an array or null. A snapshot of this array is used so further
  16881. * changes to the array are ignored.
  16882. *
  16883. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16884. * allowed in this array.
  16885. *
  16886. * The typical usage for the blacklist is to **block
  16887. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  16888. * these would otherwise be trusted but actually return content from the redirected domain.
  16889. *
  16890. * Finally, **the blacklist overrides the whitelist** and has the final say.
  16891. *
  16892. * @return {Array} the currently set blacklist array.
  16893. *
  16894. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16895. * is no blacklist.)
  16896. *
  16897. * @description
  16898. * Sets/Gets the blacklist of trusted resource URLs.
  16899. */
  16900. this.resourceUrlBlacklist = function(value) {
  16901. if (arguments.length) {
  16902. resourceUrlBlacklist = adjustMatchers(value);
  16903. }
  16904. return resourceUrlBlacklist;
  16905. };
  16906. this.$get = ['$injector', function($injector) {
  16907. var htmlSanitizer = function htmlSanitizer(html) {
  16908. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16909. };
  16910. if ($injector.has('$sanitize')) {
  16911. htmlSanitizer = $injector.get('$sanitize');
  16912. }
  16913. function matchUrl(matcher, parsedUrl) {
  16914. if (matcher === 'self') {
  16915. return urlIsSameOrigin(parsedUrl);
  16916. } else {
  16917. // definitely a regex. See adjustMatchers()
  16918. return !!matcher.exec(parsedUrl.href);
  16919. }
  16920. }
  16921. function isResourceUrlAllowedByPolicy(url) {
  16922. var parsedUrl = urlResolve(url.toString());
  16923. var i, n, allowed = false;
  16924. // Ensure that at least one item from the whitelist allows this url.
  16925. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  16926. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  16927. allowed = true;
  16928. break;
  16929. }
  16930. }
  16931. if (allowed) {
  16932. // Ensure that no item from the blacklist blocked this url.
  16933. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  16934. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  16935. allowed = false;
  16936. break;
  16937. }
  16938. }
  16939. }
  16940. return allowed;
  16941. }
  16942. function generateHolderType(Base) {
  16943. var holderType = function TrustedValueHolderType(trustedValue) {
  16944. this.$$unwrapTrustedValue = function() {
  16945. return trustedValue;
  16946. };
  16947. };
  16948. if (Base) {
  16949. holderType.prototype = new Base();
  16950. }
  16951. holderType.prototype.valueOf = function sceValueOf() {
  16952. return this.$$unwrapTrustedValue();
  16953. };
  16954. holderType.prototype.toString = function sceToString() {
  16955. return this.$$unwrapTrustedValue().toString();
  16956. };
  16957. return holderType;
  16958. }
  16959. var trustedValueHolderBase = generateHolderType(),
  16960. byType = {};
  16961. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  16962. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  16963. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  16964. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  16965. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  16966. /**
  16967. * @ngdoc method
  16968. * @name $sceDelegate#trustAs
  16969. *
  16970. * @description
  16971. * Returns an object that is trusted by angular for use in specified strict
  16972. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  16973. * attribute interpolation, any dom event binding attribute interpolation
  16974. * such as for onclick, etc.) that uses the provided value.
  16975. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  16976. *
  16977. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16978. * resourceUrl, html, js and css.
  16979. * @param {*} value The value that that should be considered trusted/safe.
  16980. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16981. * where Angular expects a $sce.trustAs() return value.
  16982. */
  16983. function trustAs(type, trustedValue) {
  16984. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16985. if (!Constructor) {
  16986. throw $sceMinErr('icontext',
  16987. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  16988. type, trustedValue);
  16989. }
  16990. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  16991. return trustedValue;
  16992. }
  16993. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  16994. // mutable objects, we ensure here that the value passed in is actually a string.
  16995. if (typeof trustedValue !== 'string') {
  16996. throw $sceMinErr('itype',
  16997. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  16998. type);
  16999. }
  17000. return new Constructor(trustedValue);
  17001. }
  17002. /**
  17003. * @ngdoc method
  17004. * @name $sceDelegate#valueOf
  17005. *
  17006. * @description
  17007. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17008. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17009. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17010. *
  17011. * If the passed parameter is not a value that had been returned by {@link
  17012. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  17013. *
  17014. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17015. * call or anything else.
  17016. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17017. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17018. * `value` unchanged.
  17019. */
  17020. function valueOf(maybeTrusted) {
  17021. if (maybeTrusted instanceof trustedValueHolderBase) {
  17022. return maybeTrusted.$$unwrapTrustedValue();
  17023. } else {
  17024. return maybeTrusted;
  17025. }
  17026. }
  17027. /**
  17028. * @ngdoc method
  17029. * @name $sceDelegate#getTrusted
  17030. *
  17031. * @description
  17032. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  17033. * returns the originally supplied value if the queried context type is a supertype of the
  17034. * created type. If this condition isn't satisfied, throws an exception.
  17035. *
  17036. * <div class="alert alert-danger">
  17037. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  17038. * (XSS) vulnerability in your application.
  17039. * </div>
  17040. *
  17041. * @param {string} type The kind of context in which this value is to be used.
  17042. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17043. * `$sceDelegate.trustAs`} call.
  17044. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  17045. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  17046. */
  17047. function getTrusted(type, maybeTrusted) {
  17048. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17049. return maybeTrusted;
  17050. }
  17051. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17052. if (constructor && maybeTrusted instanceof constructor) {
  17053. return maybeTrusted.$$unwrapTrustedValue();
  17054. }
  17055. // If we get here, then we may only take one of two actions.
  17056. // 1. sanitize the value for the requested type, or
  17057. // 2. throw an exception.
  17058. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17059. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17060. return maybeTrusted;
  17061. } else {
  17062. throw $sceMinErr('insecurl',
  17063. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17064. maybeTrusted.toString());
  17065. }
  17066. } else if (type === SCE_CONTEXTS.HTML) {
  17067. return htmlSanitizer(maybeTrusted);
  17068. }
  17069. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17070. }
  17071. return { trustAs: trustAs,
  17072. getTrusted: getTrusted,
  17073. valueOf: valueOf };
  17074. }];
  17075. }
  17076. /**
  17077. * @ngdoc provider
  17078. * @name $sceProvider
  17079. * @this
  17080. *
  17081. * @description
  17082. *
  17083. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17084. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17085. * - override the default implementation with a custom delegate
  17086. *
  17087. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17088. */
  17089. /**
  17090. * @ngdoc service
  17091. * @name $sce
  17092. * @kind function
  17093. *
  17094. * @description
  17095. *
  17096. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17097. *
  17098. * # Strict Contextual Escaping
  17099. *
  17100. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  17101. * contexts to result in a value that is marked as safe to use for that context. One example of
  17102. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  17103. * to these contexts as privileged or SCE contexts.
  17104. *
  17105. * As of version 1.2, Angular ships with SCE enabled by default.
  17106. *
  17107. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  17108. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  17109. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  17110. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  17111. * to the top of your HTML document.
  17112. *
  17113. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  17114. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17115. *
  17116. * Here's an example of a binding in a privileged context:
  17117. *
  17118. * ```
  17119. * <input ng-model="userHtml" aria-label="User input">
  17120. * <div ng-bind-html="userHtml"></div>
  17121. * ```
  17122. *
  17123. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17124. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  17125. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  17126. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  17127. * security vulnerabilities.)
  17128. *
  17129. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17130. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17131. *
  17132. * How would you ensure that every place that used these types of bindings was bound to a value that
  17133. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17134. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17135. * properties/fields and forgot to update the binding to the sanitized value?
  17136. *
  17137. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  17138. * determine that something explicitly says it's safe to use a value for binding in that
  17139. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  17140. * for those values that you can easily tell are safe - because they were received from your server,
  17141. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  17142. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  17143. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  17144. *
  17145. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17146. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17147. * obtain values that will be accepted by SCE / privileged contexts.
  17148. *
  17149. *
  17150. * ## How does it work?
  17151. *
  17152. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17153. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  17154. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  17155. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  17156. *
  17157. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17158. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17159. * simplified):
  17160. *
  17161. * ```
  17162. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17163. * return function(scope, element, attr) {
  17164. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17165. * element.html(value || '');
  17166. * });
  17167. * };
  17168. * }];
  17169. * ```
  17170. *
  17171. * ## Impact on loading templates
  17172. *
  17173. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17174. * `templateUrl`'s specified by {@link guide/directive directives}.
  17175. *
  17176. * By default, Angular only loads templates from the same domain and protocol as the application
  17177. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17178. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17179. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17180. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17181. *
  17182. * *Please note*:
  17183. * The browser's
  17184. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17185. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17186. * policy apply in addition to this and may further restrict whether the template is successfully
  17187. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17188. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17189. * browsers.
  17190. *
  17191. * ## This feels like too much overhead
  17192. *
  17193. * It's important to remember that SCE only applies to interpolation expressions.
  17194. *
  17195. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17196. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  17197. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  17198. *
  17199. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17200. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  17201. *
  17202. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17203. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17204. * It blocks loading templates from other domains or loading templates over http from an https
  17205. * served document. You can change these by setting your own custom {@link
  17206. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17207. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17208. *
  17209. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17210. * application that's secure and can be audited to verify that with much more ease than bolting
  17211. * security onto an application later.
  17212. *
  17213. * <a name="contexts"></a>
  17214. * ## What trusted context types are supported?
  17215. *
  17216. * | Context | Notes |
  17217. * |---------------------|----------------|
  17218. * | `$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. |
  17219. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  17220. * | `$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. |
  17221. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17222. * | `$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. |
  17223. *
  17224. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17225. *
  17226. * Each element in these arrays must be one of the following:
  17227. *
  17228. * - **'self'**
  17229. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17230. * domain** as the application document using the **same protocol**.
  17231. * - **String** (except the special value `'self'`)
  17232. * - The string is matched against the full *normalized / absolute URL* of the resource
  17233. * being tested (substring matches are not good enough.)
  17234. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17235. * match themselves.
  17236. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17237. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17238. * in a whitelist.
  17239. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17240. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17241. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17242. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17243. * http://foo.example.com/templates/**).
  17244. * - **RegExp** (*see caveat below*)
  17245. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17246. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17247. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17248. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17249. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17250. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17251. * is highly recommended to use the string patterns and only fall back to regular expressions
  17252. * as a last resort.
  17253. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17254. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17255. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17256. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17257. * - If you are generating your JavaScript from some other templating engine (not
  17258. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17259. * remember to escape your regular expression (and be aware that you might need more than
  17260. * one level of escaping depending on your templating engine and the way you interpolated
  17261. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17262. * enough before coding your own. E.g. Ruby has
  17263. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17264. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17265. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17266. * Closure library's [goog.string.regExpEscape(s)](
  17267. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17268. *
  17269. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17270. *
  17271. * ## Show me an example using SCE.
  17272. *
  17273. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17274. * <file name="index.html">
  17275. * <div ng-controller="AppController as myCtrl">
  17276. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17277. * <b>User comments</b><br>
  17278. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17279. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17280. * exploit.
  17281. * <div class="well">
  17282. * <div ng-repeat="userComment in myCtrl.userComments">
  17283. * <b>{{userComment.name}}</b>:
  17284. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17285. * <br>
  17286. * </div>
  17287. * </div>
  17288. * </div>
  17289. * </file>
  17290. *
  17291. * <file name="script.js">
  17292. * angular.module('mySceApp', ['ngSanitize'])
  17293. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17294. * function AppController($http, $templateCache, $sce) {
  17295. * var self = this;
  17296. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17297. * self.userComments = response.data;
  17298. * });
  17299. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17300. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17301. * 'sanitization.&quot;">Hover over this text.</span>');
  17302. * }]);
  17303. * </file>
  17304. *
  17305. * <file name="test_data.json">
  17306. * [
  17307. * { "name": "Alice",
  17308. * "htmlComment":
  17309. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17310. * },
  17311. * { "name": "Bob",
  17312. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17313. * }
  17314. * ]
  17315. * </file>
  17316. *
  17317. * <file name="protractor.js" type="protractor">
  17318. * describe('SCE doc demo', function() {
  17319. * it('should sanitize untrusted values', function() {
  17320. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17321. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17322. * });
  17323. *
  17324. * it('should NOT sanitize explicitly trusted values', function() {
  17325. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17326. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17327. * 'sanitization.&quot;">Hover over this text.</span>');
  17328. * });
  17329. * });
  17330. * </file>
  17331. * </example>
  17332. *
  17333. *
  17334. *
  17335. * ## Can I disable SCE completely?
  17336. *
  17337. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17338. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17339. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17340. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17341. * you're migrating them a module at a time.
  17342. *
  17343. * That said, here's how you can completely disable SCE:
  17344. *
  17345. * ```
  17346. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17347. * // Completely disable SCE. For demonstration purposes only!
  17348. * // Do not use in new projects.
  17349. * $sceProvider.enabled(false);
  17350. * });
  17351. * ```
  17352. *
  17353. */
  17354. function $SceProvider() {
  17355. var enabled = true;
  17356. /**
  17357. * @ngdoc method
  17358. * @name $sceProvider#enabled
  17359. * @kind function
  17360. *
  17361. * @param {boolean=} value If provided, then enables/disables SCE.
  17362. * @return {boolean} true if SCE is enabled, false otherwise.
  17363. *
  17364. * @description
  17365. * Enables/disables SCE and returns the current value.
  17366. */
  17367. this.enabled = function(value) {
  17368. if (arguments.length) {
  17369. enabled = !!value;
  17370. }
  17371. return enabled;
  17372. };
  17373. /* Design notes on the default implementation for SCE.
  17374. *
  17375. * The API contract for the SCE delegate
  17376. * -------------------------------------
  17377. * The SCE delegate object must provide the following 3 methods:
  17378. *
  17379. * - trustAs(contextEnum, value)
  17380. * This method is used to tell the SCE service that the provided value is OK to use in the
  17381. * contexts specified by contextEnum. It must return an object that will be accepted by
  17382. * getTrusted() for a compatible contextEnum and return this value.
  17383. *
  17384. * - valueOf(value)
  17385. * For values that were not produced by trustAs(), return them as is. For values that were
  17386. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17387. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17388. * such a value.
  17389. *
  17390. * - getTrusted(contextEnum, value)
  17391. * This function should return the a value that is safe to use in the context specified by
  17392. * contextEnum or throw and exception otherwise.
  17393. *
  17394. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17395. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17396. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17397. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17398. * return the same object passed in if it was found in the registry under a compatible context or
  17399. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17400. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17401. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17402. *
  17403. *
  17404. * A note on the inheritance model for SCE contexts
  17405. * ------------------------------------------------
  17406. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17407. * is purely an implementation details.
  17408. *
  17409. * The contract is simply this:
  17410. *
  17411. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17412. * will also succeed.
  17413. *
  17414. * Inheritance happens to capture this in a natural way. In some future, we
  17415. * may not use inheritance anymore. That is OK because no code outside of
  17416. * sce.js and sceSpecs.js would need to be aware of this detail.
  17417. */
  17418. this.$get = ['$parse', '$sceDelegate', function(
  17419. $parse, $sceDelegate) {
  17420. // Support: IE 9-11 only
  17421. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17422. // the "expression(javascript expression)" syntax which is insecure.
  17423. if (enabled && msie < 8) {
  17424. throw $sceMinErr('iequirks',
  17425. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17426. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17427. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17428. }
  17429. var sce = shallowCopy(SCE_CONTEXTS);
  17430. /**
  17431. * @ngdoc method
  17432. * @name $sce#isEnabled
  17433. * @kind function
  17434. *
  17435. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  17436. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17437. *
  17438. * @description
  17439. * Returns a boolean indicating if SCE is enabled.
  17440. */
  17441. sce.isEnabled = function() {
  17442. return enabled;
  17443. };
  17444. sce.trustAs = $sceDelegate.trustAs;
  17445. sce.getTrusted = $sceDelegate.getTrusted;
  17446. sce.valueOf = $sceDelegate.valueOf;
  17447. if (!enabled) {
  17448. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17449. sce.valueOf = identity;
  17450. }
  17451. /**
  17452. * @ngdoc method
  17453. * @name $sce#parseAs
  17454. *
  17455. * @description
  17456. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17457. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17458. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17459. * *result*)}
  17460. *
  17461. * @param {string} type The kind of SCE context in which this result will be used.
  17462. * @param {string} expression String expression to compile.
  17463. * @returns {function(context, locals)} a function which represents the compiled expression:
  17464. *
  17465. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17466. * are evaluated against (typically a scope object).
  17467. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17468. * `context`.
  17469. */
  17470. sce.parseAs = function sceParseAs(type, expr) {
  17471. var parsed = $parse(expr);
  17472. if (parsed.literal && parsed.constant) {
  17473. return parsed;
  17474. } else {
  17475. return $parse(expr, function(value) {
  17476. return sce.getTrusted(type, value);
  17477. });
  17478. }
  17479. };
  17480. /**
  17481. * @ngdoc method
  17482. * @name $sce#trustAs
  17483. *
  17484. * @description
  17485. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  17486. * returns an object that is trusted by angular for use in specified strict contextual
  17487. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  17488. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  17489. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  17490. * escaping.
  17491. *
  17492. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17493. * resourceUrl, html, js and css.
  17494. * @param {*} value The value that that should be considered trusted/safe.
  17495. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17496. * where Angular expects a $sce.trustAs() return value.
  17497. */
  17498. /**
  17499. * @ngdoc method
  17500. * @name $sce#trustAsHtml
  17501. *
  17502. * @description
  17503. * Shorthand method. `$sce.trustAsHtml(value)` →
  17504. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17505. *
  17506. * @param {*} value The value to trustAs.
  17507. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17508. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17509. * only accept expressions that are either literal constants or are the
  17510. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17511. */
  17512. /**
  17513. * @ngdoc method
  17514. * @name $sce#trustAsUrl
  17515. *
  17516. * @description
  17517. * Shorthand method. `$sce.trustAsUrl(value)` →
  17518. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17519. *
  17520. * @param {*} value The value to trustAs.
  17521. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17522. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17523. * only accept expressions that are either literal constants or are the
  17524. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17525. */
  17526. /**
  17527. * @ngdoc method
  17528. * @name $sce#trustAsResourceUrl
  17529. *
  17530. * @description
  17531. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17532. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17533. *
  17534. * @param {*} value The value to trustAs.
  17535. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17536. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17537. * only accept expressions that are either literal constants or are the return
  17538. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17539. */
  17540. /**
  17541. * @ngdoc method
  17542. * @name $sce#trustAsJs
  17543. *
  17544. * @description
  17545. * Shorthand method. `$sce.trustAsJs(value)` →
  17546. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17547. *
  17548. * @param {*} value The value to trustAs.
  17549. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17550. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17551. * only accept expressions that are either literal constants or are the
  17552. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17553. */
  17554. /**
  17555. * @ngdoc method
  17556. * @name $sce#getTrusted
  17557. *
  17558. * @description
  17559. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17560. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17561. * originally supplied value if the queried context type is a supertype of the created type.
  17562. * If this condition isn't satisfied, throws an exception.
  17563. *
  17564. * @param {string} type The kind of context in which this value is to be used.
  17565. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17566. * call.
  17567. * @returns {*} The value the was originally provided to
  17568. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17569. * Otherwise, throws an exception.
  17570. */
  17571. /**
  17572. * @ngdoc method
  17573. * @name $sce#getTrustedHtml
  17574. *
  17575. * @description
  17576. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17577. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17578. *
  17579. * @param {*} value The value to pass to `$sce.getTrusted`.
  17580. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17581. */
  17582. /**
  17583. * @ngdoc method
  17584. * @name $sce#getTrustedCss
  17585. *
  17586. * @description
  17587. * Shorthand method. `$sce.getTrustedCss(value)` →
  17588. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17589. *
  17590. * @param {*} value The value to pass to `$sce.getTrusted`.
  17591. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17592. */
  17593. /**
  17594. * @ngdoc method
  17595. * @name $sce#getTrustedUrl
  17596. *
  17597. * @description
  17598. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17599. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17600. *
  17601. * @param {*} value The value to pass to `$sce.getTrusted`.
  17602. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17603. */
  17604. /**
  17605. * @ngdoc method
  17606. * @name $sce#getTrustedResourceUrl
  17607. *
  17608. * @description
  17609. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17610. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17611. *
  17612. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17613. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17614. */
  17615. /**
  17616. * @ngdoc method
  17617. * @name $sce#getTrustedJs
  17618. *
  17619. * @description
  17620. * Shorthand method. `$sce.getTrustedJs(value)` →
  17621. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17622. *
  17623. * @param {*} value The value to pass to `$sce.getTrusted`.
  17624. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17625. */
  17626. /**
  17627. * @ngdoc method
  17628. * @name $sce#parseAsHtml
  17629. *
  17630. * @description
  17631. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17632. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17633. *
  17634. * @param {string} expression String expression to compile.
  17635. * @returns {function(context, locals)} a function which represents the compiled expression:
  17636. *
  17637. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17638. * are evaluated against (typically a scope object).
  17639. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17640. * `context`.
  17641. */
  17642. /**
  17643. * @ngdoc method
  17644. * @name $sce#parseAsCss
  17645. *
  17646. * @description
  17647. * Shorthand method. `$sce.parseAsCss(value)` →
  17648. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17649. *
  17650. * @param {string} expression String expression to compile.
  17651. * @returns {function(context, locals)} a function which represents the compiled expression:
  17652. *
  17653. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17654. * are evaluated against (typically a scope object).
  17655. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17656. * `context`.
  17657. */
  17658. /**
  17659. * @ngdoc method
  17660. * @name $sce#parseAsUrl
  17661. *
  17662. * @description
  17663. * Shorthand method. `$sce.parseAsUrl(value)` →
  17664. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17665. *
  17666. * @param {string} expression String expression to compile.
  17667. * @returns {function(context, locals)} a function which represents the compiled expression:
  17668. *
  17669. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17670. * are evaluated against (typically a scope object).
  17671. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17672. * `context`.
  17673. */
  17674. /**
  17675. * @ngdoc method
  17676. * @name $sce#parseAsResourceUrl
  17677. *
  17678. * @description
  17679. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17680. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17681. *
  17682. * @param {string} expression String expression to compile.
  17683. * @returns {function(context, locals)} a function which represents the compiled expression:
  17684. *
  17685. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17686. * are evaluated against (typically a scope object).
  17687. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17688. * `context`.
  17689. */
  17690. /**
  17691. * @ngdoc method
  17692. * @name $sce#parseAsJs
  17693. *
  17694. * @description
  17695. * Shorthand method. `$sce.parseAsJs(value)` →
  17696. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17697. *
  17698. * @param {string} expression String expression to compile.
  17699. * @returns {function(context, locals)} a function which represents the compiled expression:
  17700. *
  17701. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17702. * are evaluated against (typically a scope object).
  17703. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17704. * `context`.
  17705. */
  17706. // Shorthand delegations.
  17707. var parse = sce.parseAs,
  17708. getTrusted = sce.getTrusted,
  17709. trustAs = sce.trustAs;
  17710. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17711. var lName = lowercase(name);
  17712. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  17713. return parse(enumValue, expr);
  17714. };
  17715. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  17716. return getTrusted(enumValue, value);
  17717. };
  17718. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  17719. return trustAs(enumValue, value);
  17720. };
  17721. });
  17722. return sce;
  17723. }];
  17724. }
  17725. /* exported $SnifferProvider */
  17726. /**
  17727. * !!! This is an undocumented "private" service !!!
  17728. *
  17729. * @name $sniffer
  17730. * @requires $window
  17731. * @requires $document
  17732. * @this
  17733. *
  17734. * @property {boolean} history Does the browser support html5 history api ?
  17735. * @property {boolean} transitions Does the browser support CSS transition events ?
  17736. * @property {boolean} animations Does the browser support CSS animation events ?
  17737. *
  17738. * @description
  17739. * This is very simple implementation of testing browser's features.
  17740. */
  17741. function $SnifferProvider() {
  17742. this.$get = ['$window', '$document', function($window, $document) {
  17743. var eventSupport = {},
  17744. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  17745. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  17746. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  17747. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  17748. // (see https://developer.chrome.com/apps/manifest/sandbox).
  17749. isChromePackagedApp =
  17750. $window.chrome &&
  17751. ($window.chrome.app && $window.chrome.app.runtime ||
  17752. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  17753. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17754. android =
  17755. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17756. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17757. document = $document[0] || {},
  17758. bodyStyle = document.body && document.body.style,
  17759. transitions = false,
  17760. animations = false;
  17761. if (bodyStyle) {
  17762. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  17763. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  17764. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  17765. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  17766. }
  17767. return {
  17768. // Android has history.pushState, but it does not update location correctly
  17769. // so let's not use the history API at all.
  17770. // http://code.google.com/p/android/issues/detail?id=17471
  17771. // https://github.com/angular/angular.js/issues/904
  17772. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17773. // so let's not use the history API also
  17774. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17775. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17776. hasEvent: function(event) {
  17777. // Support: IE 9-11 only
  17778. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17779. // it. In particular the event is not fired when backspace or delete key are pressed or
  17780. // when cut operation is performed.
  17781. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17782. // e.g. when placeholder changes, or a form is focused.
  17783. if (event === 'input' && msie) return false;
  17784. if (isUndefined(eventSupport[event])) {
  17785. var divElm = document.createElement('div');
  17786. eventSupport[event] = 'on' + event in divElm;
  17787. }
  17788. return eventSupport[event];
  17789. },
  17790. csp: csp(),
  17791. transitions: transitions,
  17792. animations: animations,
  17793. android: android
  17794. };
  17795. }];
  17796. }
  17797. var $templateRequestMinErr = minErr('$compile');
  17798. /**
  17799. * @ngdoc provider
  17800. * @name $templateRequestProvider
  17801. * @this
  17802. *
  17803. * @description
  17804. * Used to configure the options passed to the {@link $http} service when making a template request.
  17805. *
  17806. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17807. * requesting a template.
  17808. */
  17809. function $TemplateRequestProvider() {
  17810. var httpOptions;
  17811. /**
  17812. * @ngdoc method
  17813. * @name $templateRequestProvider#httpOptions
  17814. * @description
  17815. * The options to be passed to the {@link $http} service when making the request.
  17816. * You can use this to override options such as the "Accept" header for template requests.
  17817. *
  17818. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  17819. * options if not overridden here.
  17820. *
  17821. * @param {string=} value new value for the {@link $http} options.
  17822. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  17823. */
  17824. this.httpOptions = function(val) {
  17825. if (val) {
  17826. httpOptions = val;
  17827. return this;
  17828. }
  17829. return httpOptions;
  17830. };
  17831. /**
  17832. * @ngdoc service
  17833. * @name $templateRequest
  17834. *
  17835. * @description
  17836. * The `$templateRequest` service runs security checks then downloads the provided template using
  17837. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  17838. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  17839. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  17840. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  17841. * when `tpl` is of type string and `$templateCache` has the matching entry.
  17842. *
  17843. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  17844. * can configure this via {@link $templateRequestProvider#httpOptions}.
  17845. *
  17846. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  17847. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  17848. *
  17849. * @return {Promise} a promise for the HTTP response data of the given URL.
  17850. *
  17851. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  17852. */
  17853. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  17854. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  17855. function handleRequestFn(tpl, ignoreRequestError) {
  17856. handleRequestFn.totalPendingRequests++;
  17857. // We consider the template cache holds only trusted templates, so
  17858. // there's no need to go through whitelisting again for keys that already
  17859. // are included in there. This also makes Angular accept any script
  17860. // directive, no matter its name. However, we still need to unwrap trusted
  17861. // types.
  17862. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  17863. tpl = $sce.getTrustedResourceUrl(tpl);
  17864. }
  17865. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  17866. if (isArray(transformResponse)) {
  17867. transformResponse = transformResponse.filter(function(transformer) {
  17868. return transformer !== defaultHttpResponseTransform;
  17869. });
  17870. } else if (transformResponse === defaultHttpResponseTransform) {
  17871. transformResponse = null;
  17872. }
  17873. return $http.get(tpl, extend({
  17874. cache: $templateCache,
  17875. transformResponse: transformResponse
  17876. }, httpOptions))
  17877. .finally(function() {
  17878. handleRequestFn.totalPendingRequests--;
  17879. })
  17880. .then(function(response) {
  17881. $templateCache.put(tpl, response.data);
  17882. return response.data;
  17883. }, handleError);
  17884. function handleError(resp) {
  17885. if (!ignoreRequestError) {
  17886. resp = $templateRequestMinErr('tpload',
  17887. 'Failed to load template: {0} (HTTP status: {1} {2})',
  17888. tpl, resp.status, resp.statusText);
  17889. $exceptionHandler(resp);
  17890. }
  17891. return $q.reject(resp);
  17892. }
  17893. }
  17894. handleRequestFn.totalPendingRequests = 0;
  17895. return handleRequestFn;
  17896. }
  17897. ];
  17898. }
  17899. /** @this */
  17900. function $$TestabilityProvider() {
  17901. this.$get = ['$rootScope', '$browser', '$location',
  17902. function($rootScope, $browser, $location) {
  17903. /**
  17904. * @name $testability
  17905. *
  17906. * @description
  17907. * The private $$testability service provides a collection of methods for use when debugging
  17908. * or by automated test and debugging tools.
  17909. */
  17910. var testability = {};
  17911. /**
  17912. * @name $$testability#findBindings
  17913. *
  17914. * @description
  17915. * Returns an array of elements that are bound (via ng-bind or {{}})
  17916. * to expressions matching the input.
  17917. *
  17918. * @param {Element} element The element root to search from.
  17919. * @param {string} expression The binding expression to match.
  17920. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17921. * for the expression. Filters and whitespace are ignored.
  17922. */
  17923. testability.findBindings = function(element, expression, opt_exactMatch) {
  17924. var bindings = element.getElementsByClassName('ng-binding');
  17925. var matches = [];
  17926. forEach(bindings, function(binding) {
  17927. var dataBinding = angular.element(binding).data('$binding');
  17928. if (dataBinding) {
  17929. forEach(dataBinding, function(bindingName) {
  17930. if (opt_exactMatch) {
  17931. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  17932. if (matcher.test(bindingName)) {
  17933. matches.push(binding);
  17934. }
  17935. } else {
  17936. if (bindingName.indexOf(expression) !== -1) {
  17937. matches.push(binding);
  17938. }
  17939. }
  17940. });
  17941. }
  17942. });
  17943. return matches;
  17944. };
  17945. /**
  17946. * @name $$testability#findModels
  17947. *
  17948. * @description
  17949. * Returns an array of elements that are two-way found via ng-model to
  17950. * expressions matching the input.
  17951. *
  17952. * @param {Element} element The element root to search from.
  17953. * @param {string} expression The model expression to match.
  17954. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17955. * for the expression.
  17956. */
  17957. testability.findModels = function(element, expression, opt_exactMatch) {
  17958. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  17959. for (var p = 0; p < prefixes.length; ++p) {
  17960. var attributeEquals = opt_exactMatch ? '=' : '*=';
  17961. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  17962. var elements = element.querySelectorAll(selector);
  17963. if (elements.length) {
  17964. return elements;
  17965. }
  17966. }
  17967. };
  17968. /**
  17969. * @name $$testability#getLocation
  17970. *
  17971. * @description
  17972. * Shortcut for getting the location in a browser agnostic way. Returns
  17973. * the path, search, and hash. (e.g. /path?a=b#hash)
  17974. */
  17975. testability.getLocation = function() {
  17976. return $location.url();
  17977. };
  17978. /**
  17979. * @name $$testability#setLocation
  17980. *
  17981. * @description
  17982. * Shortcut for navigating to a location without doing a full page reload.
  17983. *
  17984. * @param {string} url The location url (path, search and hash,
  17985. * e.g. /path?a=b#hash) to go to.
  17986. */
  17987. testability.setLocation = function(url) {
  17988. if (url !== $location.url()) {
  17989. $location.url(url);
  17990. $rootScope.$digest();
  17991. }
  17992. };
  17993. /**
  17994. * @name $$testability#whenStable
  17995. *
  17996. * @description
  17997. * Calls the callback when $timeout and $http requests are completed.
  17998. *
  17999. * @param {function} callback
  18000. */
  18001. testability.whenStable = function(callback) {
  18002. $browser.notifyWhenNoOutstandingRequests(callback);
  18003. };
  18004. return testability;
  18005. }];
  18006. }
  18007. /** @this */
  18008. function $TimeoutProvider() {
  18009. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18010. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18011. var deferreds = {};
  18012. /**
  18013. * @ngdoc service
  18014. * @name $timeout
  18015. *
  18016. * @description
  18017. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18018. * block and delegates any exceptions to
  18019. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18020. *
  18021. * The return value of calling `$timeout` is a promise, which will be resolved when
  18022. * the delay has passed and the timeout function, if provided, is executed.
  18023. *
  18024. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18025. *
  18026. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18027. * synchronously flush the queue of deferred functions.
  18028. *
  18029. * If you only want a promise that will be resolved after some specified delay
  18030. * then you can call `$timeout` without the `fn` function.
  18031. *
  18032. * @param {function()=} fn A function, whose execution should be delayed.
  18033. * @param {number=} [delay=0] Delay in milliseconds.
  18034. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18035. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18036. * @param {...*=} Pass additional parameters to the executed function.
  18037. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18038. * will be resolved with the return value of the `fn` function.
  18039. *
  18040. */
  18041. function timeout(fn, delay, invokeApply) {
  18042. if (!isFunction(fn)) {
  18043. invokeApply = delay;
  18044. delay = fn;
  18045. fn = noop;
  18046. }
  18047. var args = sliceArgs(arguments, 3),
  18048. skipApply = (isDefined(invokeApply) && !invokeApply),
  18049. deferred = (skipApply ? $$q : $q).defer(),
  18050. promise = deferred.promise,
  18051. timeoutId;
  18052. timeoutId = $browser.defer(function() {
  18053. try {
  18054. deferred.resolve(fn.apply(null, args));
  18055. } catch (e) {
  18056. deferred.reject(e);
  18057. $exceptionHandler(e);
  18058. } finally {
  18059. delete deferreds[promise.$$timeoutId];
  18060. }
  18061. if (!skipApply) $rootScope.$apply();
  18062. }, delay);
  18063. promise.$$timeoutId = timeoutId;
  18064. deferreds[timeoutId] = deferred;
  18065. return promise;
  18066. }
  18067. /**
  18068. * @ngdoc method
  18069. * @name $timeout#cancel
  18070. *
  18071. * @description
  18072. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18073. * resolved with a rejection.
  18074. *
  18075. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18076. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18077. * canceled.
  18078. */
  18079. timeout.cancel = function(promise) {
  18080. if (promise && promise.$$timeoutId in deferreds) {
  18081. // Timeout cancels should not report an unhandled promise.
  18082. deferreds[promise.$$timeoutId].promise.catch(noop);
  18083. deferreds[promise.$$timeoutId].reject('canceled');
  18084. delete deferreds[promise.$$timeoutId];
  18085. return $browser.defer.cancel(promise.$$timeoutId);
  18086. }
  18087. return false;
  18088. };
  18089. return timeout;
  18090. }];
  18091. }
  18092. // NOTE: The usage of window and document instead of $window and $document here is
  18093. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18094. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18095. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18096. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18097. // exactly the behavior needed here. There is little value is mocking these out for this
  18098. // service.
  18099. var urlParsingNode = window.document.createElement('a');
  18100. var originUrl = urlResolve(window.location.href);
  18101. /**
  18102. *
  18103. * Implementation Notes for non-IE browsers
  18104. * ----------------------------------------
  18105. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18106. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18107. * URL will be resolved into an absolute URL in the context of the application document.
  18108. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18109. * properties are all populated to reflect the normalized URL. This approach has wide
  18110. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  18111. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18112. *
  18113. * Implementation Notes for IE
  18114. * ---------------------------
  18115. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18116. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18117. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18118. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18119. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18120. * properties such as protocol, hostname, port, etc.
  18121. *
  18122. * References:
  18123. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18124. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18125. * http://url.spec.whatwg.org/#urlutils
  18126. * https://github.com/angular/angular.js/pull/2902
  18127. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18128. *
  18129. * @kind function
  18130. * @param {string} url The URL to be parsed.
  18131. * @description Normalizes and parses a URL.
  18132. * @returns {object} Returns the normalized URL as a dictionary.
  18133. *
  18134. * | member name | Description |
  18135. * |---------------|----------------|
  18136. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18137. * | protocol | The protocol including the trailing colon |
  18138. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18139. * | search | The search params, minus the question mark |
  18140. * | hash | The hash string, minus the hash symbol
  18141. * | hostname | The hostname
  18142. * | port | The port, without ":"
  18143. * | pathname | The pathname, beginning with "/"
  18144. *
  18145. */
  18146. function urlResolve(url) {
  18147. var href = url;
  18148. // Support: IE 9-11 only
  18149. if (msie) {
  18150. // Normalize before parse. Refer Implementation Notes on why this is
  18151. // done in two steps on IE.
  18152. urlParsingNode.setAttribute('href', href);
  18153. href = urlParsingNode.href;
  18154. }
  18155. urlParsingNode.setAttribute('href', href);
  18156. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18157. return {
  18158. href: urlParsingNode.href,
  18159. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18160. host: urlParsingNode.host,
  18161. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18162. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18163. hostname: urlParsingNode.hostname,
  18164. port: urlParsingNode.port,
  18165. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18166. ? urlParsingNode.pathname
  18167. : '/' + urlParsingNode.pathname
  18168. };
  18169. }
  18170. /**
  18171. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18172. *
  18173. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18174. * or a parsed URL object.
  18175. * @returns {boolean} Whether the request is for the same origin as the application document.
  18176. */
  18177. function urlIsSameOrigin(requestUrl) {
  18178. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18179. return (parsed.protocol === originUrl.protocol &&
  18180. parsed.host === originUrl.host);
  18181. }
  18182. /**
  18183. * @ngdoc service
  18184. * @name $window
  18185. * @this
  18186. *
  18187. * @description
  18188. * A reference to the browser's `window` object. While `window`
  18189. * is globally available in JavaScript, it causes testability problems, because
  18190. * it is a global variable. In angular we always refer to it through the
  18191. * `$window` service, so it may be overridden, removed or mocked for testing.
  18192. *
  18193. * Expressions, like the one defined for the `ngClick` directive in the example
  18194. * below, are evaluated with respect to the current scope. Therefore, there is
  18195. * no risk of inadvertently coding in a dependency on a global value in such an
  18196. * expression.
  18197. *
  18198. * @example
  18199. <example module="windowExample" name="window-service">
  18200. <file name="index.html">
  18201. <script>
  18202. angular.module('windowExample', [])
  18203. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18204. $scope.greeting = 'Hello, World!';
  18205. $scope.doGreeting = function(greeting) {
  18206. $window.alert(greeting);
  18207. };
  18208. }]);
  18209. </script>
  18210. <div ng-controller="ExampleController">
  18211. <input type="text" ng-model="greeting" aria-label="greeting" />
  18212. <button ng-click="doGreeting(greeting)">ALERT</button>
  18213. </div>
  18214. </file>
  18215. <file name="protractor.js" type="protractor">
  18216. it('should display the greeting in the input box', function() {
  18217. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18218. // If we click the button it will block the test runner
  18219. // element(':button').click();
  18220. });
  18221. </file>
  18222. </example>
  18223. */
  18224. function $WindowProvider() {
  18225. this.$get = valueFn(window);
  18226. }
  18227. /**
  18228. * @name $$cookieReader
  18229. * @requires $document
  18230. *
  18231. * @description
  18232. * This is a private service for reading cookies used by $http and ngCookies
  18233. *
  18234. * @return {Object} a key/value map of the current cookies
  18235. */
  18236. function $$CookieReader($document) {
  18237. var rawDocument = $document[0] || {};
  18238. var lastCookies = {};
  18239. var lastCookieString = '';
  18240. function safeGetCookie(rawDocument) {
  18241. try {
  18242. return rawDocument.cookie || '';
  18243. } catch (e) {
  18244. return '';
  18245. }
  18246. }
  18247. function safeDecodeURIComponent(str) {
  18248. try {
  18249. return decodeURIComponent(str);
  18250. } catch (e) {
  18251. return str;
  18252. }
  18253. }
  18254. return function() {
  18255. var cookieArray, cookie, i, index, name;
  18256. var currentCookieString = safeGetCookie(rawDocument);
  18257. if (currentCookieString !== lastCookieString) {
  18258. lastCookieString = currentCookieString;
  18259. cookieArray = lastCookieString.split('; ');
  18260. lastCookies = {};
  18261. for (i = 0; i < cookieArray.length; i++) {
  18262. cookie = cookieArray[i];
  18263. index = cookie.indexOf('=');
  18264. if (index > 0) { //ignore nameless cookies
  18265. name = safeDecodeURIComponent(cookie.substring(0, index));
  18266. // the first value that is seen for a cookie is the most
  18267. // specific one. values for the same cookie name that
  18268. // follow are for less specific paths.
  18269. if (isUndefined(lastCookies[name])) {
  18270. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18271. }
  18272. }
  18273. }
  18274. }
  18275. return lastCookies;
  18276. };
  18277. }
  18278. $$CookieReader.$inject = ['$document'];
  18279. /** @this */
  18280. function $$CookieReaderProvider() {
  18281. this.$get = $$CookieReader;
  18282. }
  18283. /* global currencyFilter: true,
  18284. dateFilter: true,
  18285. filterFilter: true,
  18286. jsonFilter: true,
  18287. limitToFilter: true,
  18288. lowercaseFilter: true,
  18289. numberFilter: true,
  18290. orderByFilter: true,
  18291. uppercaseFilter: true,
  18292. */
  18293. /**
  18294. * @ngdoc provider
  18295. * @name $filterProvider
  18296. * @description
  18297. *
  18298. * Filters are just functions which transform input to an output. However filters need to be
  18299. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18300. * annotated with dependencies and is responsible for creating a filter function.
  18301. *
  18302. * <div class="alert alert-warning">
  18303. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18304. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18305. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18306. * (`myapp_subsection_filterx`).
  18307. * </div>
  18308. *
  18309. * ```js
  18310. * // Filter registration
  18311. * function MyModule($provide, $filterProvider) {
  18312. * // create a service to demonstrate injection (not always needed)
  18313. * $provide.value('greet', function(name){
  18314. * return 'Hello ' + name + '!';
  18315. * });
  18316. *
  18317. * // register a filter factory which uses the
  18318. * // greet service to demonstrate DI.
  18319. * $filterProvider.register('greet', function(greet){
  18320. * // return the filter function which uses the greet service
  18321. * // to generate salutation
  18322. * return function(text) {
  18323. * // filters need to be forgiving so check input validity
  18324. * return text && greet(text) || text;
  18325. * };
  18326. * });
  18327. * }
  18328. * ```
  18329. *
  18330. * The filter function is registered with the `$injector` under the filter name suffix with
  18331. * `Filter`.
  18332. *
  18333. * ```js
  18334. * it('should be the same instance', inject(
  18335. * function($filterProvider) {
  18336. * $filterProvider.register('reverse', function(){
  18337. * return ...;
  18338. * });
  18339. * },
  18340. * function($filter, reverseFilter) {
  18341. * expect($filter('reverse')).toBe(reverseFilter);
  18342. * });
  18343. * ```
  18344. *
  18345. *
  18346. * For more information about how angular filters work, and how to create your own filters, see
  18347. * {@link guide/filter Filters} in the Angular Developer Guide.
  18348. */
  18349. /**
  18350. * @ngdoc service
  18351. * @name $filter
  18352. * @kind function
  18353. * @description
  18354. * Filters are used for formatting data displayed to the user.
  18355. *
  18356. * They can be used in view templates, controllers or services.Angular comes
  18357. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18358. * define your own as well.
  18359. *
  18360. * The general syntax in templates is as follows:
  18361. *
  18362. * ```html
  18363. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18364. * ```
  18365. *
  18366. * @param {String} name Name of the filter function to retrieve
  18367. * @return {Function} the filter function
  18368. * @example
  18369. <example name="$filter" module="filterExample">
  18370. <file name="index.html">
  18371. <div ng-controller="MainCtrl">
  18372. <h3>{{ originalText }}</h3>
  18373. <h3>{{ filteredText }}</h3>
  18374. </div>
  18375. </file>
  18376. <file name="script.js">
  18377. angular.module('filterExample', [])
  18378. .controller('MainCtrl', function($scope, $filter) {
  18379. $scope.originalText = 'hello';
  18380. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18381. });
  18382. </file>
  18383. </example>
  18384. */
  18385. $FilterProvider.$inject = ['$provide'];
  18386. /** @this */
  18387. function $FilterProvider($provide) {
  18388. var suffix = 'Filter';
  18389. /**
  18390. * @ngdoc method
  18391. * @name $filterProvider#register
  18392. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18393. * the keys are the filter names and the values are the filter factories.
  18394. *
  18395. * <div class="alert alert-warning">
  18396. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18397. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18398. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18399. * (`myapp_subsection_filterx`).
  18400. * </div>
  18401. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18402. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18403. * of the registered filter instances.
  18404. */
  18405. function register(name, factory) {
  18406. if (isObject(name)) {
  18407. var filters = {};
  18408. forEach(name, function(filter, key) {
  18409. filters[key] = register(key, filter);
  18410. });
  18411. return filters;
  18412. } else {
  18413. return $provide.factory(name + suffix, factory);
  18414. }
  18415. }
  18416. this.register = register;
  18417. this.$get = ['$injector', function($injector) {
  18418. return function(name) {
  18419. return $injector.get(name + suffix);
  18420. };
  18421. }];
  18422. ////////////////////////////////////////
  18423. /* global
  18424. currencyFilter: false,
  18425. dateFilter: false,
  18426. filterFilter: false,
  18427. jsonFilter: false,
  18428. limitToFilter: false,
  18429. lowercaseFilter: false,
  18430. numberFilter: false,
  18431. orderByFilter: false,
  18432. uppercaseFilter: false
  18433. */
  18434. register('currency', currencyFilter);
  18435. register('date', dateFilter);
  18436. register('filter', filterFilter);
  18437. register('json', jsonFilter);
  18438. register('limitTo', limitToFilter);
  18439. register('lowercase', lowercaseFilter);
  18440. register('number', numberFilter);
  18441. register('orderBy', orderByFilter);
  18442. register('uppercase', uppercaseFilter);
  18443. }
  18444. /**
  18445. * @ngdoc filter
  18446. * @name filter
  18447. * @kind function
  18448. *
  18449. * @description
  18450. * Selects a subset of items from `array` and returns it as a new array.
  18451. *
  18452. * @param {Array} array The source array.
  18453. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18454. * `array`.
  18455. *
  18456. * Can be one of:
  18457. *
  18458. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18459. * objects with string properties in `array` that match this string will be returned. This also
  18460. * applies to nested object properties.
  18461. * The predicate can be negated by prefixing the string with `!`.
  18462. *
  18463. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18464. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18465. * which have property `name` containing "M" and property `phone` containing "1". A special
  18466. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18467. * against any property of the object or its nested object properties. That's equivalent to the
  18468. * simple substring match with a `string` as described above. The special property name can be
  18469. * overwritten, using the `anyPropertyKey` parameter.
  18470. * The predicate can be negated by prefixing the string with `!`.
  18471. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18472. * not containing "M".
  18473. *
  18474. * Note that a named property will match properties on the same level only, while the special
  18475. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18476. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18477. * **will** be matched by `{$: 'John'}`.
  18478. *
  18479. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18480. * The function is called for each element of the array, with the element, its index, and
  18481. * the entire array itself as arguments.
  18482. *
  18483. * The final result is an array of those elements that the predicate returned true for.
  18484. *
  18485. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  18486. * determining if the expected value (from the filter expression) and actual value (from
  18487. * the object in the array) should be considered a match.
  18488. *
  18489. * Can be one of:
  18490. *
  18491. * - `function(actual, expected)`:
  18492. * The function will be given the object value and the predicate value to compare and
  18493. * should return true if both values should be considered equal.
  18494. *
  18495. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18496. * This is essentially strict comparison of expected and actual.
  18497. *
  18498. * - `false`: A short hand for a function which will look for a substring match in a case
  18499. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  18500. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  18501. *
  18502. *
  18503. * Defaults to `false`.
  18504. *
  18505. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  18506. * By default `$`.
  18507. *
  18508. * @example
  18509. <example name="filter-filter">
  18510. <file name="index.html">
  18511. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18512. {name:'Mary', phone:'800-BIG-MARY'},
  18513. {name:'Mike', phone:'555-4321'},
  18514. {name:'Adam', phone:'555-5678'},
  18515. {name:'Julie', phone:'555-8765'},
  18516. {name:'Juliette', phone:'555-5678'}]"></div>
  18517. <label>Search: <input ng-model="searchText"></label>
  18518. <table id="searchTextResults">
  18519. <tr><th>Name</th><th>Phone</th></tr>
  18520. <tr ng-repeat="friend in friends | filter:searchText">
  18521. <td>{{friend.name}}</td>
  18522. <td>{{friend.phone}}</td>
  18523. </tr>
  18524. </table>
  18525. <hr>
  18526. <label>Any: <input ng-model="search.$"></label> <br>
  18527. <label>Name only <input ng-model="search.name"></label><br>
  18528. <label>Phone only <input ng-model="search.phone"></label><br>
  18529. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18530. <table id="searchObjResults">
  18531. <tr><th>Name</th><th>Phone</th></tr>
  18532. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18533. <td>{{friendObj.name}}</td>
  18534. <td>{{friendObj.phone}}</td>
  18535. </tr>
  18536. </table>
  18537. </file>
  18538. <file name="protractor.js" type="protractor">
  18539. var expectFriendNames = function(expectedNames, key) {
  18540. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18541. arr.forEach(function(wd, i) {
  18542. expect(wd.getText()).toMatch(expectedNames[i]);
  18543. });
  18544. });
  18545. };
  18546. it('should search across all fields when filtering with a string', function() {
  18547. var searchText = element(by.model('searchText'));
  18548. searchText.clear();
  18549. searchText.sendKeys('m');
  18550. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18551. searchText.clear();
  18552. searchText.sendKeys('76');
  18553. expectFriendNames(['John', 'Julie'], 'friend');
  18554. });
  18555. it('should search in specific fields when filtering with a predicate object', function() {
  18556. var searchAny = element(by.model('search.$'));
  18557. searchAny.clear();
  18558. searchAny.sendKeys('i');
  18559. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18560. });
  18561. it('should use a equal comparison when comparator is true', function() {
  18562. var searchName = element(by.model('search.name'));
  18563. var strict = element(by.model('strict'));
  18564. searchName.clear();
  18565. searchName.sendKeys('Julie');
  18566. strict.click();
  18567. expectFriendNames(['Julie'], 'friendObj');
  18568. });
  18569. </file>
  18570. </example>
  18571. */
  18572. function filterFilter() {
  18573. return function(array, expression, comparator, anyPropertyKey) {
  18574. if (!isArrayLike(array)) {
  18575. if (array == null) {
  18576. return array;
  18577. } else {
  18578. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18579. }
  18580. }
  18581. anyPropertyKey = anyPropertyKey || '$';
  18582. var expressionType = getTypeForFilter(expression);
  18583. var predicateFn;
  18584. var matchAgainstAnyProp;
  18585. switch (expressionType) {
  18586. case 'function':
  18587. predicateFn = expression;
  18588. break;
  18589. case 'boolean':
  18590. case 'null':
  18591. case 'number':
  18592. case 'string':
  18593. matchAgainstAnyProp = true;
  18594. // falls through
  18595. case 'object':
  18596. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18597. break;
  18598. default:
  18599. return array;
  18600. }
  18601. return Array.prototype.filter.call(array, predicateFn);
  18602. };
  18603. }
  18604. // Helper functions for `filterFilter`
  18605. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18606. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18607. var predicateFn;
  18608. if (comparator === true) {
  18609. comparator = equals;
  18610. } else if (!isFunction(comparator)) {
  18611. comparator = function(actual, expected) {
  18612. if (isUndefined(actual)) {
  18613. // No substring matching against `undefined`
  18614. return false;
  18615. }
  18616. if ((actual === null) || (expected === null)) {
  18617. // No substring matching against `null`; only match against `null`
  18618. return actual === expected;
  18619. }
  18620. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18621. // Should not compare primitives against objects, unless they have custom `toString` method
  18622. return false;
  18623. }
  18624. actual = lowercase('' + actual);
  18625. expected = lowercase('' + expected);
  18626. return actual.indexOf(expected) !== -1;
  18627. };
  18628. }
  18629. predicateFn = function(item) {
  18630. if (shouldMatchPrimitives && !isObject(item)) {
  18631. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18632. }
  18633. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18634. };
  18635. return predicateFn;
  18636. }
  18637. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18638. var actualType = getTypeForFilter(actual);
  18639. var expectedType = getTypeForFilter(expected);
  18640. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18641. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18642. } else if (isArray(actual)) {
  18643. // In case `actual` is an array, consider it a match
  18644. // if ANY of it's items matches `expected`
  18645. return actual.some(function(item) {
  18646. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18647. });
  18648. }
  18649. switch (actualType) {
  18650. case 'object':
  18651. var key;
  18652. if (matchAgainstAnyProp) {
  18653. for (key in actual) {
  18654. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18655. return true;
  18656. }
  18657. }
  18658. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18659. } else if (expectedType === 'object') {
  18660. for (key in expected) {
  18661. var expectedVal = expected[key];
  18662. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18663. continue;
  18664. }
  18665. var matchAnyProperty = key === anyPropertyKey;
  18666. var actualVal = matchAnyProperty ? actual : actual[key];
  18667. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18668. return false;
  18669. }
  18670. }
  18671. return true;
  18672. } else {
  18673. return comparator(actual, expected);
  18674. }
  18675. case 'function':
  18676. return false;
  18677. default:
  18678. return comparator(actual, expected);
  18679. }
  18680. }
  18681. // Used for easily differentiating between `null` and actual `object`
  18682. function getTypeForFilter(val) {
  18683. return (val === null) ? 'null' : typeof val;
  18684. }
  18685. var MAX_DIGITS = 22;
  18686. var DECIMAL_SEP = '.';
  18687. var ZERO_CHAR = '0';
  18688. /**
  18689. * @ngdoc filter
  18690. * @name currency
  18691. * @kind function
  18692. *
  18693. * @description
  18694. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18695. * symbol for current locale is used.
  18696. *
  18697. * @param {number} amount Input to filter.
  18698. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18699. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18700. * @returns {string} Formatted number.
  18701. *
  18702. *
  18703. * @example
  18704. <example module="currencyExample" name="currency-filter">
  18705. <file name="index.html">
  18706. <script>
  18707. angular.module('currencyExample', [])
  18708. .controller('ExampleController', ['$scope', function($scope) {
  18709. $scope.amount = 1234.56;
  18710. }]);
  18711. </script>
  18712. <div ng-controller="ExampleController">
  18713. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18714. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18715. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  18716. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18717. </div>
  18718. </file>
  18719. <file name="protractor.js" type="protractor">
  18720. it('should init with 1234.56', function() {
  18721. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18722. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18723. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18724. });
  18725. it('should update', function() {
  18726. if (browser.params.browser === 'safari') {
  18727. // Safari does not understand the minus key. See
  18728. // https://github.com/angular/protractor/issues/481
  18729. return;
  18730. }
  18731. element(by.model('amount')).clear();
  18732. element(by.model('amount')).sendKeys('-1234');
  18733. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18734. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18735. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18736. });
  18737. </file>
  18738. </example>
  18739. */
  18740. currencyFilter.$inject = ['$locale'];
  18741. function currencyFilter($locale) {
  18742. var formats = $locale.NUMBER_FORMATS;
  18743. return function(amount, currencySymbol, fractionSize) {
  18744. if (isUndefined(currencySymbol)) {
  18745. currencySymbol = formats.CURRENCY_SYM;
  18746. }
  18747. if (isUndefined(fractionSize)) {
  18748. fractionSize = formats.PATTERNS[1].maxFrac;
  18749. }
  18750. // if null or undefined pass it through
  18751. return (amount == null)
  18752. ? amount
  18753. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18754. replace(/\u00A4/g, currencySymbol);
  18755. };
  18756. }
  18757. /**
  18758. * @ngdoc filter
  18759. * @name number
  18760. * @kind function
  18761. *
  18762. * @description
  18763. * Formats a number as text.
  18764. *
  18765. * If the input is null or undefined, it will just be returned.
  18766. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18767. * If the input is not a number an empty string is returned.
  18768. *
  18769. *
  18770. * @param {number|string} number Number to format.
  18771. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18772. * If this is not provided then the fraction size is computed from the current locale's number
  18773. * formatting pattern. In the case of the default locale, it will be 3.
  18774. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18775. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18776. * include "," group separators after each third digit).
  18777. *
  18778. * @example
  18779. <example module="numberFilterExample" name="number-filter">
  18780. <file name="index.html">
  18781. <script>
  18782. angular.module('numberFilterExample', [])
  18783. .controller('ExampleController', ['$scope', function($scope) {
  18784. $scope.val = 1234.56789;
  18785. }]);
  18786. </script>
  18787. <div ng-controller="ExampleController">
  18788. <label>Enter number: <input ng-model='val'></label><br>
  18789. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18790. No fractions: <span>{{val | number:0}}</span><br>
  18791. Negative number: <span>{{-val | number:4}}</span>
  18792. </div>
  18793. </file>
  18794. <file name="protractor.js" type="protractor">
  18795. it('should format numbers', function() {
  18796. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18797. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18798. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18799. });
  18800. it('should update', function() {
  18801. element(by.model('val')).clear();
  18802. element(by.model('val')).sendKeys('3374.333');
  18803. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18804. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18805. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18806. });
  18807. </file>
  18808. </example>
  18809. */
  18810. numberFilter.$inject = ['$locale'];
  18811. function numberFilter($locale) {
  18812. var formats = $locale.NUMBER_FORMATS;
  18813. return function(number, fractionSize) {
  18814. // if null or undefined pass it through
  18815. return (number == null)
  18816. ? number
  18817. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  18818. fractionSize);
  18819. };
  18820. }
  18821. /**
  18822. * Parse a number (as a string) into three components that can be used
  18823. * for formatting the number.
  18824. *
  18825. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  18826. *
  18827. * @param {string} numStr The number to parse
  18828. * @return {object} An object describing this number, containing the following keys:
  18829. * - d : an array of digits containing leading zeros as necessary
  18830. * - i : the number of the digits in `d` that are to the left of the decimal point
  18831. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  18832. *
  18833. */
  18834. function parse(numStr) {
  18835. var exponent = 0, digits, numberOfIntegerDigits;
  18836. var i, j, zeros;
  18837. // Decimal point?
  18838. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  18839. numStr = numStr.replace(DECIMAL_SEP, '');
  18840. }
  18841. // Exponential form?
  18842. if ((i = numStr.search(/e/i)) > 0) {
  18843. // Work out the exponent.
  18844. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  18845. numberOfIntegerDigits += +numStr.slice(i + 1);
  18846. numStr = numStr.substring(0, i);
  18847. } else if (numberOfIntegerDigits < 0) {
  18848. // There was no decimal point or exponent so it is an integer.
  18849. numberOfIntegerDigits = numStr.length;
  18850. }
  18851. // Count the number of leading zeros.
  18852. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  18853. if (i === (zeros = numStr.length)) {
  18854. // The digits are all zero.
  18855. digits = [0];
  18856. numberOfIntegerDigits = 1;
  18857. } else {
  18858. // Count the number of trailing zeros
  18859. zeros--;
  18860. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  18861. // Trailing zeros are insignificant so ignore them
  18862. numberOfIntegerDigits -= i;
  18863. digits = [];
  18864. // Convert string to array of digits without leading/trailing zeros.
  18865. for (j = 0; i <= zeros; i++, j++) {
  18866. digits[j] = +numStr.charAt(i);
  18867. }
  18868. }
  18869. // If the number overflows the maximum allowed digits then use an exponent.
  18870. if (numberOfIntegerDigits > MAX_DIGITS) {
  18871. digits = digits.splice(0, MAX_DIGITS - 1);
  18872. exponent = numberOfIntegerDigits - 1;
  18873. numberOfIntegerDigits = 1;
  18874. }
  18875. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  18876. }
  18877. /**
  18878. * Round the parsed number to the specified number of decimal places
  18879. * This function changed the parsedNumber in-place
  18880. */
  18881. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  18882. var digits = parsedNumber.d;
  18883. var fractionLen = digits.length - parsedNumber.i;
  18884. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  18885. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  18886. // The index of the digit to where rounding is to occur
  18887. var roundAt = fractionSize + parsedNumber.i;
  18888. var digit = digits[roundAt];
  18889. if (roundAt > 0) {
  18890. // Drop fractional digits beyond `roundAt`
  18891. digits.splice(Math.max(parsedNumber.i, roundAt));
  18892. // Set non-fractional digits beyond `roundAt` to 0
  18893. for (var j = roundAt; j < digits.length; j++) {
  18894. digits[j] = 0;
  18895. }
  18896. } else {
  18897. // We rounded to zero so reset the parsedNumber
  18898. fractionLen = Math.max(0, fractionLen);
  18899. parsedNumber.i = 1;
  18900. digits.length = Math.max(1, roundAt = fractionSize + 1);
  18901. digits[0] = 0;
  18902. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  18903. }
  18904. if (digit >= 5) {
  18905. if (roundAt - 1 < 0) {
  18906. for (var k = 0; k > roundAt; k--) {
  18907. digits.unshift(0);
  18908. parsedNumber.i++;
  18909. }
  18910. digits.unshift(1);
  18911. parsedNumber.i++;
  18912. } else {
  18913. digits[roundAt - 1]++;
  18914. }
  18915. }
  18916. // Pad out with zeros to get the required fraction length
  18917. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  18918. // Do any carrying, e.g. a digit was rounded up to 10
  18919. var carry = digits.reduceRight(function(carry, d, i, digits) {
  18920. d = d + carry;
  18921. digits[i] = d % 10;
  18922. return Math.floor(d / 10);
  18923. }, 0);
  18924. if (carry) {
  18925. digits.unshift(carry);
  18926. parsedNumber.i++;
  18927. }
  18928. }
  18929. /**
  18930. * Format a number into a string
  18931. * @param {number} number The number to format
  18932. * @param {{
  18933. * minFrac, // the minimum number of digits required in the fraction part of the number
  18934. * maxFrac, // the maximum number of digits required in the fraction part of the number
  18935. * gSize, // number of digits in each group of separated digits
  18936. * lgSize, // number of digits in the last group of digits before the decimal separator
  18937. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  18938. * posPre, // the string to go in front of a positive number
  18939. * negSuf, // the string to go after a negative number (e.g. `)`)
  18940. * posSuf // the string to go after a positive number
  18941. * }} pattern
  18942. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  18943. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  18944. * @param {[type]} fractionSize The size of the fractional part of the number
  18945. * @return {string} The number formatted as a string
  18946. */
  18947. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  18948. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  18949. var isInfinity = !isFinite(number);
  18950. var isZero = false;
  18951. var numStr = Math.abs(number) + '',
  18952. formattedText = '',
  18953. parsedNumber;
  18954. if (isInfinity) {
  18955. formattedText = '\u221e';
  18956. } else {
  18957. parsedNumber = parse(numStr);
  18958. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  18959. var digits = parsedNumber.d;
  18960. var integerLen = parsedNumber.i;
  18961. var exponent = parsedNumber.e;
  18962. var decimals = [];
  18963. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  18964. // pad zeros for small numbers
  18965. while (integerLen < 0) {
  18966. digits.unshift(0);
  18967. integerLen++;
  18968. }
  18969. // extract decimals digits
  18970. if (integerLen > 0) {
  18971. decimals = digits.splice(integerLen, digits.length);
  18972. } else {
  18973. decimals = digits;
  18974. digits = [0];
  18975. }
  18976. // format the integer digits with grouping separators
  18977. var groups = [];
  18978. if (digits.length >= pattern.lgSize) {
  18979. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  18980. }
  18981. while (digits.length > pattern.gSize) {
  18982. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  18983. }
  18984. if (digits.length) {
  18985. groups.unshift(digits.join(''));
  18986. }
  18987. formattedText = groups.join(groupSep);
  18988. // append the decimal digits
  18989. if (decimals.length) {
  18990. formattedText += decimalSep + decimals.join('');
  18991. }
  18992. if (exponent) {
  18993. formattedText += 'e+' + exponent;
  18994. }
  18995. }
  18996. if (number < 0 && !isZero) {
  18997. return pattern.negPre + formattedText + pattern.negSuf;
  18998. } else {
  18999. return pattern.posPre + formattedText + pattern.posSuf;
  19000. }
  19001. }
  19002. function padNumber(num, digits, trim, negWrap) {
  19003. var neg = '';
  19004. if (num < 0 || (negWrap && num <= 0)) {
  19005. if (negWrap) {
  19006. num = -num + 1;
  19007. } else {
  19008. num = -num;
  19009. neg = '-';
  19010. }
  19011. }
  19012. num = '' + num;
  19013. while (num.length < digits) num = ZERO_CHAR + num;
  19014. if (trim) {
  19015. num = num.substr(num.length - digits);
  19016. }
  19017. return neg + num;
  19018. }
  19019. function dateGetter(name, size, offset, trim, negWrap) {
  19020. offset = offset || 0;
  19021. return function(date) {
  19022. var value = date['get' + name]();
  19023. if (offset > 0 || value > -offset) {
  19024. value += offset;
  19025. }
  19026. if (value === 0 && offset === -12) value = 12;
  19027. return padNumber(value, size, trim, negWrap);
  19028. };
  19029. }
  19030. function dateStrGetter(name, shortForm, standAlone) {
  19031. return function(date, formats) {
  19032. var value = date['get' + name]();
  19033. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19034. var get = uppercase(propPrefix + name);
  19035. return formats[get][value];
  19036. };
  19037. }
  19038. function timeZoneGetter(date, formats, offset) {
  19039. var zone = -1 * offset;
  19040. var paddedZone = (zone >= 0) ? '+' : '';
  19041. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19042. padNumber(Math.abs(zone % 60), 2);
  19043. return paddedZone;
  19044. }
  19045. function getFirstThursdayOfYear(year) {
  19046. // 0 = index of January
  19047. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19048. // 4 = index of Thursday (+1 to account for 1st = 5)
  19049. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19050. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19051. }
  19052. function getThursdayThisWeek(datetime) {
  19053. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19054. // 4 = index of Thursday
  19055. datetime.getDate() + (4 - datetime.getDay()));
  19056. }
  19057. function weekGetter(size) {
  19058. return function(date) {
  19059. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19060. thisThurs = getThursdayThisWeek(date);
  19061. var diff = +thisThurs - +firstThurs,
  19062. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19063. return padNumber(result, size);
  19064. };
  19065. }
  19066. function ampmGetter(date, formats) {
  19067. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19068. }
  19069. function eraGetter(date, formats) {
  19070. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19071. }
  19072. function longEraGetter(date, formats) {
  19073. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19074. }
  19075. var DATE_FORMATS = {
  19076. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19077. yy: dateGetter('FullYear', 2, 0, true, true),
  19078. y: dateGetter('FullYear', 1, 0, false, true),
  19079. MMMM: dateStrGetter('Month'),
  19080. MMM: dateStrGetter('Month', true),
  19081. MM: dateGetter('Month', 2, 1),
  19082. M: dateGetter('Month', 1, 1),
  19083. LLLL: dateStrGetter('Month', false, true),
  19084. dd: dateGetter('Date', 2),
  19085. d: dateGetter('Date', 1),
  19086. HH: dateGetter('Hours', 2),
  19087. H: dateGetter('Hours', 1),
  19088. hh: dateGetter('Hours', 2, -12),
  19089. h: dateGetter('Hours', 1, -12),
  19090. mm: dateGetter('Minutes', 2),
  19091. m: dateGetter('Minutes', 1),
  19092. ss: dateGetter('Seconds', 2),
  19093. s: dateGetter('Seconds', 1),
  19094. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19095. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19096. sss: dateGetter('Milliseconds', 3),
  19097. EEEE: dateStrGetter('Day'),
  19098. EEE: dateStrGetter('Day', true),
  19099. a: ampmGetter,
  19100. Z: timeZoneGetter,
  19101. ww: weekGetter(2),
  19102. w: weekGetter(1),
  19103. G: eraGetter,
  19104. GG: eraGetter,
  19105. GGG: eraGetter,
  19106. GGGG: longEraGetter
  19107. };
  19108. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  19109. NUMBER_STRING = /^-?\d+$/;
  19110. /**
  19111. * @ngdoc filter
  19112. * @name date
  19113. * @kind function
  19114. *
  19115. * @description
  19116. * Formats `date` to a string based on the requested `format`.
  19117. *
  19118. * `format` string can be composed of the following elements:
  19119. *
  19120. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19121. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19122. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19123. * * `'MMMM'`: Month in year (January-December)
  19124. * * `'MMM'`: Month in year (Jan-Dec)
  19125. * * `'MM'`: Month in year, padded (01-12)
  19126. * * `'M'`: Month in year (1-12)
  19127. * * `'LLLL'`: Stand-alone month in year (January-December)
  19128. * * `'dd'`: Day in month, padded (01-31)
  19129. * * `'d'`: Day in month (1-31)
  19130. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19131. * * `'EEE'`: Day in Week, (Sun-Sat)
  19132. * * `'HH'`: Hour in day, padded (00-23)
  19133. * * `'H'`: Hour in day (0-23)
  19134. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19135. * * `'h'`: Hour in AM/PM, (1-12)
  19136. * * `'mm'`: Minute in hour, padded (00-59)
  19137. * * `'m'`: Minute in hour (0-59)
  19138. * * `'ss'`: Second in minute, padded (00-59)
  19139. * * `'s'`: Second in minute (0-59)
  19140. * * `'sss'`: Millisecond in second, padded (000-999)
  19141. * * `'a'`: AM/PM marker
  19142. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19143. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19144. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19145. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19146. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19147. *
  19148. * `format` string can also be one of the following predefined
  19149. * {@link guide/i18n localizable formats}:
  19150. *
  19151. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19152. * (e.g. Sep 3, 2010 12:05:08 PM)
  19153. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19154. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19155. * (e.g. Friday, September 3, 2010)
  19156. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19157. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19158. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19159. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19160. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19161. *
  19162. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19163. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19164. * (e.g. `"h 'o''clock'"`).
  19165. *
  19166. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19167. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19168. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19169. * specified in the string input, the time is considered to be in the local timezone.
  19170. * @param {string=} format Formatting rules (see Description). If not specified,
  19171. * `mediumDate` is used.
  19172. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19173. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19174. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19175. * If not specified, the timezone of the browser will be used.
  19176. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19177. *
  19178. * @example
  19179. <example name="filter-date">
  19180. <file name="index.html">
  19181. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19182. <span>{{1288323623006 | date:'medium'}}</span><br>
  19183. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19184. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19185. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19186. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19187. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19188. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19189. </file>
  19190. <file name="protractor.js" type="protractor">
  19191. it('should format date', function() {
  19192. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19193. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19194. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19195. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19196. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19197. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19198. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19199. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19200. });
  19201. </file>
  19202. </example>
  19203. */
  19204. dateFilter.$inject = ['$locale'];
  19205. function dateFilter($locale) {
  19206. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19207. // 1 2 3 4 5 6 7 8 9 10 11
  19208. function jsonStringToDate(string) {
  19209. var match;
  19210. if ((match = string.match(R_ISO8601_STR))) {
  19211. var date = new Date(0),
  19212. tzHour = 0,
  19213. tzMin = 0,
  19214. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19215. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19216. if (match[9]) {
  19217. tzHour = toInt(match[9] + match[10]);
  19218. tzMin = toInt(match[9] + match[11]);
  19219. }
  19220. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19221. var h = toInt(match[4] || 0) - tzHour;
  19222. var m = toInt(match[5] || 0) - tzMin;
  19223. var s = toInt(match[6] || 0);
  19224. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19225. timeSetter.call(date, h, m, s, ms);
  19226. return date;
  19227. }
  19228. return string;
  19229. }
  19230. return function(date, format, timezone) {
  19231. var text = '',
  19232. parts = [],
  19233. fn, match;
  19234. format = format || 'mediumDate';
  19235. format = $locale.DATETIME_FORMATS[format] || format;
  19236. if (isString(date)) {
  19237. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19238. }
  19239. if (isNumber(date)) {
  19240. date = new Date(date);
  19241. }
  19242. if (!isDate(date) || !isFinite(date.getTime())) {
  19243. return date;
  19244. }
  19245. while (format) {
  19246. match = DATE_FORMATS_SPLIT.exec(format);
  19247. if (match) {
  19248. parts = concat(parts, match, 1);
  19249. format = parts.pop();
  19250. } else {
  19251. parts.push(format);
  19252. format = null;
  19253. }
  19254. }
  19255. var dateTimezoneOffset = date.getTimezoneOffset();
  19256. if (timezone) {
  19257. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19258. date = convertTimezoneToLocal(date, timezone, true);
  19259. }
  19260. forEach(parts, function(value) {
  19261. fn = DATE_FORMATS[value];
  19262. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19263. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19264. });
  19265. return text;
  19266. };
  19267. }
  19268. /**
  19269. * @ngdoc filter
  19270. * @name json
  19271. * @kind function
  19272. *
  19273. * @description
  19274. * Allows you to convert a JavaScript object into JSON string.
  19275. *
  19276. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19277. * the binding is automatically converted to JSON.
  19278. *
  19279. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19280. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19281. * @returns {string} JSON string.
  19282. *
  19283. *
  19284. * @example
  19285. <example name="filter-json">
  19286. <file name="index.html">
  19287. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19288. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19289. </file>
  19290. <file name="protractor.js" type="protractor">
  19291. it('should jsonify filtered objects', function() {
  19292. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19293. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19294. });
  19295. </file>
  19296. </example>
  19297. *
  19298. */
  19299. function jsonFilter() {
  19300. return function(object, spacing) {
  19301. if (isUndefined(spacing)) {
  19302. spacing = 2;
  19303. }
  19304. return toJson(object, spacing);
  19305. };
  19306. }
  19307. /**
  19308. * @ngdoc filter
  19309. * @name lowercase
  19310. * @kind function
  19311. * @description
  19312. * Converts string to lowercase.
  19313. * @see angular.lowercase
  19314. */
  19315. var lowercaseFilter = valueFn(lowercase);
  19316. /**
  19317. * @ngdoc filter
  19318. * @name uppercase
  19319. * @kind function
  19320. * @description
  19321. * Converts string to uppercase.
  19322. * @see angular.uppercase
  19323. */
  19324. var uppercaseFilter = valueFn(uppercase);
  19325. /**
  19326. * @ngdoc filter
  19327. * @name limitTo
  19328. * @kind function
  19329. *
  19330. * @description
  19331. * Creates a new array or string containing only a specified number of elements. The elements are
  19332. * taken from either the beginning or the end of the source array, string or number, as specified by
  19333. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19334. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19335. * it is converted to a string.
  19336. *
  19337. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19338. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19339. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19340. * If the number is negative, `limit` number of items from the end of the source array/string
  19341. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19342. * the input will be returned unchanged.
  19343. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19344. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19345. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19346. * less than `limit` elements.
  19347. *
  19348. * @example
  19349. <example module="limitToExample" name="limit-to-filter">
  19350. <file name="index.html">
  19351. <script>
  19352. angular.module('limitToExample', [])
  19353. .controller('ExampleController', ['$scope', function($scope) {
  19354. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19355. $scope.letters = "abcdefghi";
  19356. $scope.longNumber = 2345432342;
  19357. $scope.numLimit = 3;
  19358. $scope.letterLimit = 3;
  19359. $scope.longNumberLimit = 3;
  19360. }]);
  19361. </script>
  19362. <div ng-controller="ExampleController">
  19363. <label>
  19364. Limit {{numbers}} to:
  19365. <input type="number" step="1" ng-model="numLimit">
  19366. </label>
  19367. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19368. <label>
  19369. Limit {{letters}} to:
  19370. <input type="number" step="1" ng-model="letterLimit">
  19371. </label>
  19372. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19373. <label>
  19374. Limit {{longNumber}} to:
  19375. <input type="number" step="1" ng-model="longNumberLimit">
  19376. </label>
  19377. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19378. </div>
  19379. </file>
  19380. <file name="protractor.js" type="protractor">
  19381. var numLimitInput = element(by.model('numLimit'));
  19382. var letterLimitInput = element(by.model('letterLimit'));
  19383. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19384. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19385. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19386. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19387. it('should limit the number array to first three items', function() {
  19388. expect(numLimitInput.getAttribute('value')).toBe('3');
  19389. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19390. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19391. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19392. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19393. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19394. });
  19395. // There is a bug in safari and protractor that doesn't like the minus key
  19396. // it('should update the output when -3 is entered', function() {
  19397. // numLimitInput.clear();
  19398. // numLimitInput.sendKeys('-3');
  19399. // letterLimitInput.clear();
  19400. // letterLimitInput.sendKeys('-3');
  19401. // longNumberLimitInput.clear();
  19402. // longNumberLimitInput.sendKeys('-3');
  19403. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19404. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19405. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19406. // });
  19407. it('should not exceed the maximum size of input array', function() {
  19408. numLimitInput.clear();
  19409. numLimitInput.sendKeys('100');
  19410. letterLimitInput.clear();
  19411. letterLimitInput.sendKeys('100');
  19412. longNumberLimitInput.clear();
  19413. longNumberLimitInput.sendKeys('100');
  19414. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19415. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19416. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19417. });
  19418. </file>
  19419. </example>
  19420. */
  19421. function limitToFilter() {
  19422. return function(input, limit, begin) {
  19423. if (Math.abs(Number(limit)) === Infinity) {
  19424. limit = Number(limit);
  19425. } else {
  19426. limit = toInt(limit);
  19427. }
  19428. if (isNumberNaN(limit)) return input;
  19429. if (isNumber(input)) input = input.toString();
  19430. if (!isArrayLike(input)) return input;
  19431. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19432. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19433. if (limit >= 0) {
  19434. return sliceFn(input, begin, begin + limit);
  19435. } else {
  19436. if (begin === 0) {
  19437. return sliceFn(input, limit, input.length);
  19438. } else {
  19439. return sliceFn(input, Math.max(0, begin + limit), begin);
  19440. }
  19441. }
  19442. };
  19443. }
  19444. function sliceFn(input, begin, end) {
  19445. if (isString(input)) return input.slice(begin, end);
  19446. return slice.call(input, begin, end);
  19447. }
  19448. /**
  19449. * @ngdoc filter
  19450. * @name orderBy
  19451. * @kind function
  19452. *
  19453. * @description
  19454. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19455. * function based on the values computed using the `expression` predicate.
  19456. *
  19457. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19458. * `[{id: 'bar'}, {id: 'foo'}]`.
  19459. *
  19460. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19461. * String, etc).
  19462. *
  19463. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19464. * for the preceding one. The `expression` is evaluated against each item and the output is used
  19465. * for comparing with other items.
  19466. *
  19467. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19468. * ascending order.
  19469. *
  19470. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19471. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19472. * strings alphabetically).
  19473. *
  19474. * ### Under the hood
  19475. *
  19476. * Ordering the specified `collection` happens in two phases:
  19477. *
  19478. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19479. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19480. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19481. * ```
  19482. * {
  19483. * value: 'foo',
  19484. * type: 'string',
  19485. * index: ...
  19486. * }
  19487. * ```
  19488. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19489. * indices.
  19490. *
  19491. * If you use a custom comparator, it will be called with pairs of objects of the form
  19492. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19493. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19494. * second, or `1` otherwise.
  19495. *
  19496. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19497. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19498. * dummy predicate that returns the item's index as `value`.
  19499. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19500. *
  19501. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19502. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19503. * it to the comparator. The following rules govern the conversion:
  19504. *
  19505. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19506. * used instead.<br />
  19507. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19508. * will be used in subsequent steps.)
  19509. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19510. * returns a primitive, its return value will be used instead.<br />
  19511. * (If the object has a `toString()` method that returns another object, then the returned object
  19512. * will be used in subsequent steps.)
  19513. * 3. No conversion; the object itself is used.
  19514. *
  19515. * ### The default comparator
  19516. *
  19517. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19518. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19519. * using their index in the original collection, and sorts values of different types by type.
  19520. *
  19521. * More specifically, it follows these steps to determine the relative order of items:
  19522. *
  19523. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19524. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19525. * locale-insensitive way.
  19526. * 3. If both values are objects, compare their indices instead.
  19527. * 4. Otherwise, return:
  19528. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19529. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19530. * - `1`, otherwise.
  19531. *
  19532. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19533. * saved as numbers and not strings.
  19534. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  19535. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  19536. * other values.
  19537. *
  19538. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19539. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19540. * predicates) to be used by the comparator to determine the order of elements.
  19541. *
  19542. * Can be one of:
  19543. *
  19544. * - `Function`: A getter function. This function will be called with each item as argument and
  19545. * the return value will be used for sorting.
  19546. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19547. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19548. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19549. * property.<br />
  19550. * (The result of a constant expression is interpreted as a property name to be used for
  19551. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19552. * property called `special name`.)<br />
  19553. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19554. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19555. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19556. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19557. * relative order of two items, the next predicate is used as a tie-breaker.
  19558. *
  19559. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19560. *
  19561. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19562. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19563. * value pairs. If omitted, the built-in comparator will be used.
  19564. *
  19565. * @returns {Array} - The sorted array.
  19566. *
  19567. *
  19568. * @example
  19569. * ### Ordering a table with `ngRepeat`
  19570. *
  19571. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19572. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19573. * it defaults to the built-in comparator.
  19574. *
  19575. <example name="orderBy-static" module="orderByExample1">
  19576. <file name="index.html">
  19577. <div ng-controller="ExampleController">
  19578. <table class="friends">
  19579. <tr>
  19580. <th>Name</th>
  19581. <th>Phone Number</th>
  19582. <th>Age</th>
  19583. </tr>
  19584. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19585. <td>{{friend.name}}</td>
  19586. <td>{{friend.phone}}</td>
  19587. <td>{{friend.age}}</td>
  19588. </tr>
  19589. </table>
  19590. </div>
  19591. </file>
  19592. <file name="script.js">
  19593. angular.module('orderByExample1', [])
  19594. .controller('ExampleController', ['$scope', function($scope) {
  19595. $scope.friends = [
  19596. {name: 'John', phone: '555-1212', age: 10},
  19597. {name: 'Mary', phone: '555-9876', age: 19},
  19598. {name: 'Mike', phone: '555-4321', age: 21},
  19599. {name: 'Adam', phone: '555-5678', age: 35},
  19600. {name: 'Julie', phone: '555-8765', age: 29}
  19601. ];
  19602. }]);
  19603. </file>
  19604. <file name="style.css">
  19605. .friends {
  19606. border-collapse: collapse;
  19607. }
  19608. .friends th {
  19609. border-bottom: 1px solid;
  19610. }
  19611. .friends td, .friends th {
  19612. border-left: 1px solid;
  19613. padding: 5px 10px;
  19614. }
  19615. .friends td:first-child, .friends th:first-child {
  19616. border-left: none;
  19617. }
  19618. </file>
  19619. <file name="protractor.js" type="protractor">
  19620. // Element locators
  19621. var names = element.all(by.repeater('friends').column('friend.name'));
  19622. it('should sort friends by age in reverse order', function() {
  19623. expect(names.get(0).getText()).toBe('Adam');
  19624. expect(names.get(1).getText()).toBe('Julie');
  19625. expect(names.get(2).getText()).toBe('Mike');
  19626. expect(names.get(3).getText()).toBe('Mary');
  19627. expect(names.get(4).getText()).toBe('John');
  19628. });
  19629. </file>
  19630. </example>
  19631. * <hr />
  19632. *
  19633. * @example
  19634. * ### Changing parameters dynamically
  19635. *
  19636. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19637. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19638. *
  19639. <example name="orderBy-dynamic" module="orderByExample2">
  19640. <file name="index.html">
  19641. <div ng-controller="ExampleController">
  19642. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19643. <hr/>
  19644. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19645. <hr/>
  19646. <table class="friends">
  19647. <tr>
  19648. <th>
  19649. <button ng-click="sortBy('name')">Name</button>
  19650. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19651. </th>
  19652. <th>
  19653. <button ng-click="sortBy('phone')">Phone Number</button>
  19654. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19655. </th>
  19656. <th>
  19657. <button ng-click="sortBy('age')">Age</button>
  19658. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19659. </th>
  19660. </tr>
  19661. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19662. <td>{{friend.name}}</td>
  19663. <td>{{friend.phone}}</td>
  19664. <td>{{friend.age}}</td>
  19665. </tr>
  19666. </table>
  19667. </div>
  19668. </file>
  19669. <file name="script.js">
  19670. angular.module('orderByExample2', [])
  19671. .controller('ExampleController', ['$scope', function($scope) {
  19672. var friends = [
  19673. {name: 'John', phone: '555-1212', age: 10},
  19674. {name: 'Mary', phone: '555-9876', age: 19},
  19675. {name: 'Mike', phone: '555-4321', age: 21},
  19676. {name: 'Adam', phone: '555-5678', age: 35},
  19677. {name: 'Julie', phone: '555-8765', age: 29}
  19678. ];
  19679. $scope.propertyName = 'age';
  19680. $scope.reverse = true;
  19681. $scope.friends = friends;
  19682. $scope.sortBy = function(propertyName) {
  19683. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19684. $scope.propertyName = propertyName;
  19685. };
  19686. }]);
  19687. </file>
  19688. <file name="style.css">
  19689. .friends {
  19690. border-collapse: collapse;
  19691. }
  19692. .friends th {
  19693. border-bottom: 1px solid;
  19694. }
  19695. .friends td, .friends th {
  19696. border-left: 1px solid;
  19697. padding: 5px 10px;
  19698. }
  19699. .friends td:first-child, .friends th:first-child {
  19700. border-left: none;
  19701. }
  19702. .sortorder:after {
  19703. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19704. }
  19705. .sortorder.reverse:after {
  19706. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19707. }
  19708. </file>
  19709. <file name="protractor.js" type="protractor">
  19710. // Element locators
  19711. var unsortButton = element(by.partialButtonText('unsorted'));
  19712. var nameHeader = element(by.partialButtonText('Name'));
  19713. var phoneHeader = element(by.partialButtonText('Phone'));
  19714. var ageHeader = element(by.partialButtonText('Age'));
  19715. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19716. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19717. it('should sort friends by some property, when clicking on the column header', function() {
  19718. expect(firstName.getText()).toBe('Adam');
  19719. expect(lastName.getText()).toBe('John');
  19720. phoneHeader.click();
  19721. expect(firstName.getText()).toBe('John');
  19722. expect(lastName.getText()).toBe('Mary');
  19723. nameHeader.click();
  19724. expect(firstName.getText()).toBe('Adam');
  19725. expect(lastName.getText()).toBe('Mike');
  19726. ageHeader.click();
  19727. expect(firstName.getText()).toBe('John');
  19728. expect(lastName.getText()).toBe('Adam');
  19729. });
  19730. it('should sort friends in reverse order, when clicking on the same column', function() {
  19731. expect(firstName.getText()).toBe('Adam');
  19732. expect(lastName.getText()).toBe('John');
  19733. ageHeader.click();
  19734. expect(firstName.getText()).toBe('John');
  19735. expect(lastName.getText()).toBe('Adam');
  19736. ageHeader.click();
  19737. expect(firstName.getText()).toBe('Adam');
  19738. expect(lastName.getText()).toBe('John');
  19739. });
  19740. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19741. expect(firstName.getText()).toBe('Adam');
  19742. expect(lastName.getText()).toBe('John');
  19743. unsortButton.click();
  19744. expect(firstName.getText()).toBe('John');
  19745. expect(lastName.getText()).toBe('Julie');
  19746. });
  19747. </file>
  19748. </example>
  19749. * <hr />
  19750. *
  19751. * @example
  19752. * ### Using `orderBy` inside a controller
  19753. *
  19754. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19755. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19756. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19757. *
  19758. <example name="orderBy-call-manually" module="orderByExample3">
  19759. <file name="index.html">
  19760. <div ng-controller="ExampleController">
  19761. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19762. <hr/>
  19763. <button ng-click="sortBy(null)">Set to unsorted</button>
  19764. <hr/>
  19765. <table class="friends">
  19766. <tr>
  19767. <th>
  19768. <button ng-click="sortBy('name')">Name</button>
  19769. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19770. </th>
  19771. <th>
  19772. <button ng-click="sortBy('phone')">Phone Number</button>
  19773. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19774. </th>
  19775. <th>
  19776. <button ng-click="sortBy('age')">Age</button>
  19777. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19778. </th>
  19779. </tr>
  19780. <tr ng-repeat="friend in friends">
  19781. <td>{{friend.name}}</td>
  19782. <td>{{friend.phone}}</td>
  19783. <td>{{friend.age}}</td>
  19784. </tr>
  19785. </table>
  19786. </div>
  19787. </file>
  19788. <file name="script.js">
  19789. angular.module('orderByExample3', [])
  19790. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19791. var friends = [
  19792. {name: 'John', phone: '555-1212', age: 10},
  19793. {name: 'Mary', phone: '555-9876', age: 19},
  19794. {name: 'Mike', phone: '555-4321', age: 21},
  19795. {name: 'Adam', phone: '555-5678', age: 35},
  19796. {name: 'Julie', phone: '555-8765', age: 29}
  19797. ];
  19798. $scope.propertyName = 'age';
  19799. $scope.reverse = true;
  19800. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19801. $scope.sortBy = function(propertyName) {
  19802. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19803. ? !$scope.reverse : false;
  19804. $scope.propertyName = propertyName;
  19805. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19806. };
  19807. }]);
  19808. </file>
  19809. <file name="style.css">
  19810. .friends {
  19811. border-collapse: collapse;
  19812. }
  19813. .friends th {
  19814. border-bottom: 1px solid;
  19815. }
  19816. .friends td, .friends th {
  19817. border-left: 1px solid;
  19818. padding: 5px 10px;
  19819. }
  19820. .friends td:first-child, .friends th:first-child {
  19821. border-left: none;
  19822. }
  19823. .sortorder:after {
  19824. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19825. }
  19826. .sortorder.reverse:after {
  19827. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19828. }
  19829. </file>
  19830. <file name="protractor.js" type="protractor">
  19831. // Element locators
  19832. var unsortButton = element(by.partialButtonText('unsorted'));
  19833. var nameHeader = element(by.partialButtonText('Name'));
  19834. var phoneHeader = element(by.partialButtonText('Phone'));
  19835. var ageHeader = element(by.partialButtonText('Age'));
  19836. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19837. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19838. it('should sort friends by some property, when clicking on the column header', function() {
  19839. expect(firstName.getText()).toBe('Adam');
  19840. expect(lastName.getText()).toBe('John');
  19841. phoneHeader.click();
  19842. expect(firstName.getText()).toBe('John');
  19843. expect(lastName.getText()).toBe('Mary');
  19844. nameHeader.click();
  19845. expect(firstName.getText()).toBe('Adam');
  19846. expect(lastName.getText()).toBe('Mike');
  19847. ageHeader.click();
  19848. expect(firstName.getText()).toBe('John');
  19849. expect(lastName.getText()).toBe('Adam');
  19850. });
  19851. it('should sort friends in reverse order, when clicking on the same column', function() {
  19852. expect(firstName.getText()).toBe('Adam');
  19853. expect(lastName.getText()).toBe('John');
  19854. ageHeader.click();
  19855. expect(firstName.getText()).toBe('John');
  19856. expect(lastName.getText()).toBe('Adam');
  19857. ageHeader.click();
  19858. expect(firstName.getText()).toBe('Adam');
  19859. expect(lastName.getText()).toBe('John');
  19860. });
  19861. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19862. expect(firstName.getText()).toBe('Adam');
  19863. expect(lastName.getText()).toBe('John');
  19864. unsortButton.click();
  19865. expect(firstName.getText()).toBe('John');
  19866. expect(lastName.getText()).toBe('Julie');
  19867. });
  19868. </file>
  19869. </example>
  19870. * <hr />
  19871. *
  19872. * @example
  19873. * ### Using a custom comparator
  19874. *
  19875. * If you have very specific requirements about the way items are sorted, you can pass your own
  19876. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  19877. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  19878. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  19879. *
  19880. <example name="orderBy-custom-comparator" module="orderByExample4">
  19881. <file name="index.html">
  19882. <div ng-controller="ExampleController">
  19883. <div class="friends-container custom-comparator">
  19884. <h3>Locale-sensitive Comparator</h3>
  19885. <table class="friends">
  19886. <tr>
  19887. <th>Name</th>
  19888. <th>Favorite Letter</th>
  19889. </tr>
  19890. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  19891. <td>{{friend.name}}</td>
  19892. <td>{{friend.favoriteLetter}}</td>
  19893. </tr>
  19894. </table>
  19895. </div>
  19896. <div class="friends-container default-comparator">
  19897. <h3>Default Comparator</h3>
  19898. <table class="friends">
  19899. <tr>
  19900. <th>Name</th>
  19901. <th>Favorite Letter</th>
  19902. </tr>
  19903. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  19904. <td>{{friend.name}}</td>
  19905. <td>{{friend.favoriteLetter}}</td>
  19906. </tr>
  19907. </table>
  19908. </div>
  19909. </div>
  19910. </file>
  19911. <file name="script.js">
  19912. angular.module('orderByExample4', [])
  19913. .controller('ExampleController', ['$scope', function($scope) {
  19914. $scope.friends = [
  19915. {name: 'John', favoriteLetter: 'Ä'},
  19916. {name: 'Mary', favoriteLetter: 'Ü'},
  19917. {name: 'Mike', favoriteLetter: 'Ö'},
  19918. {name: 'Adam', favoriteLetter: 'H'},
  19919. {name: 'Julie', favoriteLetter: 'Z'}
  19920. ];
  19921. $scope.localeSensitiveComparator = function(v1, v2) {
  19922. // If we don't get strings, just compare by index
  19923. if (v1.type !== 'string' || v2.type !== 'string') {
  19924. return (v1.index < v2.index) ? -1 : 1;
  19925. }
  19926. // Compare strings alphabetically, taking locale into account
  19927. return v1.value.localeCompare(v2.value);
  19928. };
  19929. }]);
  19930. </file>
  19931. <file name="style.css">
  19932. .friends-container {
  19933. display: inline-block;
  19934. margin: 0 30px;
  19935. }
  19936. .friends {
  19937. border-collapse: collapse;
  19938. }
  19939. .friends th {
  19940. border-bottom: 1px solid;
  19941. }
  19942. .friends td, .friends th {
  19943. border-left: 1px solid;
  19944. padding: 5px 10px;
  19945. }
  19946. .friends td:first-child, .friends th:first-child {
  19947. border-left: none;
  19948. }
  19949. </file>
  19950. <file name="protractor.js" type="protractor">
  19951. // Element locators
  19952. var container = element(by.css('.custom-comparator'));
  19953. var names = container.all(by.repeater('friends').column('friend.name'));
  19954. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  19955. expect(names.get(0).getText()).toBe('John');
  19956. expect(names.get(1).getText()).toBe('Adam');
  19957. expect(names.get(2).getText()).toBe('Mike');
  19958. expect(names.get(3).getText()).toBe('Mary');
  19959. expect(names.get(4).getText()).toBe('Julie');
  19960. });
  19961. </file>
  19962. </example>
  19963. *
  19964. */
  19965. orderByFilter.$inject = ['$parse'];
  19966. function orderByFilter($parse) {
  19967. return function(array, sortPredicate, reverseOrder, compareFn) {
  19968. if (array == null) return array;
  19969. if (!isArrayLike(array)) {
  19970. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  19971. }
  19972. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  19973. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  19974. var predicates = processPredicates(sortPredicate);
  19975. var descending = reverseOrder ? -1 : 1;
  19976. // Define the `compare()` function. Use a default comparator if none is specified.
  19977. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  19978. // The next three lines are a version of a Swartzian Transform idiom from Perl
  19979. // (sometimes called the Decorate-Sort-Undecorate idiom)
  19980. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  19981. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  19982. compareValues.sort(doComparison);
  19983. array = compareValues.map(function(item) { return item.value; });
  19984. return array;
  19985. function getComparisonObject(value, index) {
  19986. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  19987. // This will be used to keep the sort stable when none of the input predicates can
  19988. // distinguish between two elements.
  19989. return {
  19990. value: value,
  19991. tieBreaker: {value: index, type: 'number', index: index},
  19992. predicateValues: predicates.map(function(predicate) {
  19993. return getPredicateValue(predicate.get(value), index);
  19994. })
  19995. };
  19996. }
  19997. function doComparison(v1, v2) {
  19998. for (var i = 0, ii = predicates.length; i < ii; i++) {
  19999. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20000. if (result) {
  20001. return result * predicates[i].descending * descending;
  20002. }
  20003. }
  20004. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  20005. }
  20006. };
  20007. function processPredicates(sortPredicates) {
  20008. return sortPredicates.map(function(predicate) {
  20009. var descending = 1, get = identity;
  20010. if (isFunction(predicate)) {
  20011. get = predicate;
  20012. } else if (isString(predicate)) {
  20013. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20014. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20015. predicate = predicate.substring(1);
  20016. }
  20017. if (predicate !== '') {
  20018. get = $parse(predicate);
  20019. if (get.constant) {
  20020. var key = get();
  20021. get = function(value) { return value[key]; };
  20022. }
  20023. }
  20024. }
  20025. return {get: get, descending: descending};
  20026. });
  20027. }
  20028. function isPrimitive(value) {
  20029. switch (typeof value) {
  20030. case 'number': /* falls through */
  20031. case 'boolean': /* falls through */
  20032. case 'string':
  20033. return true;
  20034. default:
  20035. return false;
  20036. }
  20037. }
  20038. function objectValue(value) {
  20039. // If `valueOf` is a valid function use that
  20040. if (isFunction(value.valueOf)) {
  20041. value = value.valueOf();
  20042. if (isPrimitive(value)) return value;
  20043. }
  20044. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20045. if (hasCustomToString(value)) {
  20046. value = value.toString();
  20047. if (isPrimitive(value)) return value;
  20048. }
  20049. return value;
  20050. }
  20051. function getPredicateValue(value, index) {
  20052. var type = typeof value;
  20053. if (value === null) {
  20054. type = 'string';
  20055. value = 'null';
  20056. } else if (type === 'object') {
  20057. value = objectValue(value);
  20058. }
  20059. return {value: value, type: type, index: index};
  20060. }
  20061. function defaultCompare(v1, v2) {
  20062. var result = 0;
  20063. var type1 = v1.type;
  20064. var type2 = v2.type;
  20065. if (type1 === type2) {
  20066. var value1 = v1.value;
  20067. var value2 = v2.value;
  20068. if (type1 === 'string') {
  20069. // Compare strings case-insensitively
  20070. value1 = value1.toLowerCase();
  20071. value2 = value2.toLowerCase();
  20072. } else if (type1 === 'object') {
  20073. // For basic objects, use the position of the object
  20074. // in the collection instead of the value
  20075. if (isObject(value1)) value1 = v1.index;
  20076. if (isObject(value2)) value2 = v2.index;
  20077. }
  20078. if (value1 !== value2) {
  20079. result = value1 < value2 ? -1 : 1;
  20080. }
  20081. } else {
  20082. result = type1 < type2 ? -1 : 1;
  20083. }
  20084. return result;
  20085. }
  20086. }
  20087. function ngDirective(directive) {
  20088. if (isFunction(directive)) {
  20089. directive = {
  20090. link: directive
  20091. };
  20092. }
  20093. directive.restrict = directive.restrict || 'AC';
  20094. return valueFn(directive);
  20095. }
  20096. /**
  20097. * @ngdoc directive
  20098. * @name a
  20099. * @restrict E
  20100. *
  20101. * @description
  20102. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20103. * the href attribute is empty.
  20104. *
  20105. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20106. */
  20107. var htmlAnchorDirective = valueFn({
  20108. restrict: 'E',
  20109. compile: function(element, attr) {
  20110. if (!attr.href && !attr.xlinkHref) {
  20111. return function(scope, element) {
  20112. // If the linked element is not an anchor tag anymore, do nothing
  20113. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20114. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20115. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20116. 'xlink:href' : 'href';
  20117. element.on('click', function(event) {
  20118. // if we have no href url, then don't navigate anywhere.
  20119. if (!element.attr(href)) {
  20120. event.preventDefault();
  20121. }
  20122. });
  20123. };
  20124. }
  20125. }
  20126. });
  20127. /**
  20128. * @ngdoc directive
  20129. * @name ngHref
  20130. * @restrict A
  20131. * @priority 99
  20132. *
  20133. * @description
  20134. * Using Angular markup like `{{hash}}` in an href attribute will
  20135. * make the link go to the wrong URL if the user clicks it before
  20136. * Angular has a chance to replace the `{{hash}}` markup with its
  20137. * value. Until Angular replaces the markup the link will be broken
  20138. * and will most likely return a 404 error. The `ngHref` directive
  20139. * solves this problem.
  20140. *
  20141. * The wrong way to write it:
  20142. * ```html
  20143. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20144. * ```
  20145. *
  20146. * The correct way to write it:
  20147. * ```html
  20148. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20149. * ```
  20150. *
  20151. * @element A
  20152. * @param {template} ngHref any string which can contain `{{}}` markup.
  20153. *
  20154. * @example
  20155. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20156. * in links and their different behaviors:
  20157. <example name="ng-href">
  20158. <file name="index.html">
  20159. <input ng-model="value" /><br />
  20160. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20161. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20162. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20163. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20164. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20165. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20166. </file>
  20167. <file name="protractor.js" type="protractor">
  20168. it('should execute ng-click but not reload when href without value', function() {
  20169. element(by.id('link-1')).click();
  20170. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20171. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20172. });
  20173. it('should execute ng-click but not reload when href empty string', function() {
  20174. element(by.id('link-2')).click();
  20175. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20176. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20177. });
  20178. it('should execute ng-click and change url when ng-href specified', function() {
  20179. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20180. element(by.id('link-3')).click();
  20181. // At this point, we navigate away from an Angular page, so we need
  20182. // to use browser.driver to get the base webdriver.
  20183. browser.wait(function() {
  20184. return browser.driver.getCurrentUrl().then(function(url) {
  20185. return url.match(/\/123$/);
  20186. });
  20187. }, 5000, 'page should navigate to /123');
  20188. });
  20189. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20190. element(by.id('link-4')).click();
  20191. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20192. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20193. });
  20194. it('should execute ng-click but not reload when no href but name specified', function() {
  20195. element(by.id('link-5')).click();
  20196. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20197. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20198. });
  20199. it('should only change url when only ng-href', function() {
  20200. element(by.model('value')).clear();
  20201. element(by.model('value')).sendKeys('6');
  20202. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20203. element(by.id('link-6')).click();
  20204. // At this point, we navigate away from an Angular page, so we need
  20205. // to use browser.driver to get the base webdriver.
  20206. browser.wait(function() {
  20207. return browser.driver.getCurrentUrl().then(function(url) {
  20208. return url.match(/\/6$/);
  20209. });
  20210. }, 5000, 'page should navigate to /6');
  20211. });
  20212. </file>
  20213. </example>
  20214. */
  20215. /**
  20216. * @ngdoc directive
  20217. * @name ngSrc
  20218. * @restrict A
  20219. * @priority 99
  20220. *
  20221. * @description
  20222. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20223. * work right: The browser will fetch from the URL with the literal
  20224. * text `{{hash}}` until Angular replaces the expression inside
  20225. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20226. *
  20227. * The buggy way to write it:
  20228. * ```html
  20229. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20230. * ```
  20231. *
  20232. * The correct way to write it:
  20233. * ```html
  20234. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20235. * ```
  20236. *
  20237. * @element IMG
  20238. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20239. */
  20240. /**
  20241. * @ngdoc directive
  20242. * @name ngSrcset
  20243. * @restrict A
  20244. * @priority 99
  20245. *
  20246. * @description
  20247. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20248. * work right: The browser will fetch from the URL with the literal
  20249. * text `{{hash}}` until Angular replaces the expression inside
  20250. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20251. *
  20252. * The buggy way to write it:
  20253. * ```html
  20254. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20255. * ```
  20256. *
  20257. * The correct way to write it:
  20258. * ```html
  20259. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20260. * ```
  20261. *
  20262. * @element IMG
  20263. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20264. */
  20265. /**
  20266. * @ngdoc directive
  20267. * @name ngDisabled
  20268. * @restrict A
  20269. * @priority 100
  20270. *
  20271. * @description
  20272. *
  20273. * This directive sets the `disabled` attribute on the element if the
  20274. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20275. *
  20276. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20277. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20278. *
  20279. * @example
  20280. <example name="ng-disabled">
  20281. <file name="index.html">
  20282. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20283. <button ng-model="button" ng-disabled="checked">Button</button>
  20284. </file>
  20285. <file name="protractor.js" type="protractor">
  20286. it('should toggle button', function() {
  20287. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20288. element(by.model('checked')).click();
  20289. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20290. });
  20291. </file>
  20292. </example>
  20293. *
  20294. * @element INPUT
  20295. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20296. * then the `disabled` attribute will be set on the element
  20297. */
  20298. /**
  20299. * @ngdoc directive
  20300. * @name ngChecked
  20301. * @restrict A
  20302. * @priority 100
  20303. *
  20304. * @description
  20305. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20306. *
  20307. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20308. * as this can lead to unexpected behavior.
  20309. *
  20310. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20311. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20312. *
  20313. * @example
  20314. <example name="ng-checked">
  20315. <file name="index.html">
  20316. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20317. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20318. </file>
  20319. <file name="protractor.js" type="protractor">
  20320. it('should check both checkBoxes', function() {
  20321. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20322. element(by.model('master')).click();
  20323. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20324. });
  20325. </file>
  20326. </example>
  20327. *
  20328. * @element INPUT
  20329. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20330. * then the `checked` attribute will be set on the element
  20331. */
  20332. /**
  20333. * @ngdoc directive
  20334. * @name ngReadonly
  20335. * @restrict A
  20336. * @priority 100
  20337. *
  20338. * @description
  20339. *
  20340. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20341. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20342. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20343. *
  20344. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20345. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20346. *
  20347. * @example
  20348. <example name="ng-readonly">
  20349. <file name="index.html">
  20350. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20351. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20352. </file>
  20353. <file name="protractor.js" type="protractor">
  20354. it('should toggle readonly attr', function() {
  20355. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20356. element(by.model('checked')).click();
  20357. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20358. });
  20359. </file>
  20360. </example>
  20361. *
  20362. * @element INPUT
  20363. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20364. * then special attribute "readonly" will be set on the element
  20365. */
  20366. /**
  20367. * @ngdoc directive
  20368. * @name ngSelected
  20369. * @restrict A
  20370. * @priority 100
  20371. *
  20372. * @description
  20373. *
  20374. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20375. *
  20376. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20377. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20378. *
  20379. * <div class="alert alert-warning">
  20380. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20381. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20382. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20383. * selected options.
  20384. * </div>
  20385. *
  20386. * @example
  20387. <example name="ng-selected">
  20388. <file name="index.html">
  20389. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20390. <select aria-label="ngSelected demo">
  20391. <option>Hello!</option>
  20392. <option id="greet" ng-selected="selected">Greetings!</option>
  20393. </select>
  20394. </file>
  20395. <file name="protractor.js" type="protractor">
  20396. it('should select Greetings!', function() {
  20397. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20398. element(by.model('selected')).click();
  20399. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20400. });
  20401. </file>
  20402. </example>
  20403. *
  20404. * @element OPTION
  20405. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20406. * then special attribute "selected" will be set on the element
  20407. */
  20408. /**
  20409. * @ngdoc directive
  20410. * @name ngOpen
  20411. * @restrict A
  20412. * @priority 100
  20413. *
  20414. * @description
  20415. *
  20416. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20417. *
  20418. * A special directive is necessary because we cannot use interpolation inside the `open`
  20419. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20420. *
  20421. * ## A note about browser compatibility
  20422. *
  20423. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20424. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20425. *
  20426. * @example
  20427. <example name="ng-open">
  20428. <file name="index.html">
  20429. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20430. <details id="details" ng-open="open">
  20431. <summary>Show/Hide me</summary>
  20432. </details>
  20433. </file>
  20434. <file name="protractor.js" type="protractor">
  20435. it('should toggle open', function() {
  20436. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20437. element(by.model('open')).click();
  20438. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20439. });
  20440. </file>
  20441. </example>
  20442. *
  20443. * @element DETAILS
  20444. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20445. * then special attribute "open" will be set on the element
  20446. */
  20447. var ngAttributeAliasDirectives = {};
  20448. // boolean attrs are evaluated
  20449. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20450. // binding to multiple is not supported
  20451. if (propName === 'multiple') return;
  20452. function defaultLinkFn(scope, element, attr) {
  20453. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20454. attr.$set(attrName, !!value);
  20455. });
  20456. }
  20457. var normalized = directiveNormalize('ng-' + attrName);
  20458. var linkFn = defaultLinkFn;
  20459. if (propName === 'checked') {
  20460. linkFn = function(scope, element, attr) {
  20461. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20462. if (attr.ngModel !== attr[normalized]) {
  20463. defaultLinkFn(scope, element, attr);
  20464. }
  20465. };
  20466. }
  20467. ngAttributeAliasDirectives[normalized] = function() {
  20468. return {
  20469. restrict: 'A',
  20470. priority: 100,
  20471. link: linkFn
  20472. };
  20473. };
  20474. });
  20475. // aliased input attrs are evaluated
  20476. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20477. ngAttributeAliasDirectives[ngAttr] = function() {
  20478. return {
  20479. priority: 100,
  20480. link: function(scope, element, attr) {
  20481. //special case ngPattern when a literal regular expression value
  20482. //is used as the expression (this way we don't have to watch anything).
  20483. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  20484. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20485. if (match) {
  20486. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  20487. return;
  20488. }
  20489. }
  20490. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20491. attr.$set(ngAttr, value);
  20492. });
  20493. }
  20494. };
  20495. };
  20496. });
  20497. // ng-src, ng-srcset, ng-href are interpolated
  20498. forEach(['src', 'srcset', 'href'], function(attrName) {
  20499. var normalized = directiveNormalize('ng-' + attrName);
  20500. ngAttributeAliasDirectives[normalized] = function() {
  20501. return {
  20502. priority: 99, // it needs to run after the attributes are interpolated
  20503. link: function(scope, element, attr) {
  20504. var propName = attrName,
  20505. name = attrName;
  20506. if (attrName === 'href' &&
  20507. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20508. name = 'xlinkHref';
  20509. attr.$attr[name] = 'xlink:href';
  20510. propName = null;
  20511. }
  20512. attr.$observe(normalized, function(value) {
  20513. if (!value) {
  20514. if (attrName === 'href') {
  20515. attr.$set(name, null);
  20516. }
  20517. return;
  20518. }
  20519. attr.$set(name, value);
  20520. // Support: IE 9-11 only
  20521. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20522. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20523. // to set the property as well to achieve the desired effect.
  20524. // We use attr[attrName] value since $set can sanitize the url.
  20525. if (msie && propName) element.prop(propName, attr[name]);
  20526. });
  20527. }
  20528. };
  20529. };
  20530. });
  20531. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  20532. */
  20533. var nullFormCtrl = {
  20534. $addControl: noop,
  20535. $$renameControl: nullFormRenameControl,
  20536. $removeControl: noop,
  20537. $setValidity: noop,
  20538. $setDirty: noop,
  20539. $setPristine: noop,
  20540. $setSubmitted: noop
  20541. },
  20542. PENDING_CLASS = 'ng-pending',
  20543. SUBMITTED_CLASS = 'ng-submitted';
  20544. function nullFormRenameControl(control, name) {
  20545. control.$name = name;
  20546. }
  20547. /**
  20548. * @ngdoc type
  20549. * @name form.FormController
  20550. *
  20551. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20552. * @property {boolean} $dirty True if user has already interacted with the form.
  20553. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20554. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20555. * @property {boolean} $pending True if at least one containing control or form is pending.
  20556. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20557. *
  20558. * @property {Object} $error Is an object hash, containing references to controls or
  20559. * forms with failing validators, where:
  20560. *
  20561. * - keys are validation tokens (error names),
  20562. * - values are arrays of controls or forms that have a failing validator for given error name.
  20563. *
  20564. * Built-in validation tokens:
  20565. *
  20566. * - `email`
  20567. * - `max`
  20568. * - `maxlength`
  20569. * - `min`
  20570. * - `minlength`
  20571. * - `number`
  20572. * - `pattern`
  20573. * - `required`
  20574. * - `url`
  20575. * - `date`
  20576. * - `datetimelocal`
  20577. * - `time`
  20578. * - `week`
  20579. * - `month`
  20580. *
  20581. * @description
  20582. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20583. * such as being valid/invalid or dirty/pristine.
  20584. *
  20585. * Each {@link ng.directive:form form} directive creates an instance
  20586. * of `FormController`.
  20587. *
  20588. */
  20589. //asks for $scope to fool the BC controller module
  20590. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20591. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  20592. this.$$controls = [];
  20593. // init state
  20594. this.$error = {};
  20595. this.$$success = {};
  20596. this.$pending = undefined;
  20597. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  20598. this.$dirty = false;
  20599. this.$pristine = true;
  20600. this.$valid = true;
  20601. this.$invalid = false;
  20602. this.$submitted = false;
  20603. this.$$parentForm = nullFormCtrl;
  20604. this.$$element = $element;
  20605. this.$$animate = $animate;
  20606. setupValidity(this);
  20607. }
  20608. FormController.prototype = {
  20609. /**
  20610. * @ngdoc method
  20611. * @name form.FormController#$rollbackViewValue
  20612. *
  20613. * @description
  20614. * Rollback all form controls pending updates to the `$modelValue`.
  20615. *
  20616. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20617. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20618. * a form that uses `ng-model-options` to pend updates.
  20619. */
  20620. $rollbackViewValue: function() {
  20621. forEach(this.$$controls, function(control) {
  20622. control.$rollbackViewValue();
  20623. });
  20624. },
  20625. /**
  20626. * @ngdoc method
  20627. * @name form.FormController#$commitViewValue
  20628. *
  20629. * @description
  20630. * Commit all form controls pending updates to the `$modelValue`.
  20631. *
  20632. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20633. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20634. * usually handles calling this in response to input events.
  20635. */
  20636. $commitViewValue: function() {
  20637. forEach(this.$$controls, function(control) {
  20638. control.$commitViewValue();
  20639. });
  20640. },
  20641. /**
  20642. * @ngdoc method
  20643. * @name form.FormController#$addControl
  20644. * @param {object} control control object, either a {@link form.FormController} or an
  20645. * {@link ngModel.NgModelController}
  20646. *
  20647. * @description
  20648. * Register a control with the form. Input elements using ngModelController do this automatically
  20649. * when they are linked.
  20650. *
  20651. * Note that the current state of the control will not be reflected on the new parent form. This
  20652. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20653. * state.
  20654. *
  20655. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20656. * or controls that have been previously removed without destroying their corresponding DOM element,
  20657. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20658. *
  20659. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20660. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20661. */
  20662. $addControl: function(control) {
  20663. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20664. // and not added to the scope. Now we throw an error.
  20665. assertNotHasOwnProperty(control.$name, 'input');
  20666. this.$$controls.push(control);
  20667. if (control.$name) {
  20668. this[control.$name] = control;
  20669. }
  20670. control.$$parentForm = this;
  20671. },
  20672. // Private API: rename a form control
  20673. $$renameControl: function(control, newName) {
  20674. var oldName = control.$name;
  20675. if (this[oldName] === control) {
  20676. delete this[oldName];
  20677. }
  20678. this[newName] = control;
  20679. control.$name = newName;
  20680. },
  20681. /**
  20682. * @ngdoc method
  20683. * @name form.FormController#$removeControl
  20684. * @param {object} control control object, either a {@link form.FormController} or an
  20685. * {@link ngModel.NgModelController}
  20686. *
  20687. * @description
  20688. * Deregister a control from the form.
  20689. *
  20690. * Input elements using ngModelController do this automatically when they are destroyed.
  20691. *
  20692. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20693. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20694. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20695. * may not mean that the form is still `$dirty`.
  20696. */
  20697. $removeControl: function(control) {
  20698. if (control.$name && this[control.$name] === control) {
  20699. delete this[control.$name];
  20700. }
  20701. forEach(this.$pending, function(value, name) {
  20702. // eslint-disable-next-line no-invalid-this
  20703. this.$setValidity(name, null, control);
  20704. }, this);
  20705. forEach(this.$error, function(value, name) {
  20706. // eslint-disable-next-line no-invalid-this
  20707. this.$setValidity(name, null, control);
  20708. }, this);
  20709. forEach(this.$$success, function(value, name) {
  20710. // eslint-disable-next-line no-invalid-this
  20711. this.$setValidity(name, null, control);
  20712. }, this);
  20713. arrayRemove(this.$$controls, control);
  20714. control.$$parentForm = nullFormCtrl;
  20715. },
  20716. /**
  20717. * @ngdoc method
  20718. * @name form.FormController#$setDirty
  20719. *
  20720. * @description
  20721. * Sets the form to a dirty state.
  20722. *
  20723. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20724. * state (ng-dirty class). This method will also propagate to parent forms.
  20725. */
  20726. $setDirty: function() {
  20727. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  20728. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  20729. this.$dirty = true;
  20730. this.$pristine = false;
  20731. this.$$parentForm.$setDirty();
  20732. },
  20733. /**
  20734. * @ngdoc method
  20735. * @name form.FormController#$setPristine
  20736. *
  20737. * @description
  20738. * Sets the form to its pristine state.
  20739. *
  20740. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  20741. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  20742. * state to false.
  20743. *
  20744. * This method will also propagate to all the controls contained in this form.
  20745. *
  20746. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20747. * saving or resetting it.
  20748. */
  20749. $setPristine: function() {
  20750. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20751. this.$dirty = false;
  20752. this.$pristine = true;
  20753. this.$submitted = false;
  20754. forEach(this.$$controls, function(control) {
  20755. control.$setPristine();
  20756. });
  20757. },
  20758. /**
  20759. * @ngdoc method
  20760. * @name form.FormController#$setUntouched
  20761. *
  20762. * @description
  20763. * Sets the form to its untouched state.
  20764. *
  20765. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20766. * untouched state (ng-untouched class).
  20767. *
  20768. * Setting a form controls back to their untouched state is often useful when setting the form
  20769. * back to its pristine state.
  20770. */
  20771. $setUntouched: function() {
  20772. forEach(this.$$controls, function(control) {
  20773. control.$setUntouched();
  20774. });
  20775. },
  20776. /**
  20777. * @ngdoc method
  20778. * @name form.FormController#$setSubmitted
  20779. *
  20780. * @description
  20781. * Sets the form to its submitted state.
  20782. */
  20783. $setSubmitted: function() {
  20784. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  20785. this.$submitted = true;
  20786. this.$$parentForm.$setSubmitted();
  20787. }
  20788. };
  20789. /**
  20790. * @ngdoc method
  20791. * @name form.FormController#$setValidity
  20792. *
  20793. * @description
  20794. * Sets the validity of a form control.
  20795. *
  20796. * This method will also propagate to parent forms.
  20797. */
  20798. addSetValidityMethod({
  20799. clazz: FormController,
  20800. set: function(object, property, controller) {
  20801. var list = object[property];
  20802. if (!list) {
  20803. object[property] = [controller];
  20804. } else {
  20805. var index = list.indexOf(controller);
  20806. if (index === -1) {
  20807. list.push(controller);
  20808. }
  20809. }
  20810. },
  20811. unset: function(object, property, controller) {
  20812. var list = object[property];
  20813. if (!list) {
  20814. return;
  20815. }
  20816. arrayRemove(list, controller);
  20817. if (list.length === 0) {
  20818. delete object[property];
  20819. }
  20820. }
  20821. });
  20822. /**
  20823. * @ngdoc directive
  20824. * @name ngForm
  20825. * @restrict EAC
  20826. *
  20827. * @description
  20828. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  20829. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  20830. * sub-group of controls needs to be determined.
  20831. *
  20832. * Note: the purpose of `ngForm` is to group controls,
  20833. * but not to be a replacement for the `<form>` tag with all of its capabilities
  20834. * (e.g. posting to the server, ...).
  20835. *
  20836. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  20837. * related scope, under this name.
  20838. *
  20839. */
  20840. /**
  20841. * @ngdoc directive
  20842. * @name form
  20843. * @restrict E
  20844. *
  20845. * @description
  20846. * Directive that instantiates
  20847. * {@link form.FormController FormController}.
  20848. *
  20849. * If the `name` attribute is specified, the form controller is published onto the current scope under
  20850. * this name.
  20851. *
  20852. * # Alias: {@link ng.directive:ngForm `ngForm`}
  20853. *
  20854. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  20855. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  20856. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  20857. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  20858. * of controls needs to be determined.
  20859. *
  20860. * # CSS classes
  20861. * - `ng-valid` is set if the form is valid.
  20862. * - `ng-invalid` is set if the form is invalid.
  20863. * - `ng-pending` is set if the form is pending.
  20864. * - `ng-pristine` is set if the form is pristine.
  20865. * - `ng-dirty` is set if the form is dirty.
  20866. * - `ng-submitted` is set if the form was submitted.
  20867. *
  20868. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  20869. *
  20870. *
  20871. * # Submitting a form and preventing the default action
  20872. *
  20873. * Since the role of forms in client-side Angular applications is different than in classical
  20874. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  20875. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  20876. * to handle the form submission in an application-specific way.
  20877. *
  20878. * For this reason, Angular prevents the default action (form submission to the server) unless the
  20879. * `<form>` element has an `action` attribute specified.
  20880. *
  20881. * You can use one of the following two ways to specify what javascript method should be called when
  20882. * a form is submitted:
  20883. *
  20884. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  20885. * - {@link ng.directive:ngClick ngClick} directive on the first
  20886. * button or input field of type submit (input[type=submit])
  20887. *
  20888. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  20889. * or {@link ng.directive:ngClick ngClick} directives.
  20890. * This is because of the following form submission rules in the HTML specification:
  20891. *
  20892. * - If a form has only one input field then hitting enter in this field triggers form submit
  20893. * (`ngSubmit`)
  20894. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  20895. * doesn't trigger submit
  20896. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  20897. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  20898. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  20899. *
  20900. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  20901. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  20902. * to have access to the updated model.
  20903. *
  20904. * ## Animation Hooks
  20905. *
  20906. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  20907. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  20908. * other validations that are performed within the form. Animations in ngForm are similar to how
  20909. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  20910. * as JS animations.
  20911. *
  20912. * The following example shows a simple way to utilize CSS transitions to style a form element
  20913. * that has been rendered as invalid after it has been validated:
  20914. *
  20915. * <pre>
  20916. * //be sure to include ngAnimate as a module to hook into more
  20917. * //advanced animations
  20918. * .my-form {
  20919. * transition:0.5s linear all;
  20920. * background: white;
  20921. * }
  20922. * .my-form.ng-invalid {
  20923. * background: red;
  20924. * color:white;
  20925. * }
  20926. * </pre>
  20927. *
  20928. * @example
  20929. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  20930. <file name="index.html">
  20931. <script>
  20932. angular.module('formExample', [])
  20933. .controller('FormController', ['$scope', function($scope) {
  20934. $scope.userType = 'guest';
  20935. }]);
  20936. </script>
  20937. <style>
  20938. .my-form {
  20939. transition:all linear 0.5s;
  20940. background: transparent;
  20941. }
  20942. .my-form.ng-invalid {
  20943. background: red;
  20944. }
  20945. </style>
  20946. <form name="myForm" ng-controller="FormController" class="my-form">
  20947. userType: <input name="input" ng-model="userType" required>
  20948. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  20949. <code>userType = {{userType}}</code><br>
  20950. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  20951. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  20952. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  20953. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  20954. </form>
  20955. </file>
  20956. <file name="protractor.js" type="protractor">
  20957. it('should initialize to model', function() {
  20958. var userType = element(by.binding('userType'));
  20959. var valid = element(by.binding('myForm.input.$valid'));
  20960. expect(userType.getText()).toContain('guest');
  20961. expect(valid.getText()).toContain('true');
  20962. });
  20963. it('should be invalid if empty', function() {
  20964. var userType = element(by.binding('userType'));
  20965. var valid = element(by.binding('myForm.input.$valid'));
  20966. var userInput = element(by.model('userType'));
  20967. userInput.clear();
  20968. userInput.sendKeys('');
  20969. expect(userType.getText()).toEqual('userType =');
  20970. expect(valid.getText()).toContain('false');
  20971. });
  20972. </file>
  20973. </example>
  20974. *
  20975. * @param {string=} name Name of the form. If specified, the form controller will be published into
  20976. * related scope, under this name.
  20977. */
  20978. var formDirectiveFactory = function(isNgForm) {
  20979. return ['$timeout', '$parse', function($timeout, $parse) {
  20980. var formDirective = {
  20981. name: 'form',
  20982. restrict: isNgForm ? 'EAC' : 'E',
  20983. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  20984. controller: FormController,
  20985. compile: function ngFormCompile(formElement, attr) {
  20986. // Setup initial state of the control
  20987. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  20988. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  20989. return {
  20990. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  20991. var controller = ctrls[0];
  20992. // if `action` attr is not present on the form, prevent the default action (submission)
  20993. if (!('action' in attr)) {
  20994. // we can't use jq events because if a form is destroyed during submission the default
  20995. // action is not prevented. see #1238
  20996. //
  20997. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  20998. // page reload if the form was destroyed by submission of the form via a click handler
  20999. // on a button in the form. Looks like an IE9 specific bug.
  21000. var handleFormSubmission = function(event) {
  21001. scope.$apply(function() {
  21002. controller.$commitViewValue();
  21003. controller.$setSubmitted();
  21004. });
  21005. event.preventDefault();
  21006. };
  21007. formElement[0].addEventListener('submit', handleFormSubmission);
  21008. // unregister the preventDefault listener so that we don't not leak memory but in a
  21009. // way that will achieve the prevention of the default action.
  21010. formElement.on('$destroy', function() {
  21011. $timeout(function() {
  21012. formElement[0].removeEventListener('submit', handleFormSubmission);
  21013. }, 0, false);
  21014. });
  21015. }
  21016. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21017. parentFormCtrl.$addControl(controller);
  21018. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21019. if (nameAttr) {
  21020. setter(scope, controller);
  21021. attr.$observe(nameAttr, function(newValue) {
  21022. if (controller.$name === newValue) return;
  21023. setter(scope, undefined);
  21024. controller.$$parentForm.$$renameControl(controller, newValue);
  21025. setter = getSetter(controller.$name);
  21026. setter(scope, controller);
  21027. });
  21028. }
  21029. formElement.on('$destroy', function() {
  21030. controller.$$parentForm.$removeControl(controller);
  21031. setter(scope, undefined);
  21032. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21033. });
  21034. }
  21035. };
  21036. }
  21037. };
  21038. return formDirective;
  21039. function getSetter(expression) {
  21040. if (expression === '') {
  21041. //create an assignable expression, so forms with an empty name can be renamed later
  21042. return $parse('this[""]').assign;
  21043. }
  21044. return $parse(expression).assign || noop;
  21045. }
  21046. }];
  21047. };
  21048. var formDirective = formDirectiveFactory();
  21049. var ngFormDirective = formDirectiveFactory(true);
  21050. // helper methods
  21051. function setupValidity(instance) {
  21052. instance.$$classCache = {};
  21053. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21054. }
  21055. function addSetValidityMethod(context) {
  21056. var clazz = context.clazz,
  21057. set = context.set,
  21058. unset = context.unset;
  21059. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21060. if (isUndefined(state)) {
  21061. createAndSet(this, '$pending', validationErrorKey, controller);
  21062. } else {
  21063. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21064. }
  21065. if (!isBoolean(state)) {
  21066. unset(this.$error, validationErrorKey, controller);
  21067. unset(this.$$success, validationErrorKey, controller);
  21068. } else {
  21069. if (state) {
  21070. unset(this.$error, validationErrorKey, controller);
  21071. set(this.$$success, validationErrorKey, controller);
  21072. } else {
  21073. set(this.$error, validationErrorKey, controller);
  21074. unset(this.$$success, validationErrorKey, controller);
  21075. }
  21076. }
  21077. if (this.$pending) {
  21078. cachedToggleClass(this, PENDING_CLASS, true);
  21079. this.$valid = this.$invalid = undefined;
  21080. toggleValidationCss(this, '', null);
  21081. } else {
  21082. cachedToggleClass(this, PENDING_CLASS, false);
  21083. this.$valid = isObjectEmpty(this.$error);
  21084. this.$invalid = !this.$valid;
  21085. toggleValidationCss(this, '', this.$valid);
  21086. }
  21087. // re-read the state as the set/unset methods could have
  21088. // combined state in this.$error[validationError] (used for forms),
  21089. // where setting/unsetting only increments/decrements the value,
  21090. // and does not replace it.
  21091. var combinedState;
  21092. if (this.$pending && this.$pending[validationErrorKey]) {
  21093. combinedState = undefined;
  21094. } else if (this.$error[validationErrorKey]) {
  21095. combinedState = false;
  21096. } else if (this.$$success[validationErrorKey]) {
  21097. combinedState = true;
  21098. } else {
  21099. combinedState = null;
  21100. }
  21101. toggleValidationCss(this, validationErrorKey, combinedState);
  21102. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21103. };
  21104. function createAndSet(ctrl, name, value, controller) {
  21105. if (!ctrl[name]) {
  21106. ctrl[name] = {};
  21107. }
  21108. set(ctrl[name], value, controller);
  21109. }
  21110. function unsetAndCleanup(ctrl, name, value, controller) {
  21111. if (ctrl[name]) {
  21112. unset(ctrl[name], value, controller);
  21113. }
  21114. if (isObjectEmpty(ctrl[name])) {
  21115. ctrl[name] = undefined;
  21116. }
  21117. }
  21118. function cachedToggleClass(ctrl, className, switchValue) {
  21119. if (switchValue && !ctrl.$$classCache[className]) {
  21120. ctrl.$$animate.addClass(ctrl.$$element, className);
  21121. ctrl.$$classCache[className] = true;
  21122. } else if (!switchValue && ctrl.$$classCache[className]) {
  21123. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21124. ctrl.$$classCache[className] = false;
  21125. }
  21126. }
  21127. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21128. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21129. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21130. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21131. }
  21132. }
  21133. function isObjectEmpty(obj) {
  21134. if (obj) {
  21135. for (var prop in obj) {
  21136. if (obj.hasOwnProperty(prop)) {
  21137. return false;
  21138. }
  21139. }
  21140. }
  21141. return true;
  21142. }
  21143. /* global
  21144. VALID_CLASS: false,
  21145. INVALID_CLASS: false,
  21146. PRISTINE_CLASS: false,
  21147. DIRTY_CLASS: false,
  21148. ngModelMinErr: false
  21149. */
  21150. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21151. 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)$/;
  21152. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21153. // Note: We are being more lenient, because browsers are too.
  21154. // 1. Scheme
  21155. // 2. Slashes
  21156. // 3. Username
  21157. // 4. Password
  21158. // 5. Hostname
  21159. // 6. Port
  21160. // 7. Path
  21161. // 8. Query
  21162. // 9. Fragment
  21163. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21164. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21165. // eslint-disable-next-line max-len
  21166. var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
  21167. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21168. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21169. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21170. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21171. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21172. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21173. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21174. var PARTIAL_VALIDATION_TYPES = createMap();
  21175. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21176. PARTIAL_VALIDATION_TYPES[type] = true;
  21177. });
  21178. var inputType = {
  21179. /**
  21180. * @ngdoc input
  21181. * @name input[text]
  21182. *
  21183. * @description
  21184. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21185. *
  21186. *
  21187. * @param {string} ngModel Assignable angular expression to data-bind to.
  21188. * @param {string=} name Property name of the form under which the control is published.
  21189. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21190. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21191. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21192. * `required` when you want to data-bind to the `required` attribute.
  21193. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21194. * minlength.
  21195. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21196. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21197. * any length.
  21198. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21199. * that contains the regular expression body that will be converted to a regular expression
  21200. * as in the ngPattern directive.
  21201. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21202. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21203. * If the expression evaluates to a RegExp object, then this is used directly.
  21204. * If the expression evaluates to a string, then it will be converted to a RegExp
  21205. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21206. * `new RegExp('^abc$')`.<br />
  21207. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21208. * start at the index of the last search's match, thus not taking the whole input value into
  21209. * account.
  21210. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21211. * interaction with the input element.
  21212. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21213. * This parameter is ignored for input[type=password] controls, which will never trim the
  21214. * input.
  21215. *
  21216. * @example
  21217. <example name="text-input-directive" module="textInputExample">
  21218. <file name="index.html">
  21219. <script>
  21220. angular.module('textInputExample', [])
  21221. .controller('ExampleController', ['$scope', function($scope) {
  21222. $scope.example = {
  21223. text: 'guest',
  21224. word: /^\s*\w*\s*$/
  21225. };
  21226. }]);
  21227. </script>
  21228. <form name="myForm" ng-controller="ExampleController">
  21229. <label>Single word:
  21230. <input type="text" name="input" ng-model="example.text"
  21231. ng-pattern="example.word" required ng-trim="false">
  21232. </label>
  21233. <div role="alert">
  21234. <span class="error" ng-show="myForm.input.$error.required">
  21235. Required!</span>
  21236. <span class="error" ng-show="myForm.input.$error.pattern">
  21237. Single word only!</span>
  21238. </div>
  21239. <code>text = {{example.text}}</code><br/>
  21240. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21241. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21242. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21243. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21244. </form>
  21245. </file>
  21246. <file name="protractor.js" type="protractor">
  21247. var text = element(by.binding('example.text'));
  21248. var valid = element(by.binding('myForm.input.$valid'));
  21249. var input = element(by.model('example.text'));
  21250. it('should initialize to model', function() {
  21251. expect(text.getText()).toContain('guest');
  21252. expect(valid.getText()).toContain('true');
  21253. });
  21254. it('should be invalid if empty', function() {
  21255. input.clear();
  21256. input.sendKeys('');
  21257. expect(text.getText()).toEqual('text =');
  21258. expect(valid.getText()).toContain('false');
  21259. });
  21260. it('should be invalid if multi word', function() {
  21261. input.clear();
  21262. input.sendKeys('hello world');
  21263. expect(valid.getText()).toContain('false');
  21264. });
  21265. </file>
  21266. </example>
  21267. */
  21268. 'text': textInputType,
  21269. /**
  21270. * @ngdoc input
  21271. * @name input[date]
  21272. *
  21273. * @description
  21274. * Input with date validation and transformation. In browsers that do not yet support
  21275. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21276. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21277. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21278. * expected input format via a placeholder or label.
  21279. *
  21280. * The model must always be a Date object, otherwise Angular will throw an error.
  21281. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21282. *
  21283. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21284. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21285. *
  21286. * @param {string} ngModel Assignable angular expression to data-bind to.
  21287. * @param {string=} name Property name of the form under which the control is published.
  21288. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21289. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21290. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21291. * constraint validation.
  21292. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21293. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21294. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21295. * constraint validation.
  21296. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21297. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21298. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21299. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21300. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21301. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21302. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21303. * `required` when you want to data-bind to the `required` attribute.
  21304. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21305. * interaction with the input element.
  21306. *
  21307. * @example
  21308. <example name="date-input-directive" module="dateInputExample">
  21309. <file name="index.html">
  21310. <script>
  21311. angular.module('dateInputExample', [])
  21312. .controller('DateController', ['$scope', function($scope) {
  21313. $scope.example = {
  21314. value: new Date(2013, 9, 22)
  21315. };
  21316. }]);
  21317. </script>
  21318. <form name="myForm" ng-controller="DateController as dateCtrl">
  21319. <label for="exampleInput">Pick a date in 2013:</label>
  21320. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21321. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21322. <div role="alert">
  21323. <span class="error" ng-show="myForm.input.$error.required">
  21324. Required!</span>
  21325. <span class="error" ng-show="myForm.input.$error.date">
  21326. Not a valid date!</span>
  21327. </div>
  21328. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21329. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21330. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21331. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21332. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21333. </form>
  21334. </file>
  21335. <file name="protractor.js" type="protractor">
  21336. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21337. var valid = element(by.binding('myForm.input.$valid'));
  21338. // currently protractor/webdriver does not support
  21339. // sending keys to all known HTML5 input controls
  21340. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21341. function setInput(val) {
  21342. // set the value of the element and force validation.
  21343. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21344. "ipt.value = '" + val + "';" +
  21345. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21346. browser.executeScript(scr);
  21347. }
  21348. it('should initialize to model', function() {
  21349. expect(value.getText()).toContain('2013-10-22');
  21350. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21351. });
  21352. it('should be invalid if empty', function() {
  21353. setInput('');
  21354. expect(value.getText()).toEqual('value =');
  21355. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21356. });
  21357. it('should be invalid if over max', function() {
  21358. setInput('2015-01-01');
  21359. expect(value.getText()).toContain('');
  21360. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21361. });
  21362. </file>
  21363. </example>
  21364. */
  21365. 'date': createDateInputType('date', DATE_REGEXP,
  21366. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21367. 'yyyy-MM-dd'),
  21368. /**
  21369. * @ngdoc input
  21370. * @name input[datetime-local]
  21371. *
  21372. * @description
  21373. * Input with datetime validation and transformation. In browsers that do not yet support
  21374. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21375. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21376. *
  21377. * The model must always be a Date object, otherwise Angular will throw an error.
  21378. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21379. *
  21380. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21381. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21382. *
  21383. * @param {string} ngModel Assignable angular expression to data-bind to.
  21384. * @param {string=} name Property name of the form under which the control is published.
  21385. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21386. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21387. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21388. * Note that `min` will also add native HTML5 constraint validation.
  21389. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21390. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21391. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21392. * Note that `max` will also add native HTML5 constraint validation.
  21393. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21394. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21395. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21396. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21397. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21398. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21399. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21400. * `required` when you want to data-bind to the `required` attribute.
  21401. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21402. * interaction with the input element.
  21403. *
  21404. * @example
  21405. <example name="datetimelocal-input-directive" module="dateExample">
  21406. <file name="index.html">
  21407. <script>
  21408. angular.module('dateExample', [])
  21409. .controller('DateController', ['$scope', function($scope) {
  21410. $scope.example = {
  21411. value: new Date(2010, 11, 28, 14, 57)
  21412. };
  21413. }]);
  21414. </script>
  21415. <form name="myForm" ng-controller="DateController as dateCtrl">
  21416. <label for="exampleInput">Pick a date between in 2013:</label>
  21417. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21418. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21419. <div role="alert">
  21420. <span class="error" ng-show="myForm.input.$error.required">
  21421. Required!</span>
  21422. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21423. Not a valid date!</span>
  21424. </div>
  21425. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21426. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21427. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21428. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21429. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21430. </form>
  21431. </file>
  21432. <file name="protractor.js" type="protractor">
  21433. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21434. var valid = element(by.binding('myForm.input.$valid'));
  21435. // currently protractor/webdriver does not support
  21436. // sending keys to all known HTML5 input controls
  21437. // for various browsers (https://github.com/angular/protractor/issues/562).
  21438. function setInput(val) {
  21439. // set the value of the element and force validation.
  21440. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21441. "ipt.value = '" + val + "';" +
  21442. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21443. browser.executeScript(scr);
  21444. }
  21445. it('should initialize to model', function() {
  21446. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21447. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21448. });
  21449. it('should be invalid if empty', function() {
  21450. setInput('');
  21451. expect(value.getText()).toEqual('value =');
  21452. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21453. });
  21454. it('should be invalid if over max', function() {
  21455. setInput('2015-01-01T23:59:00');
  21456. expect(value.getText()).toContain('');
  21457. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21458. });
  21459. </file>
  21460. </example>
  21461. */
  21462. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21463. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21464. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21465. /**
  21466. * @ngdoc input
  21467. * @name input[time]
  21468. *
  21469. * @description
  21470. * Input with time validation and transformation. In browsers that do not yet support
  21471. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21472. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21473. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21474. *
  21475. * The model must always be a Date object, otherwise Angular will throw an error.
  21476. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21477. *
  21478. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21479. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21480. *
  21481. * @param {string} ngModel Assignable angular expression to data-bind to.
  21482. * @param {string=} name Property name of the form under which the control is published.
  21483. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21484. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21485. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21486. * native HTML5 constraint validation.
  21487. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21488. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21489. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21490. * native HTML5 constraint validation.
  21491. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21492. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21493. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21494. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21495. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21496. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21497. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21498. * `required` when you want to data-bind to the `required` attribute.
  21499. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21500. * interaction with the input element.
  21501. *
  21502. * @example
  21503. <example name="time-input-directive" module="timeExample">
  21504. <file name="index.html">
  21505. <script>
  21506. angular.module('timeExample', [])
  21507. .controller('DateController', ['$scope', function($scope) {
  21508. $scope.example = {
  21509. value: new Date(1970, 0, 1, 14, 57, 0)
  21510. };
  21511. }]);
  21512. </script>
  21513. <form name="myForm" ng-controller="DateController as dateCtrl">
  21514. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21515. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21516. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21517. <div role="alert">
  21518. <span class="error" ng-show="myForm.input.$error.required">
  21519. Required!</span>
  21520. <span class="error" ng-show="myForm.input.$error.time">
  21521. Not a valid date!</span>
  21522. </div>
  21523. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21524. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21525. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21526. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21527. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21528. </form>
  21529. </file>
  21530. <file name="protractor.js" type="protractor">
  21531. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21532. var valid = element(by.binding('myForm.input.$valid'));
  21533. // currently protractor/webdriver does not support
  21534. // sending keys to all known HTML5 input controls
  21535. // for various browsers (https://github.com/angular/protractor/issues/562).
  21536. function setInput(val) {
  21537. // set the value of the element and force validation.
  21538. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21539. "ipt.value = '" + val + "';" +
  21540. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21541. browser.executeScript(scr);
  21542. }
  21543. it('should initialize to model', function() {
  21544. expect(value.getText()).toContain('14:57:00');
  21545. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21546. });
  21547. it('should be invalid if empty', function() {
  21548. setInput('');
  21549. expect(value.getText()).toEqual('value =');
  21550. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21551. });
  21552. it('should be invalid if over max', function() {
  21553. setInput('23:59:00');
  21554. expect(value.getText()).toContain('');
  21555. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21556. });
  21557. </file>
  21558. </example>
  21559. */
  21560. 'time': createDateInputType('time', TIME_REGEXP,
  21561. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21562. 'HH:mm:ss.sss'),
  21563. /**
  21564. * @ngdoc input
  21565. * @name input[week]
  21566. *
  21567. * @description
  21568. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21569. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21570. * week format (yyyy-W##), for example: `2013-W02`.
  21571. *
  21572. * The model must always be a Date object, otherwise Angular will throw an error.
  21573. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21574. *
  21575. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21576. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21577. *
  21578. * @param {string} ngModel Assignable angular expression to data-bind to.
  21579. * @param {string=} name Property name of the form under which the control is published.
  21580. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21581. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21582. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21583. * native HTML5 constraint validation.
  21584. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21585. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21586. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21587. * native HTML5 constraint validation.
  21588. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21589. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21590. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21591. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21592. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21593. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21594. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21595. * `required` when you want to data-bind to the `required` attribute.
  21596. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21597. * interaction with the input element.
  21598. *
  21599. * @example
  21600. <example name="week-input-directive" module="weekExample">
  21601. <file name="index.html">
  21602. <script>
  21603. angular.module('weekExample', [])
  21604. .controller('DateController', ['$scope', function($scope) {
  21605. $scope.example = {
  21606. value: new Date(2013, 0, 3)
  21607. };
  21608. }]);
  21609. </script>
  21610. <form name="myForm" ng-controller="DateController as dateCtrl">
  21611. <label>Pick a date between in 2013:
  21612. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21613. placeholder="YYYY-W##" min="2012-W32"
  21614. max="2013-W52" required />
  21615. </label>
  21616. <div role="alert">
  21617. <span class="error" ng-show="myForm.input.$error.required">
  21618. Required!</span>
  21619. <span class="error" ng-show="myForm.input.$error.week">
  21620. Not a valid date!</span>
  21621. </div>
  21622. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21623. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21624. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21625. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21626. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21627. </form>
  21628. </file>
  21629. <file name="protractor.js" type="protractor">
  21630. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21631. var valid = element(by.binding('myForm.input.$valid'));
  21632. // currently protractor/webdriver does not support
  21633. // sending keys to all known HTML5 input controls
  21634. // for various browsers (https://github.com/angular/protractor/issues/562).
  21635. function setInput(val) {
  21636. // set the value of the element and force validation.
  21637. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21638. "ipt.value = '" + val + "';" +
  21639. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21640. browser.executeScript(scr);
  21641. }
  21642. it('should initialize to model', function() {
  21643. expect(value.getText()).toContain('2013-W01');
  21644. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21645. });
  21646. it('should be invalid if empty', function() {
  21647. setInput('');
  21648. expect(value.getText()).toEqual('value =');
  21649. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21650. });
  21651. it('should be invalid if over max', function() {
  21652. setInput('2015-W01');
  21653. expect(value.getText()).toContain('');
  21654. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21655. });
  21656. </file>
  21657. </example>
  21658. */
  21659. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21660. /**
  21661. * @ngdoc input
  21662. * @name input[month]
  21663. *
  21664. * @description
  21665. * Input with month validation and transformation. In browsers that do not yet support
  21666. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21667. * month format (yyyy-MM), for example: `2009-01`.
  21668. *
  21669. * The model must always be a Date object, otherwise Angular will throw an error.
  21670. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21671. * If the model is not set to the first of the month, the next view to model update will set it
  21672. * to the first of the month.
  21673. *
  21674. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21675. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21676. *
  21677. * @param {string} ngModel Assignable angular expression to data-bind to.
  21678. * @param {string=} name Property name of the form under which the control is published.
  21679. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21680. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21681. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21682. * native HTML5 constraint validation.
  21683. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21684. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21685. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21686. * native HTML5 constraint validation.
  21687. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21688. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21689. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21690. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21691. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21692. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21693. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21694. * `required` when you want to data-bind to the `required` attribute.
  21695. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21696. * interaction with the input element.
  21697. *
  21698. * @example
  21699. <example name="month-input-directive" module="monthExample">
  21700. <file name="index.html">
  21701. <script>
  21702. angular.module('monthExample', [])
  21703. .controller('DateController', ['$scope', function($scope) {
  21704. $scope.example = {
  21705. value: new Date(2013, 9, 1)
  21706. };
  21707. }]);
  21708. </script>
  21709. <form name="myForm" ng-controller="DateController as dateCtrl">
  21710. <label for="exampleInput">Pick a month in 2013:</label>
  21711. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21712. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21713. <div role="alert">
  21714. <span class="error" ng-show="myForm.input.$error.required">
  21715. Required!</span>
  21716. <span class="error" ng-show="myForm.input.$error.month">
  21717. Not a valid month!</span>
  21718. </div>
  21719. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21720. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21721. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21722. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21723. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21724. </form>
  21725. </file>
  21726. <file name="protractor.js" type="protractor">
  21727. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21728. var valid = element(by.binding('myForm.input.$valid'));
  21729. // currently protractor/webdriver does not support
  21730. // sending keys to all known HTML5 input controls
  21731. // for various browsers (https://github.com/angular/protractor/issues/562).
  21732. function setInput(val) {
  21733. // set the value of the element and force validation.
  21734. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21735. "ipt.value = '" + val + "';" +
  21736. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21737. browser.executeScript(scr);
  21738. }
  21739. it('should initialize to model', function() {
  21740. expect(value.getText()).toContain('2013-10');
  21741. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21742. });
  21743. it('should be invalid if empty', function() {
  21744. setInput('');
  21745. expect(value.getText()).toEqual('value =');
  21746. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21747. });
  21748. it('should be invalid if over max', function() {
  21749. setInput('2015-01');
  21750. expect(value.getText()).toContain('');
  21751. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21752. });
  21753. </file>
  21754. </example>
  21755. */
  21756. 'month': createDateInputType('month', MONTH_REGEXP,
  21757. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21758. 'yyyy-MM'),
  21759. /**
  21760. * @ngdoc input
  21761. * @name input[number]
  21762. *
  21763. * @description
  21764. * Text input with number validation and transformation. Sets the `number` validation
  21765. * error if not a valid number.
  21766. *
  21767. * <div class="alert alert-warning">
  21768. * The model must always be of type `number` otherwise Angular will throw an error.
  21769. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21770. * error docs for more information and an example of how to convert your model if necessary.
  21771. * </div>
  21772. *
  21773. * ## Issues with HTML5 constraint validation
  21774. *
  21775. * In browsers that follow the
  21776. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21777. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21778. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21779. * which means the view / model values in `ngModel` and subsequently the scope value
  21780. * will also be an empty string.
  21781. *
  21782. *
  21783. * @param {string} ngModel Assignable angular expression to data-bind to.
  21784. * @param {string=} name Property name of the form under which the control is published.
  21785. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21786. * Can be interpolated.
  21787. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21788. * Can be interpolated.
  21789. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  21790. * but does not trigger HTML5 native validation. Takes an expression.
  21791. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  21792. * but does not trigger HTML5 native validation. Takes an expression.
  21793. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  21794. * Can be interpolated.
  21795. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  21796. * but does not trigger HTML5 native validation. Takes an expression.
  21797. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21798. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21799. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21800. * `required` when you want to data-bind to the `required` attribute.
  21801. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21802. * minlength.
  21803. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21804. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21805. * any length.
  21806. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21807. * that contains the regular expression body that will be converted to a regular expression
  21808. * as in the ngPattern directive.
  21809. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21810. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21811. * If the expression evaluates to a RegExp object, then this is used directly.
  21812. * If the expression evaluates to a string, then it will be converted to a RegExp
  21813. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21814. * `new RegExp('^abc$')`.<br />
  21815. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21816. * start at the index of the last search's match, thus not taking the whole input value into
  21817. * account.
  21818. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21819. * interaction with the input element.
  21820. *
  21821. * @example
  21822. <example name="number-input-directive" module="numberExample">
  21823. <file name="index.html">
  21824. <script>
  21825. angular.module('numberExample', [])
  21826. .controller('ExampleController', ['$scope', function($scope) {
  21827. $scope.example = {
  21828. value: 12
  21829. };
  21830. }]);
  21831. </script>
  21832. <form name="myForm" ng-controller="ExampleController">
  21833. <label>Number:
  21834. <input type="number" name="input" ng-model="example.value"
  21835. min="0" max="99" required>
  21836. </label>
  21837. <div role="alert">
  21838. <span class="error" ng-show="myForm.input.$error.required">
  21839. Required!</span>
  21840. <span class="error" ng-show="myForm.input.$error.number">
  21841. Not valid number!</span>
  21842. </div>
  21843. <tt>value = {{example.value}}</tt><br/>
  21844. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21845. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21846. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21847. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21848. </form>
  21849. </file>
  21850. <file name="protractor.js" type="protractor">
  21851. var value = element(by.binding('example.value'));
  21852. var valid = element(by.binding('myForm.input.$valid'));
  21853. var input = element(by.model('example.value'));
  21854. it('should initialize to model', function() {
  21855. expect(value.getText()).toContain('12');
  21856. expect(valid.getText()).toContain('true');
  21857. });
  21858. it('should be invalid if empty', function() {
  21859. input.clear();
  21860. input.sendKeys('');
  21861. expect(value.getText()).toEqual('value =');
  21862. expect(valid.getText()).toContain('false');
  21863. });
  21864. it('should be invalid if over max', function() {
  21865. input.clear();
  21866. input.sendKeys('123');
  21867. expect(value.getText()).toEqual('value =');
  21868. expect(valid.getText()).toContain('false');
  21869. });
  21870. </file>
  21871. </example>
  21872. */
  21873. 'number': numberInputType,
  21874. /**
  21875. * @ngdoc input
  21876. * @name input[url]
  21877. *
  21878. * @description
  21879. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  21880. * valid URL.
  21881. *
  21882. * <div class="alert alert-warning">
  21883. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  21884. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  21885. * the built-in validators (see the {@link guide/forms Forms guide})
  21886. * </div>
  21887. *
  21888. * @param {string} ngModel Assignable angular expression to data-bind to.
  21889. * @param {string=} name Property name of the form under which the control is published.
  21890. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21891. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21892. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21893. * `required` when you want to data-bind to the `required` attribute.
  21894. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21895. * minlength.
  21896. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21897. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21898. * any length.
  21899. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21900. * that contains the regular expression body that will be converted to a regular expression
  21901. * as in the ngPattern directive.
  21902. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21903. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21904. * If the expression evaluates to a RegExp object, then this is used directly.
  21905. * If the expression evaluates to a string, then it will be converted to a RegExp
  21906. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21907. * `new RegExp('^abc$')`.<br />
  21908. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21909. * start at the index of the last search's match, thus not taking the whole input value into
  21910. * account.
  21911. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21912. * interaction with the input element.
  21913. *
  21914. * @example
  21915. <example name="url-input-directive" module="urlExample">
  21916. <file name="index.html">
  21917. <script>
  21918. angular.module('urlExample', [])
  21919. .controller('ExampleController', ['$scope', function($scope) {
  21920. $scope.url = {
  21921. text: 'http://google.com'
  21922. };
  21923. }]);
  21924. </script>
  21925. <form name="myForm" ng-controller="ExampleController">
  21926. <label>URL:
  21927. <input type="url" name="input" ng-model="url.text" required>
  21928. <label>
  21929. <div role="alert">
  21930. <span class="error" ng-show="myForm.input.$error.required">
  21931. Required!</span>
  21932. <span class="error" ng-show="myForm.input.$error.url">
  21933. Not valid url!</span>
  21934. </div>
  21935. <tt>text = {{url.text}}</tt><br/>
  21936. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21937. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21938. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21939. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21940. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  21941. </form>
  21942. </file>
  21943. <file name="protractor.js" type="protractor">
  21944. var text = element(by.binding('url.text'));
  21945. var valid = element(by.binding('myForm.input.$valid'));
  21946. var input = element(by.model('url.text'));
  21947. it('should initialize to model', function() {
  21948. expect(text.getText()).toContain('http://google.com');
  21949. expect(valid.getText()).toContain('true');
  21950. });
  21951. it('should be invalid if empty', function() {
  21952. input.clear();
  21953. input.sendKeys('');
  21954. expect(text.getText()).toEqual('text =');
  21955. expect(valid.getText()).toContain('false');
  21956. });
  21957. it('should be invalid if not url', function() {
  21958. input.clear();
  21959. input.sendKeys('box');
  21960. expect(valid.getText()).toContain('false');
  21961. });
  21962. </file>
  21963. </example>
  21964. */
  21965. 'url': urlInputType,
  21966. /**
  21967. * @ngdoc input
  21968. * @name input[email]
  21969. *
  21970. * @description
  21971. * Text input with email validation. Sets the `email` validation error key if not a valid email
  21972. * address.
  21973. *
  21974. * <div class="alert alert-warning">
  21975. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  21976. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  21977. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  21978. * </div>
  21979. *
  21980. * @param {string} ngModel Assignable angular expression to data-bind to.
  21981. * @param {string=} name Property name of the form under which the control is published.
  21982. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21983. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21984. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21985. * `required` when you want to data-bind to the `required` attribute.
  21986. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21987. * minlength.
  21988. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21989. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21990. * any length.
  21991. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21992. * that contains the regular expression body that will be converted to a regular expression
  21993. * as in the ngPattern directive.
  21994. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21995. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21996. * If the expression evaluates to a RegExp object, then this is used directly.
  21997. * If the expression evaluates to a string, then it will be converted to a RegExp
  21998. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21999. * `new RegExp('^abc$')`.<br />
  22000. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22001. * start at the index of the last search's match, thus not taking the whole input value into
  22002. * account.
  22003. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22004. * interaction with the input element.
  22005. *
  22006. * @example
  22007. <example name="email-input-directive" module="emailExample">
  22008. <file name="index.html">
  22009. <script>
  22010. angular.module('emailExample', [])
  22011. .controller('ExampleController', ['$scope', function($scope) {
  22012. $scope.email = {
  22013. text: 'me@example.com'
  22014. };
  22015. }]);
  22016. </script>
  22017. <form name="myForm" ng-controller="ExampleController">
  22018. <label>Email:
  22019. <input type="email" name="input" ng-model="email.text" required>
  22020. </label>
  22021. <div role="alert">
  22022. <span class="error" ng-show="myForm.input.$error.required">
  22023. Required!</span>
  22024. <span class="error" ng-show="myForm.input.$error.email">
  22025. Not valid email!</span>
  22026. </div>
  22027. <tt>text = {{email.text}}</tt><br/>
  22028. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22029. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22030. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22031. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22032. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22033. </form>
  22034. </file>
  22035. <file name="protractor.js" type="protractor">
  22036. var text = element(by.binding('email.text'));
  22037. var valid = element(by.binding('myForm.input.$valid'));
  22038. var input = element(by.model('email.text'));
  22039. it('should initialize to model', function() {
  22040. expect(text.getText()).toContain('me@example.com');
  22041. expect(valid.getText()).toContain('true');
  22042. });
  22043. it('should be invalid if empty', function() {
  22044. input.clear();
  22045. input.sendKeys('');
  22046. expect(text.getText()).toEqual('text =');
  22047. expect(valid.getText()).toContain('false');
  22048. });
  22049. it('should be invalid if not email', function() {
  22050. input.clear();
  22051. input.sendKeys('xxx');
  22052. expect(valid.getText()).toContain('false');
  22053. });
  22054. </file>
  22055. </example>
  22056. */
  22057. 'email': emailInputType,
  22058. /**
  22059. * @ngdoc input
  22060. * @name input[radio]
  22061. *
  22062. * @description
  22063. * HTML radio button.
  22064. *
  22065. * @param {string} ngModel Assignable angular expression to data-bind to.
  22066. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22067. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22068. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22069. * @param {string=} name Property name of the form under which the control is published.
  22070. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22071. * interaction with the input element.
  22072. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22073. * is selected. Should be used instead of the `value` attribute if you need
  22074. * a non-string `ngModel` (`boolean`, `array`, ...).
  22075. *
  22076. * @example
  22077. <example name="radio-input-directive" module="radioExample">
  22078. <file name="index.html">
  22079. <script>
  22080. angular.module('radioExample', [])
  22081. .controller('ExampleController', ['$scope', function($scope) {
  22082. $scope.color = {
  22083. name: 'blue'
  22084. };
  22085. $scope.specialValue = {
  22086. "id": "12345",
  22087. "value": "green"
  22088. };
  22089. }]);
  22090. </script>
  22091. <form name="myForm" ng-controller="ExampleController">
  22092. <label>
  22093. <input type="radio" ng-model="color.name" value="red">
  22094. Red
  22095. </label><br/>
  22096. <label>
  22097. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22098. Green
  22099. </label><br/>
  22100. <label>
  22101. <input type="radio" ng-model="color.name" value="blue">
  22102. Blue
  22103. </label><br/>
  22104. <tt>color = {{color.name | json}}</tt><br/>
  22105. </form>
  22106. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22107. </file>
  22108. <file name="protractor.js" type="protractor">
  22109. it('should change state', function() {
  22110. var inputs = element.all(by.model('color.name'));
  22111. var color = element(by.binding('color.name'));
  22112. expect(color.getText()).toContain('blue');
  22113. inputs.get(0).click();
  22114. expect(color.getText()).toContain('red');
  22115. inputs.get(1).click();
  22116. expect(color.getText()).toContain('green');
  22117. });
  22118. </file>
  22119. </example>
  22120. */
  22121. 'radio': radioInputType,
  22122. /**
  22123. * @ngdoc input
  22124. * @name input[range]
  22125. *
  22126. * @description
  22127. * Native range input with validation and transformation.
  22128. *
  22129. * The model for the range input must always be a `Number`.
  22130. *
  22131. * IE9 and other browsers that do not support the `range` type fall back
  22132. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22133. * validation and number parsing are nevertheless supported.
  22134. *
  22135. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22136. * in a way that never allows the input to hold an invalid value. That means:
  22137. * - any non-numerical value is set to `(max + min) / 2`.
  22138. * - any numerical value that is less than the current min val, or greater than the current max val
  22139. * is set to the min / max val respectively.
  22140. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22141. * is used.
  22142. *
  22143. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22144. * for more info.
  22145. *
  22146. * This has the following consequences for Angular:
  22147. *
  22148. * Since the element value should always reflect the current model value, a range input
  22149. * will set the bound ngModel expression to the value that the browser has set for the
  22150. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22151. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22152. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22153. *
  22154. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22155. * initialized. It also means a range input can never have the required error.
  22156. *
  22157. * This does not only affect changes to the model value, but also to the values of the `min`,
  22158. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22159. * the input value, Angular will also update the model value.
  22160. *
  22161. * Automatic value adjustment also means that a range input element can never have the `required`,
  22162. * `min`, or `max` errors.
  22163. *
  22164. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22165. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22166. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22167. * error on the input, and set the model to `undefined`.
  22168. *
  22169. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22170. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22171. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22172. *
  22173. * @param {string} ngModel Assignable angular expression to data-bind to.
  22174. * @param {string=} name Property name of the form under which the control is published.
  22175. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22176. * than `min`. Can be interpolated.
  22177. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22178. * Can be interpolated.
  22179. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22180. * Can be interpolated.
  22181. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22182. * to user interaction with the input element.
  22183. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22184. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22185. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22186. *
  22187. * @example
  22188. <example name="range-input-directive" module="rangeExample">
  22189. <file name="index.html">
  22190. <script>
  22191. angular.module('rangeExample', [])
  22192. .controller('ExampleController', ['$scope', function($scope) {
  22193. $scope.value = 75;
  22194. $scope.min = 10;
  22195. $scope.max = 90;
  22196. }]);
  22197. </script>
  22198. <form name="myForm" ng-controller="ExampleController">
  22199. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22200. <hr>
  22201. Model as number: <input type="number" ng-model="value"><br>
  22202. Min: <input type="number" ng-model="min"><br>
  22203. Max: <input type="number" ng-model="max"><br>
  22204. value = <code>{{value}}</code><br/>
  22205. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22206. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22207. </form>
  22208. </file>
  22209. </example>
  22210. * ## Range Input with ngMin & ngMax attributes
  22211. * @example
  22212. <example name="range-input-directive-ng" module="rangeExample">
  22213. <file name="index.html">
  22214. <script>
  22215. angular.module('rangeExample', [])
  22216. .controller('ExampleController', ['$scope', function($scope) {
  22217. $scope.value = 75;
  22218. $scope.min = 10;
  22219. $scope.max = 90;
  22220. }]);
  22221. </script>
  22222. <form name="myForm" ng-controller="ExampleController">
  22223. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22224. <hr>
  22225. Model as number: <input type="number" ng-model="value"><br>
  22226. Min: <input type="number" ng-model="min"><br>
  22227. Max: <input type="number" ng-model="max"><br>
  22228. value = <code>{{value}}</code><br/>
  22229. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22230. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22231. </form>
  22232. </file>
  22233. </example>
  22234. */
  22235. 'range': rangeInputType,
  22236. /**
  22237. * @ngdoc input
  22238. * @name input[checkbox]
  22239. *
  22240. * @description
  22241. * HTML checkbox.
  22242. *
  22243. * @param {string} ngModel Assignable angular expression to data-bind to.
  22244. * @param {string=} name Property name of the form under which the control is published.
  22245. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22246. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22247. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22248. * interaction with the input element.
  22249. *
  22250. * @example
  22251. <example name="checkbox-input-directive" module="checkboxExample">
  22252. <file name="index.html">
  22253. <script>
  22254. angular.module('checkboxExample', [])
  22255. .controller('ExampleController', ['$scope', function($scope) {
  22256. $scope.checkboxModel = {
  22257. value1 : true,
  22258. value2 : 'YES'
  22259. };
  22260. }]);
  22261. </script>
  22262. <form name="myForm" ng-controller="ExampleController">
  22263. <label>Value1:
  22264. <input type="checkbox" ng-model="checkboxModel.value1">
  22265. </label><br/>
  22266. <label>Value2:
  22267. <input type="checkbox" ng-model="checkboxModel.value2"
  22268. ng-true-value="'YES'" ng-false-value="'NO'">
  22269. </label><br/>
  22270. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22271. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22272. </form>
  22273. </file>
  22274. <file name="protractor.js" type="protractor">
  22275. it('should change state', function() {
  22276. var value1 = element(by.binding('checkboxModel.value1'));
  22277. var value2 = element(by.binding('checkboxModel.value2'));
  22278. expect(value1.getText()).toContain('true');
  22279. expect(value2.getText()).toContain('YES');
  22280. element(by.model('checkboxModel.value1')).click();
  22281. element(by.model('checkboxModel.value2')).click();
  22282. expect(value1.getText()).toContain('false');
  22283. expect(value2.getText()).toContain('NO');
  22284. });
  22285. </file>
  22286. </example>
  22287. */
  22288. 'checkbox': checkboxInputType,
  22289. 'hidden': noop,
  22290. 'button': noop,
  22291. 'submit': noop,
  22292. 'reset': noop,
  22293. 'file': noop
  22294. };
  22295. function stringBasedInputType(ctrl) {
  22296. ctrl.$formatters.push(function(value) {
  22297. return ctrl.$isEmpty(value) ? value : value.toString();
  22298. });
  22299. }
  22300. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22301. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22302. stringBasedInputType(ctrl);
  22303. }
  22304. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22305. var type = lowercase(element[0].type);
  22306. // In composition mode, users are still inputting intermediate text buffer,
  22307. // hold the listener until composition is done.
  22308. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22309. if (!$sniffer.android) {
  22310. var composing = false;
  22311. element.on('compositionstart', function() {
  22312. composing = true;
  22313. });
  22314. element.on('compositionend', function() {
  22315. composing = false;
  22316. listener();
  22317. });
  22318. }
  22319. var timeout;
  22320. var listener = function(ev) {
  22321. if (timeout) {
  22322. $browser.defer.cancel(timeout);
  22323. timeout = null;
  22324. }
  22325. if (composing) return;
  22326. var value = element.val(),
  22327. event = ev && ev.type;
  22328. // By default we will trim the value
  22329. // If the attribute ng-trim exists we will avoid trimming
  22330. // If input type is 'password', the value is never trimmed
  22331. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22332. value = trim(value);
  22333. }
  22334. // If a control is suffering from bad input (due to native validators), browsers discard its
  22335. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22336. // control's value is the same empty value twice in a row.
  22337. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22338. ctrl.$setViewValue(value, event);
  22339. }
  22340. };
  22341. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22342. // input event on backspace, delete or cut
  22343. if ($sniffer.hasEvent('input')) {
  22344. element.on('input', listener);
  22345. } else {
  22346. var deferListener = function(ev, input, origValue) {
  22347. if (!timeout) {
  22348. timeout = $browser.defer(function() {
  22349. timeout = null;
  22350. if (!input || input.value !== origValue) {
  22351. listener(ev);
  22352. }
  22353. });
  22354. }
  22355. };
  22356. element.on('keydown', /** @this */ function(event) {
  22357. var key = event.keyCode;
  22358. // ignore
  22359. // command modifiers arrows
  22360. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22361. deferListener(event, this, this.value);
  22362. });
  22363. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22364. if ($sniffer.hasEvent('paste')) {
  22365. element.on('paste cut', deferListener);
  22366. }
  22367. }
  22368. // if user paste into input using mouse on older browser
  22369. // or form autocomplete on newer browser, we need "change" event to catch it
  22370. element.on('change', listener);
  22371. // Some native input types (date-family) have the ability to change validity without
  22372. // firing any input/change events.
  22373. // For these event types, when native validators are present and the browser supports the type,
  22374. // check for validity changes on various DOM events.
  22375. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22376. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22377. if (!timeout) {
  22378. var validity = this[VALIDITY_STATE_PROPERTY];
  22379. var origBadInput = validity.badInput;
  22380. var origTypeMismatch = validity.typeMismatch;
  22381. timeout = $browser.defer(function() {
  22382. timeout = null;
  22383. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22384. listener(ev);
  22385. }
  22386. });
  22387. }
  22388. });
  22389. }
  22390. ctrl.$render = function() {
  22391. // Workaround for Firefox validation #12102.
  22392. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22393. if (element.val() !== value) {
  22394. element.val(value);
  22395. }
  22396. };
  22397. }
  22398. function weekParser(isoWeek, existingDate) {
  22399. if (isDate(isoWeek)) {
  22400. return isoWeek;
  22401. }
  22402. if (isString(isoWeek)) {
  22403. WEEK_REGEXP.lastIndex = 0;
  22404. var parts = WEEK_REGEXP.exec(isoWeek);
  22405. if (parts) {
  22406. var year = +parts[1],
  22407. week = +parts[2],
  22408. hours = 0,
  22409. minutes = 0,
  22410. seconds = 0,
  22411. milliseconds = 0,
  22412. firstThurs = getFirstThursdayOfYear(year),
  22413. addDays = (week - 1) * 7;
  22414. if (existingDate) {
  22415. hours = existingDate.getHours();
  22416. minutes = existingDate.getMinutes();
  22417. seconds = existingDate.getSeconds();
  22418. milliseconds = existingDate.getMilliseconds();
  22419. }
  22420. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22421. }
  22422. }
  22423. return NaN;
  22424. }
  22425. function createDateParser(regexp, mapping) {
  22426. return function(iso, date) {
  22427. var parts, map;
  22428. if (isDate(iso)) {
  22429. return iso;
  22430. }
  22431. if (isString(iso)) {
  22432. // When a date is JSON'ified to wraps itself inside of an extra
  22433. // set of double quotes. This makes the date parsing code unable
  22434. // to match the date string and parse it as a date.
  22435. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22436. iso = iso.substring(1, iso.length - 1);
  22437. }
  22438. if (ISO_DATE_REGEXP.test(iso)) {
  22439. return new Date(iso);
  22440. }
  22441. regexp.lastIndex = 0;
  22442. parts = regexp.exec(iso);
  22443. if (parts) {
  22444. parts.shift();
  22445. if (date) {
  22446. map = {
  22447. yyyy: date.getFullYear(),
  22448. MM: date.getMonth() + 1,
  22449. dd: date.getDate(),
  22450. HH: date.getHours(),
  22451. mm: date.getMinutes(),
  22452. ss: date.getSeconds(),
  22453. sss: date.getMilliseconds() / 1000
  22454. };
  22455. } else {
  22456. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22457. }
  22458. forEach(parts, function(part, index) {
  22459. if (index < mapping.length) {
  22460. map[mapping[index]] = +part;
  22461. }
  22462. });
  22463. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  22464. }
  22465. }
  22466. return NaN;
  22467. };
  22468. }
  22469. function createDateInputType(type, regexp, parseDate, format) {
  22470. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  22471. badInputChecker(scope, element, attr, ctrl);
  22472. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22473. var timezone = ctrl && ctrl.$options.getOption('timezone');
  22474. var previousDate;
  22475. ctrl.$$parserName = type;
  22476. ctrl.$parsers.push(function(value) {
  22477. if (ctrl.$isEmpty(value)) return null;
  22478. if (regexp.test(value)) {
  22479. // Note: We cannot read ctrl.$modelValue, as there might be a different
  22480. // parser/formatter in the processing chain so that the model
  22481. // contains some different data format!
  22482. var parsedDate = parseDate(value, previousDate);
  22483. if (timezone) {
  22484. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  22485. }
  22486. return parsedDate;
  22487. }
  22488. return undefined;
  22489. });
  22490. ctrl.$formatters.push(function(value) {
  22491. if (value && !isDate(value)) {
  22492. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  22493. }
  22494. if (isValidDate(value)) {
  22495. previousDate = value;
  22496. if (previousDate && timezone) {
  22497. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  22498. }
  22499. return $filter('date')(value, format, timezone);
  22500. } else {
  22501. previousDate = null;
  22502. return '';
  22503. }
  22504. });
  22505. if (isDefined(attr.min) || attr.ngMin) {
  22506. var minVal;
  22507. ctrl.$validators.min = function(value) {
  22508. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  22509. };
  22510. attr.$observe('min', function(val) {
  22511. minVal = parseObservedDateValue(val);
  22512. ctrl.$validate();
  22513. });
  22514. }
  22515. if (isDefined(attr.max) || attr.ngMax) {
  22516. var maxVal;
  22517. ctrl.$validators.max = function(value) {
  22518. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22519. };
  22520. attr.$observe('max', function(val) {
  22521. maxVal = parseObservedDateValue(val);
  22522. ctrl.$validate();
  22523. });
  22524. }
  22525. function isValidDate(value) {
  22526. // Invalid Date: getTime() returns NaN
  22527. return value && !(value.getTime && value.getTime() !== value.getTime());
  22528. }
  22529. function parseObservedDateValue(val) {
  22530. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22531. }
  22532. };
  22533. }
  22534. function badInputChecker(scope, element, attr, ctrl) {
  22535. var node = element[0];
  22536. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22537. if (nativeValidation) {
  22538. ctrl.$parsers.push(function(value) {
  22539. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22540. return validity.badInput || validity.typeMismatch ? undefined : value;
  22541. });
  22542. }
  22543. }
  22544. function numberFormatterParser(ctrl) {
  22545. ctrl.$$parserName = 'number';
  22546. ctrl.$parsers.push(function(value) {
  22547. if (ctrl.$isEmpty(value)) return null;
  22548. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22549. return undefined;
  22550. });
  22551. ctrl.$formatters.push(function(value) {
  22552. if (!ctrl.$isEmpty(value)) {
  22553. if (!isNumber(value)) {
  22554. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22555. }
  22556. value = value.toString();
  22557. }
  22558. return value;
  22559. });
  22560. }
  22561. function parseNumberAttrVal(val) {
  22562. if (isDefined(val) && !isNumber(val)) {
  22563. val = parseFloat(val);
  22564. }
  22565. return !isNumberNaN(val) ? val : undefined;
  22566. }
  22567. function isNumberInteger(num) {
  22568. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  22569. // (minus the assumption that `num` is a number)
  22570. // eslint-disable-next-line no-bitwise
  22571. return (num | 0) === num;
  22572. }
  22573. function countDecimals(num) {
  22574. var numString = num.toString();
  22575. var decimalSymbolIndex = numString.indexOf('.');
  22576. if (decimalSymbolIndex === -1) {
  22577. if (-1 < num && num < 1) {
  22578. // It may be in the exponential notation format (`1e-X`)
  22579. var match = /e-(\d+)$/.exec(numString);
  22580. if (match) {
  22581. return Number(match[1]);
  22582. }
  22583. }
  22584. return 0;
  22585. }
  22586. return numString.length - decimalSymbolIndex - 1;
  22587. }
  22588. function isValidForStep(viewValue, stepBase, step) {
  22589. // At this point `stepBase` and `step` are expected to be non-NaN values
  22590. // and `viewValue` is expected to be a valid stringified number.
  22591. var value = Number(viewValue);
  22592. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  22593. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  22594. if (!isNumberInteger(value) || !isNumberInteger(stepBase) || !isNumberInteger(step)) {
  22595. var decimalCount = Math.max(countDecimals(value), countDecimals(stepBase), countDecimals(step));
  22596. var multiplier = Math.pow(10, decimalCount);
  22597. value = value * multiplier;
  22598. stepBase = stepBase * multiplier;
  22599. step = step * multiplier;
  22600. }
  22601. return (value - stepBase) % step === 0;
  22602. }
  22603. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22604. badInputChecker(scope, element, attr, ctrl);
  22605. numberFormatterParser(ctrl);
  22606. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22607. var minVal;
  22608. var maxVal;
  22609. if (isDefined(attr.min) || attr.ngMin) {
  22610. ctrl.$validators.min = function(value) {
  22611. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22612. };
  22613. attr.$observe('min', function(val) {
  22614. minVal = parseNumberAttrVal(val);
  22615. // TODO(matsko): implement validateLater to reduce number of validations
  22616. ctrl.$validate();
  22617. });
  22618. }
  22619. if (isDefined(attr.max) || attr.ngMax) {
  22620. ctrl.$validators.max = function(value) {
  22621. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22622. };
  22623. attr.$observe('max', function(val) {
  22624. maxVal = parseNumberAttrVal(val);
  22625. // TODO(matsko): implement validateLater to reduce number of validations
  22626. ctrl.$validate();
  22627. });
  22628. }
  22629. if (isDefined(attr.step) || attr.ngStep) {
  22630. var stepVal;
  22631. ctrl.$validators.step = function(modelValue, viewValue) {
  22632. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22633. isValidForStep(viewValue, minVal || 0, stepVal);
  22634. };
  22635. attr.$observe('step', function(val) {
  22636. stepVal = parseNumberAttrVal(val);
  22637. // TODO(matsko): implement validateLater to reduce number of validations
  22638. ctrl.$validate();
  22639. });
  22640. }
  22641. }
  22642. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22643. badInputChecker(scope, element, attr, ctrl);
  22644. numberFormatterParser(ctrl);
  22645. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22646. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  22647. minVal = supportsRange ? 0 : undefined,
  22648. maxVal = supportsRange ? 100 : undefined,
  22649. stepVal = supportsRange ? 1 : undefined,
  22650. validity = element[0].validity,
  22651. hasMinAttr = isDefined(attr.min),
  22652. hasMaxAttr = isDefined(attr.max),
  22653. hasStepAttr = isDefined(attr.step);
  22654. var originalRender = ctrl.$render;
  22655. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  22656. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  22657. //$render would cause the min / max validators to be applied with the wrong value
  22658. function rangeRender() {
  22659. originalRender();
  22660. ctrl.$setViewValue(element.val());
  22661. } :
  22662. originalRender;
  22663. if (hasMinAttr) {
  22664. ctrl.$validators.min = supportsRange ?
  22665. // Since all browsers set the input to a valid value, we don't need to check validity
  22666. function noopMinValidator() { return true; } :
  22667. // non-support browsers validate the min val
  22668. function minValidator(modelValue, viewValue) {
  22669. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  22670. };
  22671. setInitialValueAndObserver('min', minChange);
  22672. }
  22673. if (hasMaxAttr) {
  22674. ctrl.$validators.max = supportsRange ?
  22675. // Since all browsers set the input to a valid value, we don't need to check validity
  22676. function noopMaxValidator() { return true; } :
  22677. // non-support browsers validate the max val
  22678. function maxValidator(modelValue, viewValue) {
  22679. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  22680. };
  22681. setInitialValueAndObserver('max', maxChange);
  22682. }
  22683. if (hasStepAttr) {
  22684. ctrl.$validators.step = supportsRange ?
  22685. function nativeStepValidator() {
  22686. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  22687. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  22688. // validity error instead, so we can at least report an error in that case.
  22689. return !validity.stepMismatch;
  22690. } :
  22691. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  22692. function stepValidator(modelValue, viewValue) {
  22693. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22694. isValidForStep(viewValue, minVal || 0, stepVal);
  22695. };
  22696. setInitialValueAndObserver('step', stepChange);
  22697. }
  22698. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  22699. // interpolated attributes set the attribute value only after a digest, but we need the
  22700. // attribute value when the input is first rendered, so that the browser can adjust the
  22701. // input value based on the min/max value
  22702. element.attr(htmlAttrName, attr[htmlAttrName]);
  22703. attr.$observe(htmlAttrName, changeFn);
  22704. }
  22705. function minChange(val) {
  22706. minVal = parseNumberAttrVal(val);
  22707. // ignore changes before model is initialized
  22708. if (isNumberNaN(ctrl.$modelValue)) {
  22709. return;
  22710. }
  22711. if (supportsRange) {
  22712. var elVal = element.val();
  22713. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  22714. if (minVal > elVal) {
  22715. elVal = minVal;
  22716. element.val(elVal);
  22717. }
  22718. ctrl.$setViewValue(elVal);
  22719. } else {
  22720. // TODO(matsko): implement validateLater to reduce number of validations
  22721. ctrl.$validate();
  22722. }
  22723. }
  22724. function maxChange(val) {
  22725. maxVal = parseNumberAttrVal(val);
  22726. // ignore changes before model is initialized
  22727. if (isNumberNaN(ctrl.$modelValue)) {
  22728. return;
  22729. }
  22730. if (supportsRange) {
  22731. var elVal = element.val();
  22732. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  22733. if (maxVal < elVal) {
  22734. element.val(maxVal);
  22735. // IE11 and Chrome don't set the value to the minVal when max < min
  22736. elVal = maxVal < minVal ? minVal : maxVal;
  22737. }
  22738. ctrl.$setViewValue(elVal);
  22739. } else {
  22740. // TODO(matsko): implement validateLater to reduce number of validations
  22741. ctrl.$validate();
  22742. }
  22743. }
  22744. function stepChange(val) {
  22745. stepVal = parseNumberAttrVal(val);
  22746. // ignore changes before model is initialized
  22747. if (isNumberNaN(ctrl.$modelValue)) {
  22748. return;
  22749. }
  22750. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  22751. if (supportsRange && ctrl.$viewValue !== element.val()) {
  22752. ctrl.$setViewValue(element.val());
  22753. } else {
  22754. // TODO(matsko): implement validateLater to reduce number of validations
  22755. ctrl.$validate();
  22756. }
  22757. }
  22758. }
  22759. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22760. // Note: no badInputChecker here by purpose as `url` is only a validation
  22761. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22762. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22763. stringBasedInputType(ctrl);
  22764. ctrl.$$parserName = 'url';
  22765. ctrl.$validators.url = function(modelValue, viewValue) {
  22766. var value = modelValue || viewValue;
  22767. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  22768. };
  22769. }
  22770. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22771. // Note: no badInputChecker here by purpose as `url` is only a validation
  22772. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22773. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22774. stringBasedInputType(ctrl);
  22775. ctrl.$$parserName = 'email';
  22776. ctrl.$validators.email = function(modelValue, viewValue) {
  22777. var value = modelValue || viewValue;
  22778. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  22779. };
  22780. }
  22781. function radioInputType(scope, element, attr, ctrl) {
  22782. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  22783. // make the name unique, if not defined
  22784. if (isUndefined(attr.name)) {
  22785. element.attr('name', nextUid());
  22786. }
  22787. var listener = function(ev) {
  22788. var value;
  22789. if (element[0].checked) {
  22790. value = attr.value;
  22791. if (doTrim) {
  22792. value = trim(value);
  22793. }
  22794. ctrl.$setViewValue(value, ev && ev.type);
  22795. }
  22796. };
  22797. element.on('click', listener);
  22798. ctrl.$render = function() {
  22799. var value = attr.value;
  22800. if (doTrim) {
  22801. value = trim(value);
  22802. }
  22803. element[0].checked = (value === ctrl.$viewValue);
  22804. };
  22805. attr.$observe('value', ctrl.$render);
  22806. }
  22807. function parseConstantExpr($parse, context, name, expression, fallback) {
  22808. var parseFn;
  22809. if (isDefined(expression)) {
  22810. parseFn = $parse(expression);
  22811. if (!parseFn.constant) {
  22812. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  22813. '`{1}`.', name, expression);
  22814. }
  22815. return parseFn(context);
  22816. }
  22817. return fallback;
  22818. }
  22819. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  22820. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  22821. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  22822. var listener = function(ev) {
  22823. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  22824. };
  22825. element.on('click', listener);
  22826. ctrl.$render = function() {
  22827. element[0].checked = ctrl.$viewValue;
  22828. };
  22829. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  22830. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  22831. // it to a boolean.
  22832. ctrl.$isEmpty = function(value) {
  22833. return value === false;
  22834. };
  22835. ctrl.$formatters.push(function(value) {
  22836. return equals(value, trueValue);
  22837. });
  22838. ctrl.$parsers.push(function(value) {
  22839. return value ? trueValue : falseValue;
  22840. });
  22841. }
  22842. /**
  22843. * @ngdoc directive
  22844. * @name textarea
  22845. * @restrict E
  22846. *
  22847. * @description
  22848. * HTML textarea element control with angular data-binding. The data-binding and validation
  22849. * properties of this element are exactly the same as those of the
  22850. * {@link ng.directive:input input element}.
  22851. *
  22852. * @param {string} ngModel Assignable angular expression to data-bind to.
  22853. * @param {string=} name Property name of the form under which the control is published.
  22854. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22855. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22856. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22857. * `required` when you want to data-bind to the `required` attribute.
  22858. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22859. * minlength.
  22860. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22861. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22862. * length.
  22863. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22864. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22865. * If the expression evaluates to a RegExp object, then this is used directly.
  22866. * If the expression evaluates to a string, then it will be converted to a RegExp
  22867. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22868. * `new RegExp('^abc$')`.<br />
  22869. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22870. * start at the index of the last search's match, thus not taking the whole input value into
  22871. * account.
  22872. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22873. * interaction with the input element.
  22874. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22875. *
  22876. * @knownIssue
  22877. *
  22878. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  22879. * insert the placeholder value as the textarea's content. If the placeholder value contains
  22880. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  22881. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  22882. * textarea, but can be undesirable.
  22883. *
  22884. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  22885. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  22886. * find more details on `ngAttr` in the
  22887. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  22888. * Developer Guide.
  22889. */
  22890. /**
  22891. * @ngdoc directive
  22892. * @name input
  22893. * @restrict E
  22894. *
  22895. * @description
  22896. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  22897. * input state control, and validation.
  22898. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  22899. *
  22900. * <div class="alert alert-warning">
  22901. * **Note:** Not every feature offered is available for all input types.
  22902. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  22903. * </div>
  22904. *
  22905. * @param {string} ngModel Assignable angular expression to data-bind to.
  22906. * @param {string=} name Property name of the form under which the control is published.
  22907. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22908. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  22909. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22910. * minlength.
  22911. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22912. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22913. * length.
  22914. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22915. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22916. * If the expression evaluates to a RegExp object, then this is used directly.
  22917. * If the expression evaluates to a string, then it will be converted to a RegExp
  22918. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22919. * `new RegExp('^abc$')`.<br />
  22920. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22921. * start at the index of the last search's match, thus not taking the whole input value into
  22922. * account.
  22923. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22924. * interaction with the input element.
  22925. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22926. * This parameter is ignored for input[type=password] controls, which will never trim the
  22927. * input.
  22928. *
  22929. * @example
  22930. <example name="input-directive" module="inputExample">
  22931. <file name="index.html">
  22932. <script>
  22933. angular.module('inputExample', [])
  22934. .controller('ExampleController', ['$scope', function($scope) {
  22935. $scope.user = {name: 'guest', last: 'visitor'};
  22936. }]);
  22937. </script>
  22938. <div ng-controller="ExampleController">
  22939. <form name="myForm">
  22940. <label>
  22941. User name:
  22942. <input type="text" name="userName" ng-model="user.name" required>
  22943. </label>
  22944. <div role="alert">
  22945. <span class="error" ng-show="myForm.userName.$error.required">
  22946. Required!</span>
  22947. </div>
  22948. <label>
  22949. Last name:
  22950. <input type="text" name="lastName" ng-model="user.last"
  22951. ng-minlength="3" ng-maxlength="10">
  22952. </label>
  22953. <div role="alert">
  22954. <span class="error" ng-show="myForm.lastName.$error.minlength">
  22955. Too short!</span>
  22956. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  22957. Too long!</span>
  22958. </div>
  22959. </form>
  22960. <hr>
  22961. <tt>user = {{user}}</tt><br/>
  22962. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  22963. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  22964. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  22965. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  22966. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22967. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22968. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  22969. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  22970. </div>
  22971. </file>
  22972. <file name="protractor.js" type="protractor">
  22973. var user = element(by.exactBinding('user'));
  22974. var userNameValid = element(by.binding('myForm.userName.$valid'));
  22975. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  22976. var lastNameError = element(by.binding('myForm.lastName.$error'));
  22977. var formValid = element(by.binding('myForm.$valid'));
  22978. var userNameInput = element(by.model('user.name'));
  22979. var userLastInput = element(by.model('user.last'));
  22980. it('should initialize to model', function() {
  22981. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  22982. expect(userNameValid.getText()).toContain('true');
  22983. expect(formValid.getText()).toContain('true');
  22984. });
  22985. it('should be invalid if empty when required', function() {
  22986. userNameInput.clear();
  22987. userNameInput.sendKeys('');
  22988. expect(user.getText()).toContain('{"last":"visitor"}');
  22989. expect(userNameValid.getText()).toContain('false');
  22990. expect(formValid.getText()).toContain('false');
  22991. });
  22992. it('should be valid if empty when min length is set', function() {
  22993. userLastInput.clear();
  22994. userLastInput.sendKeys('');
  22995. expect(user.getText()).toContain('{"name":"guest","last":""}');
  22996. expect(lastNameValid.getText()).toContain('true');
  22997. expect(formValid.getText()).toContain('true');
  22998. });
  22999. it('should be invalid if less than required min length', function() {
  23000. userLastInput.clear();
  23001. userLastInput.sendKeys('xx');
  23002. expect(user.getText()).toContain('{"name":"guest"}');
  23003. expect(lastNameValid.getText()).toContain('false');
  23004. expect(lastNameError.getText()).toContain('minlength');
  23005. expect(formValid.getText()).toContain('false');
  23006. });
  23007. it('should be invalid if longer than max length', function() {
  23008. userLastInput.clear();
  23009. userLastInput.sendKeys('some ridiculously long name');
  23010. expect(user.getText()).toContain('{"name":"guest"}');
  23011. expect(lastNameValid.getText()).toContain('false');
  23012. expect(lastNameError.getText()).toContain('maxlength');
  23013. expect(formValid.getText()).toContain('false');
  23014. });
  23015. </file>
  23016. </example>
  23017. */
  23018. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23019. function($browser, $sniffer, $filter, $parse) {
  23020. return {
  23021. restrict: 'E',
  23022. require: ['?ngModel'],
  23023. link: {
  23024. pre: function(scope, element, attr, ctrls) {
  23025. if (ctrls[0]) {
  23026. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23027. $browser, $filter, $parse);
  23028. }
  23029. }
  23030. }
  23031. };
  23032. }];
  23033. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23034. /**
  23035. * @ngdoc directive
  23036. * @name ngValue
  23037. *
  23038. * @description
  23039. * Binds the given expression to the value of the element.
  23040. *
  23041. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23042. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23043. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23044. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23045. *
  23046. * It can also be used to achieve one-way binding of a given expression to an input element
  23047. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23048. *
  23049. * @element input
  23050. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  23051. * and `value` property of the element.
  23052. *
  23053. * @example
  23054. <example name="ngValue-directive" module="valueExample">
  23055. <file name="index.html">
  23056. <script>
  23057. angular.module('valueExample', [])
  23058. .controller('ExampleController', ['$scope', function($scope) {
  23059. $scope.names = ['pizza', 'unicorns', 'robots'];
  23060. $scope.my = { favorite: 'unicorns' };
  23061. }]);
  23062. </script>
  23063. <form ng-controller="ExampleController">
  23064. <h2>Which is your favorite?</h2>
  23065. <label ng-repeat="name in names" for="{{name}}">
  23066. {{name}}
  23067. <input type="radio"
  23068. ng-model="my.favorite"
  23069. ng-value="name"
  23070. id="{{name}}"
  23071. name="favorite">
  23072. </label>
  23073. <div>You chose {{my.favorite}}</div>
  23074. </form>
  23075. </file>
  23076. <file name="protractor.js" type="protractor">
  23077. var favorite = element(by.binding('my.favorite'));
  23078. it('should initialize to model', function() {
  23079. expect(favorite.getText()).toContain('unicorns');
  23080. });
  23081. it('should bind the values to the inputs', function() {
  23082. element.all(by.model('my.favorite')).get(0).click();
  23083. expect(favorite.getText()).toContain('pizza');
  23084. });
  23085. </file>
  23086. </example>
  23087. */
  23088. var ngValueDirective = function() {
  23089. /**
  23090. * inputs use the value attribute as their default value if the value property is not set.
  23091. * Once the value property has been set (by adding input), it will not react to changes to
  23092. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23093. * makes it possible to use ngValue as a sort of one-way bind.
  23094. */
  23095. function updateElementValue(element, attr, value) {
  23096. element.prop('value', value);
  23097. attr.$set('value', value);
  23098. }
  23099. return {
  23100. restrict: 'A',
  23101. priority: 100,
  23102. compile: function(tpl, tplAttr) {
  23103. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23104. return function ngValueConstantLink(scope, elm, attr) {
  23105. var value = scope.$eval(attr.ngValue);
  23106. updateElementValue(elm, attr, value);
  23107. };
  23108. } else {
  23109. return function ngValueLink(scope, elm, attr) {
  23110. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23111. updateElementValue(elm, attr, value);
  23112. });
  23113. };
  23114. }
  23115. }
  23116. };
  23117. };
  23118. /**
  23119. * @ngdoc directive
  23120. * @name ngBind
  23121. * @restrict AC
  23122. *
  23123. * @description
  23124. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23125. * with the value of a given expression, and to update the text content when the value of that
  23126. * expression changes.
  23127. *
  23128. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23129. * `{{ expression }}` which is similar but less verbose.
  23130. *
  23131. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23132. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23133. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23134. *
  23135. * An alternative solution to this problem would be using the
  23136. * {@link ng.directive:ngCloak ngCloak} directive.
  23137. *
  23138. *
  23139. * @element ANY
  23140. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23141. *
  23142. * @example
  23143. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23144. <example module="bindExample" name="ng-bind">
  23145. <file name="index.html">
  23146. <script>
  23147. angular.module('bindExample', [])
  23148. .controller('ExampleController', ['$scope', function($scope) {
  23149. $scope.name = 'Whirled';
  23150. }]);
  23151. </script>
  23152. <div ng-controller="ExampleController">
  23153. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23154. Hello <span ng-bind="name"></span>!
  23155. </div>
  23156. </file>
  23157. <file name="protractor.js" type="protractor">
  23158. it('should check ng-bind', function() {
  23159. var nameInput = element(by.model('name'));
  23160. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23161. nameInput.clear();
  23162. nameInput.sendKeys('world');
  23163. expect(element(by.binding('name')).getText()).toBe('world');
  23164. });
  23165. </file>
  23166. </example>
  23167. */
  23168. var ngBindDirective = ['$compile', function($compile) {
  23169. return {
  23170. restrict: 'AC',
  23171. compile: function ngBindCompile(templateElement) {
  23172. $compile.$$addBindingClass(templateElement);
  23173. return function ngBindLink(scope, element, attr) {
  23174. $compile.$$addBindingInfo(element, attr.ngBind);
  23175. element = element[0];
  23176. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23177. element.textContent = stringify(value);
  23178. });
  23179. };
  23180. }
  23181. };
  23182. }];
  23183. /**
  23184. * @ngdoc directive
  23185. * @name ngBindTemplate
  23186. *
  23187. * @description
  23188. * The `ngBindTemplate` directive specifies that the element
  23189. * text content should be replaced with the interpolation of the template
  23190. * in the `ngBindTemplate` attribute.
  23191. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23192. * expressions. This directive is needed since some HTML elements
  23193. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23194. *
  23195. * @element ANY
  23196. * @param {string} ngBindTemplate template of form
  23197. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23198. *
  23199. * @example
  23200. * Try it here: enter text in text box and watch the greeting change.
  23201. <example module="bindExample" name="ng-bind-template">
  23202. <file name="index.html">
  23203. <script>
  23204. angular.module('bindExample', [])
  23205. .controller('ExampleController', ['$scope', function($scope) {
  23206. $scope.salutation = 'Hello';
  23207. $scope.name = 'World';
  23208. }]);
  23209. </script>
  23210. <div ng-controller="ExampleController">
  23211. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23212. <label>Name: <input type="text" ng-model="name"></label><br>
  23213. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23214. </div>
  23215. </file>
  23216. <file name="protractor.js" type="protractor">
  23217. it('should check ng-bind', function() {
  23218. var salutationElem = element(by.binding('salutation'));
  23219. var salutationInput = element(by.model('salutation'));
  23220. var nameInput = element(by.model('name'));
  23221. expect(salutationElem.getText()).toBe('Hello World!');
  23222. salutationInput.clear();
  23223. salutationInput.sendKeys('Greetings');
  23224. nameInput.clear();
  23225. nameInput.sendKeys('user');
  23226. expect(salutationElem.getText()).toBe('Greetings user!');
  23227. });
  23228. </file>
  23229. </example>
  23230. */
  23231. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23232. return {
  23233. compile: function ngBindTemplateCompile(templateElement) {
  23234. $compile.$$addBindingClass(templateElement);
  23235. return function ngBindTemplateLink(scope, element, attr) {
  23236. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23237. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23238. element = element[0];
  23239. attr.$observe('ngBindTemplate', function(value) {
  23240. element.textContent = isUndefined(value) ? '' : value;
  23241. });
  23242. };
  23243. }
  23244. };
  23245. }];
  23246. /**
  23247. * @ngdoc directive
  23248. * @name ngBindHtml
  23249. *
  23250. * @description
  23251. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23252. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23253. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23254. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23255. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23256. *
  23257. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23258. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23259. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23260. *
  23261. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23262. * will have an exception (instead of an exploit.)
  23263. *
  23264. * @element ANY
  23265. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23266. *
  23267. * @example
  23268. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23269. <file name="index.html">
  23270. <div ng-controller="ExampleController">
  23271. <p ng-bind-html="myHTML"></p>
  23272. </div>
  23273. </file>
  23274. <file name="script.js">
  23275. angular.module('bindHtmlExample', ['ngSanitize'])
  23276. .controller('ExampleController', ['$scope', function($scope) {
  23277. $scope.myHTML =
  23278. 'I am an <code>HTML</code>string with ' +
  23279. '<a href="#">links!</a> and other <em>stuff</em>';
  23280. }]);
  23281. </file>
  23282. <file name="protractor.js" type="protractor">
  23283. it('should check ng-bind-html', function() {
  23284. expect(element(by.binding('myHTML')).getText()).toBe(
  23285. 'I am an HTMLstring with links! and other stuff');
  23286. });
  23287. </file>
  23288. </example>
  23289. */
  23290. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23291. return {
  23292. restrict: 'A',
  23293. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23294. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23295. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23296. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23297. return $sce.valueOf(val);
  23298. });
  23299. $compile.$$addBindingClass(tElement);
  23300. return function ngBindHtmlLink(scope, element, attr) {
  23301. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23302. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23303. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23304. var value = ngBindHtmlGetter(scope);
  23305. element.html($sce.getTrustedHtml(value) || '');
  23306. });
  23307. };
  23308. }
  23309. };
  23310. }];
  23311. /**
  23312. * @ngdoc directive
  23313. * @name ngChange
  23314. *
  23315. * @description
  23316. * Evaluate the given expression when the user changes the input.
  23317. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23318. * which only triggers at the end of a change (usually, when the user leaves the
  23319. * form element or presses the return key).
  23320. *
  23321. * The `ngChange` expression is only evaluated when a change in the input value causes
  23322. * a new value to be committed to the model.
  23323. *
  23324. * It will not be evaluated:
  23325. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23326. * * if the input has continued to be invalid since the model will stay `null`
  23327. * * if the model is changed programmatically and not by a change to the input value
  23328. *
  23329. *
  23330. * Note, this directive requires `ngModel` to be present.
  23331. *
  23332. * @element input
  23333. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23334. * in input value.
  23335. *
  23336. * @example
  23337. * <example name="ngChange-directive" module="changeExample">
  23338. * <file name="index.html">
  23339. * <script>
  23340. * angular.module('changeExample', [])
  23341. * .controller('ExampleController', ['$scope', function($scope) {
  23342. * $scope.counter = 0;
  23343. * $scope.change = function() {
  23344. * $scope.counter++;
  23345. * };
  23346. * }]);
  23347. * </script>
  23348. * <div ng-controller="ExampleController">
  23349. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23350. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23351. * <label for="ng-change-example2">Confirmed</label><br />
  23352. * <tt>debug = {{confirmed}}</tt><br/>
  23353. * <tt>counter = {{counter}}</tt><br/>
  23354. * </div>
  23355. * </file>
  23356. * <file name="protractor.js" type="protractor">
  23357. * var counter = element(by.binding('counter'));
  23358. * var debug = element(by.binding('confirmed'));
  23359. *
  23360. * it('should evaluate the expression if changing from view', function() {
  23361. * expect(counter.getText()).toContain('0');
  23362. *
  23363. * element(by.id('ng-change-example1')).click();
  23364. *
  23365. * expect(counter.getText()).toContain('1');
  23366. * expect(debug.getText()).toContain('true');
  23367. * });
  23368. *
  23369. * it('should not evaluate the expression if changing from model', function() {
  23370. * element(by.id('ng-change-example2')).click();
  23371. * expect(counter.getText()).toContain('0');
  23372. * expect(debug.getText()).toContain('true');
  23373. * });
  23374. * </file>
  23375. * </example>
  23376. */
  23377. var ngChangeDirective = valueFn({
  23378. restrict: 'A',
  23379. require: 'ngModel',
  23380. link: function(scope, element, attr, ctrl) {
  23381. ctrl.$viewChangeListeners.push(function() {
  23382. scope.$eval(attr.ngChange);
  23383. });
  23384. }
  23385. });
  23386. /* exported
  23387. ngClassDirective,
  23388. ngClassEvenDirective,
  23389. ngClassOddDirective
  23390. */
  23391. function classDirective(name, selector) {
  23392. name = 'ngClass' + name;
  23393. var indexWatchExpression;
  23394. return ['$parse', function($parse) {
  23395. return {
  23396. restrict: 'AC',
  23397. link: function(scope, element, attr) {
  23398. var expression = attr[name].trim();
  23399. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  23400. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  23401. var watchExpression = $parse(expression, watchInterceptor);
  23402. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  23403. var classCounts = element.data('$classCounts');
  23404. var oldModulo = true;
  23405. var oldClassString;
  23406. if (!classCounts) {
  23407. // Use createMap() to prevent class assumptions involving property
  23408. // names in Object.prototype
  23409. classCounts = createMap();
  23410. element.data('$classCounts', classCounts);
  23411. }
  23412. if (name !== 'ngClass') {
  23413. if (!indexWatchExpression) {
  23414. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  23415. // eslint-disable-next-line no-bitwise
  23416. return $index & 1;
  23417. });
  23418. }
  23419. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  23420. }
  23421. scope.$watch(watchExpression, watchAction, isOneTime);
  23422. function addClasses(classString) {
  23423. classString = digestClassCounts(split(classString), 1);
  23424. attr.$addClass(classString);
  23425. }
  23426. function removeClasses(classString) {
  23427. classString = digestClassCounts(split(classString), -1);
  23428. attr.$removeClass(classString);
  23429. }
  23430. function updateClasses(oldClassString, newClassString) {
  23431. var oldClassArray = split(oldClassString);
  23432. var newClassArray = split(newClassString);
  23433. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  23434. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  23435. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  23436. var toAddString = digestClassCounts(toAddArray, 1);
  23437. attr.$addClass(toAddString);
  23438. attr.$removeClass(toRemoveString);
  23439. }
  23440. function digestClassCounts(classArray, count) {
  23441. var classesToUpdate = [];
  23442. forEach(classArray, function(className) {
  23443. if (count > 0 || classCounts[className]) {
  23444. classCounts[className] = (classCounts[className] || 0) + count;
  23445. if (classCounts[className] === +(count > 0)) {
  23446. classesToUpdate.push(className);
  23447. }
  23448. }
  23449. });
  23450. return classesToUpdate.join(' ');
  23451. }
  23452. function ngClassIndexWatchAction(newModulo) {
  23453. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  23454. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  23455. // `ngClass[OneTime]WatchAction()` will update the classes.
  23456. if (newModulo === selector) {
  23457. addClasses(oldClassString);
  23458. } else {
  23459. removeClasses(oldClassString);
  23460. }
  23461. oldModulo = newModulo;
  23462. }
  23463. function ngClassOneTimeWatchAction(newClassValue) {
  23464. var newClassString = toClassString(newClassValue);
  23465. if (newClassString !== oldClassString) {
  23466. ngClassWatchAction(newClassString);
  23467. }
  23468. }
  23469. function ngClassWatchAction(newClassString) {
  23470. if (oldModulo === selector) {
  23471. updateClasses(oldClassString, newClassString);
  23472. }
  23473. oldClassString = newClassString;
  23474. }
  23475. }
  23476. };
  23477. }];
  23478. // Helpers
  23479. function arrayDifference(tokens1, tokens2) {
  23480. if (!tokens1 || !tokens1.length) return [];
  23481. if (!tokens2 || !tokens2.length) return tokens1;
  23482. var values = [];
  23483. outer:
  23484. for (var i = 0; i < tokens1.length; i++) {
  23485. var token = tokens1[i];
  23486. for (var j = 0; j < tokens2.length; j++) {
  23487. if (token === tokens2[j]) continue outer;
  23488. }
  23489. values.push(token);
  23490. }
  23491. return values;
  23492. }
  23493. function split(classString) {
  23494. return classString && classString.split(' ');
  23495. }
  23496. function toClassString(classValue) {
  23497. var classString = classValue;
  23498. if (isArray(classValue)) {
  23499. classString = classValue.map(toClassString).join(' ');
  23500. } else if (isObject(classValue)) {
  23501. classString = Object.keys(classValue).
  23502. filter(function(key) { return classValue[key]; }).
  23503. join(' ');
  23504. }
  23505. return classString;
  23506. }
  23507. function toFlatValue(classValue) {
  23508. var flatValue = classValue;
  23509. if (isArray(classValue)) {
  23510. flatValue = classValue.map(toFlatValue);
  23511. } else if (isObject(classValue)) {
  23512. var hasUndefined = false;
  23513. flatValue = Object.keys(classValue).filter(function(key) {
  23514. var value = classValue[key];
  23515. if (!hasUndefined && isUndefined(value)) {
  23516. hasUndefined = true;
  23517. }
  23518. return value;
  23519. });
  23520. if (hasUndefined) {
  23521. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  23522. // the watcher, by including at least one `undefined` value.
  23523. flatValue.push(undefined);
  23524. }
  23525. }
  23526. return flatValue;
  23527. }
  23528. }
  23529. /**
  23530. * @ngdoc directive
  23531. * @name ngClass
  23532. * @restrict AC
  23533. *
  23534. * @description
  23535. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  23536. * an expression that represents all classes to be added.
  23537. *
  23538. * The directive operates in three different ways, depending on which of three types the expression
  23539. * evaluates to:
  23540. *
  23541. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  23542. * names.
  23543. *
  23544. * 2. If the expression evaluates to an object, then for each key-value pair of the
  23545. * object with a truthy value the corresponding key is used as a class name.
  23546. *
  23547. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  23548. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  23549. * to give you more control over what CSS classes appear. See the code below for an example of this.
  23550. *
  23551. *
  23552. * The directive won't add duplicate classes if a particular class was already set.
  23553. *
  23554. * When the expression changes, the previously added classes are removed and only then are the
  23555. * new classes added.
  23556. *
  23557. * @knownIssue
  23558. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  23559. * attribute, when using the `ngClass` directive on the same element.
  23560. * See {@link guide/interpolation#known-issues here} for more info.
  23561. *
  23562. * @animations
  23563. * | Animation | Occurs |
  23564. * |----------------------------------|-------------------------------------|
  23565. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  23566. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  23567. *
  23568. * @element ANY
  23569. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  23570. * of the evaluation can be a string representing space delimited class
  23571. * names, an array, or a map of class names to boolean values. In the case of a map, the
  23572. * names of the properties whose values are truthy will be added as css classes to the
  23573. * element.
  23574. *
  23575. * @example Example that demonstrates basic bindings via ngClass directive.
  23576. <example name="ng-class">
  23577. <file name="index.html">
  23578. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  23579. <label>
  23580. <input type="checkbox" ng-model="deleted">
  23581. deleted (apply "strike" class)
  23582. </label><br>
  23583. <label>
  23584. <input type="checkbox" ng-model="important">
  23585. important (apply "bold" class)
  23586. </label><br>
  23587. <label>
  23588. <input type="checkbox" ng-model="error">
  23589. error (apply "has-error" class)
  23590. </label>
  23591. <hr>
  23592. <p ng-class="style">Using String Syntax</p>
  23593. <input type="text" ng-model="style"
  23594. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  23595. <hr>
  23596. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  23597. <input ng-model="style1"
  23598. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  23599. <input ng-model="style2"
  23600. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  23601. <input ng-model="style3"
  23602. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  23603. <hr>
  23604. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  23605. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  23606. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  23607. </file>
  23608. <file name="style.css">
  23609. .strike {
  23610. text-decoration: line-through;
  23611. }
  23612. .bold {
  23613. font-weight: bold;
  23614. }
  23615. .red {
  23616. color: red;
  23617. }
  23618. .has-error {
  23619. color: red;
  23620. background-color: yellow;
  23621. }
  23622. .orange {
  23623. color: orange;
  23624. }
  23625. </file>
  23626. <file name="protractor.js" type="protractor">
  23627. var ps = element.all(by.css('p'));
  23628. it('should let you toggle the class', function() {
  23629. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  23630. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  23631. element(by.model('important')).click();
  23632. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  23633. element(by.model('error')).click();
  23634. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  23635. });
  23636. it('should let you toggle string example', function() {
  23637. expect(ps.get(1).getAttribute('class')).toBe('');
  23638. element(by.model('style')).clear();
  23639. element(by.model('style')).sendKeys('red');
  23640. expect(ps.get(1).getAttribute('class')).toBe('red');
  23641. });
  23642. it('array example should have 3 classes', function() {
  23643. expect(ps.get(2).getAttribute('class')).toBe('');
  23644. element(by.model('style1')).sendKeys('bold');
  23645. element(by.model('style2')).sendKeys('strike');
  23646. element(by.model('style3')).sendKeys('red');
  23647. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  23648. });
  23649. it('array with map example should have 2 classes', function() {
  23650. expect(ps.last().getAttribute('class')).toBe('');
  23651. element(by.model('style4')).sendKeys('bold');
  23652. element(by.model('warning')).click();
  23653. expect(ps.last().getAttribute('class')).toBe('bold orange');
  23654. });
  23655. </file>
  23656. </example>
  23657. ## Animations
  23658. The example below demonstrates how to perform animations using ngClass.
  23659. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  23660. <file name="index.html">
  23661. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  23662. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  23663. <br>
  23664. <span class="base-class" ng-class="myVar">Sample Text</span>
  23665. </file>
  23666. <file name="style.css">
  23667. .base-class {
  23668. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23669. }
  23670. .base-class.my-class {
  23671. color: red;
  23672. font-size:3em;
  23673. }
  23674. </file>
  23675. <file name="protractor.js" type="protractor">
  23676. it('should check ng-class', function() {
  23677. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23678. toMatch(/my-class/);
  23679. element(by.id('setbtn')).click();
  23680. expect(element(by.css('.base-class')).getAttribute('class')).
  23681. toMatch(/my-class/);
  23682. element(by.id('clearbtn')).click();
  23683. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23684. toMatch(/my-class/);
  23685. });
  23686. </file>
  23687. </example>
  23688. ## ngClass and pre-existing CSS3 Transitions/Animations
  23689. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  23690. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  23691. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  23692. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  23693. {@link $animate#removeClass $animate.removeClass}.
  23694. */
  23695. var ngClassDirective = classDirective('', true);
  23696. /**
  23697. * @ngdoc directive
  23698. * @name ngClassOdd
  23699. * @restrict AC
  23700. *
  23701. * @description
  23702. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23703. * {@link ng.directive:ngClass ngClass}, except they work in
  23704. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23705. *
  23706. * This directive can be applied only within the scope of an
  23707. * {@link ng.directive:ngRepeat ngRepeat}.
  23708. *
  23709. * @element ANY
  23710. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  23711. * of the evaluation can be a string representing space delimited class names or an array.
  23712. *
  23713. * @example
  23714. <example name="ng-class-odd">
  23715. <file name="index.html">
  23716. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23717. <li ng-repeat="name in names">
  23718. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23719. {{name}}
  23720. </span>
  23721. </li>
  23722. </ol>
  23723. </file>
  23724. <file name="style.css">
  23725. .odd {
  23726. color: red;
  23727. }
  23728. .even {
  23729. color: blue;
  23730. }
  23731. </file>
  23732. <file name="protractor.js" type="protractor">
  23733. it('should check ng-class-odd and ng-class-even', function() {
  23734. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23735. toMatch(/odd/);
  23736. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23737. toMatch(/even/);
  23738. });
  23739. </file>
  23740. </example>
  23741. */
  23742. var ngClassOddDirective = classDirective('Odd', 0);
  23743. /**
  23744. * @ngdoc directive
  23745. * @name ngClassEven
  23746. * @restrict AC
  23747. *
  23748. * @description
  23749. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23750. * {@link ng.directive:ngClass ngClass}, except they work in
  23751. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23752. *
  23753. * This directive can be applied only within the scope of an
  23754. * {@link ng.directive:ngRepeat ngRepeat}.
  23755. *
  23756. * @element ANY
  23757. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23758. * result of the evaluation can be a string representing space delimited class names or an array.
  23759. *
  23760. * @example
  23761. <example name="ng-class-even">
  23762. <file name="index.html">
  23763. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23764. <li ng-repeat="name in names">
  23765. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23766. {{name}} &nbsp; &nbsp; &nbsp;
  23767. </span>
  23768. </li>
  23769. </ol>
  23770. </file>
  23771. <file name="style.css">
  23772. .odd {
  23773. color: red;
  23774. }
  23775. .even {
  23776. color: blue;
  23777. }
  23778. </file>
  23779. <file name="protractor.js" type="protractor">
  23780. it('should check ng-class-odd and ng-class-even', function() {
  23781. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23782. toMatch(/odd/);
  23783. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23784. toMatch(/even/);
  23785. });
  23786. </file>
  23787. </example>
  23788. */
  23789. var ngClassEvenDirective = classDirective('Even', 1);
  23790. /**
  23791. * @ngdoc directive
  23792. * @name ngCloak
  23793. * @restrict AC
  23794. *
  23795. * @description
  23796. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  23797. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  23798. * directive to avoid the undesirable flicker effect caused by the html template display.
  23799. *
  23800. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  23801. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  23802. * of the browser view.
  23803. *
  23804. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  23805. * `angular.min.js`.
  23806. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  23807. *
  23808. * ```css
  23809. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  23810. * display: none !important;
  23811. * }
  23812. * ```
  23813. *
  23814. * When this css rule is loaded by the browser, all html elements (including their children) that
  23815. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  23816. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  23817. * the compiled element visible.
  23818. *
  23819. * For the best result, the `angular.js` script must be loaded in the head section of the html
  23820. * document; alternatively, the css rule above must be included in the external stylesheet of the
  23821. * application.
  23822. *
  23823. * @element ANY
  23824. *
  23825. * @example
  23826. <example name="ng-cloak">
  23827. <file name="index.html">
  23828. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  23829. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  23830. </file>
  23831. <file name="protractor.js" type="protractor">
  23832. it('should remove the template directive and css class', function() {
  23833. expect($('#template1').getAttribute('ng-cloak')).
  23834. toBeNull();
  23835. expect($('#template2').getAttribute('ng-cloak')).
  23836. toBeNull();
  23837. });
  23838. </file>
  23839. </example>
  23840. *
  23841. */
  23842. var ngCloakDirective = ngDirective({
  23843. compile: function(element, attr) {
  23844. attr.$set('ngCloak', undefined);
  23845. element.removeClass('ng-cloak');
  23846. }
  23847. });
  23848. /**
  23849. * @ngdoc directive
  23850. * @name ngController
  23851. *
  23852. * @description
  23853. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  23854. * supports the principles behind the Model-View-Controller design pattern.
  23855. *
  23856. * MVC components in angular:
  23857. *
  23858. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  23859. * are accessed through bindings.
  23860. * * View — The template (HTML with data bindings) that is rendered into the View.
  23861. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  23862. * logic behind the application to decorate the scope with functions and values
  23863. *
  23864. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  23865. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  23866. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  23867. * and executed twice.
  23868. *
  23869. * @element ANY
  23870. * @scope
  23871. * @priority 500
  23872. * @param {expression} ngController Name of a constructor function registered with the current
  23873. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  23874. * that on the current scope evaluates to a constructor function.
  23875. *
  23876. * The controller instance can be published into a scope property by specifying
  23877. * `ng-controller="as propertyName"`.
  23878. *
  23879. * If the current `$controllerProvider` is configured to use globals (via
  23880. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  23881. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  23882. *
  23883. * @example
  23884. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  23885. * greeting are methods declared on the controller (see source tab). These methods can
  23886. * easily be called from the angular markup. Any changes to the data are automatically reflected
  23887. * in the View without the need for a manual update.
  23888. *
  23889. * Two different declaration styles are included below:
  23890. *
  23891. * * one binds methods and properties directly onto the controller using `this`:
  23892. * `ng-controller="SettingsController1 as settings"`
  23893. * * one injects `$scope` into the controller:
  23894. * `ng-controller="SettingsController2"`
  23895. *
  23896. * The second option is more common in the Angular community, and is generally used in boilerplates
  23897. * and in this guide. However, there are advantages to binding properties directly to the controller
  23898. * and avoiding scope.
  23899. *
  23900. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  23901. * multiple controllers apply to an element.
  23902. * * If you are writing your controllers as classes you have easier access to the properties and
  23903. * methods, which will appear on the scope, from inside the controller code.
  23904. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  23905. * inheritance masking primitives.
  23906. *
  23907. * This example demonstrates the `controller as` syntax.
  23908. *
  23909. * <example name="ngControllerAs" module="controllerAsExample">
  23910. * <file name="index.html">
  23911. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  23912. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  23913. * <button ng-click="settings.greet()">greet</button><br/>
  23914. * Contact:
  23915. * <ul>
  23916. * <li ng-repeat="contact in settings.contacts">
  23917. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  23918. * <option>phone</option>
  23919. * <option>email</option>
  23920. * </select>
  23921. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23922. * <button ng-click="settings.clearContact(contact)">clear</button>
  23923. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  23924. * </li>
  23925. * <li><button ng-click="settings.addContact()">add</button></li>
  23926. * </ul>
  23927. * </div>
  23928. * </file>
  23929. * <file name="app.js">
  23930. * angular.module('controllerAsExample', [])
  23931. * .controller('SettingsController1', SettingsController1);
  23932. *
  23933. * function SettingsController1() {
  23934. * this.name = 'John Smith';
  23935. * this.contacts = [
  23936. * {type: 'phone', value: '408 555 1212'},
  23937. * {type: 'email', value: 'john.smith@example.org'}
  23938. * ];
  23939. * }
  23940. *
  23941. * SettingsController1.prototype.greet = function() {
  23942. * alert(this.name);
  23943. * };
  23944. *
  23945. * SettingsController1.prototype.addContact = function() {
  23946. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  23947. * };
  23948. *
  23949. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  23950. * var index = this.contacts.indexOf(contactToRemove);
  23951. * this.contacts.splice(index, 1);
  23952. * };
  23953. *
  23954. * SettingsController1.prototype.clearContact = function(contact) {
  23955. * contact.type = 'phone';
  23956. * contact.value = '';
  23957. * };
  23958. * </file>
  23959. * <file name="protractor.js" type="protractor">
  23960. * it('should check controller as', function() {
  23961. * var container = element(by.id('ctrl-as-exmpl'));
  23962. * expect(container.element(by.model('settings.name'))
  23963. * .getAttribute('value')).toBe('John Smith');
  23964. *
  23965. * var firstRepeat =
  23966. * container.element(by.repeater('contact in settings.contacts').row(0));
  23967. * var secondRepeat =
  23968. * container.element(by.repeater('contact in settings.contacts').row(1));
  23969. *
  23970. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23971. * .toBe('408 555 1212');
  23972. *
  23973. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23974. * .toBe('john.smith@example.org');
  23975. *
  23976. * firstRepeat.element(by.buttonText('clear')).click();
  23977. *
  23978. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23979. * .toBe('');
  23980. *
  23981. * container.element(by.buttonText('add')).click();
  23982. *
  23983. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  23984. * .element(by.model('contact.value'))
  23985. * .getAttribute('value'))
  23986. * .toBe('yourname@example.org');
  23987. * });
  23988. * </file>
  23989. * </example>
  23990. *
  23991. * This example demonstrates the "attach to `$scope`" style of controller.
  23992. *
  23993. * <example name="ngController" module="controllerExample">
  23994. * <file name="index.html">
  23995. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  23996. * <label>Name: <input type="text" ng-model="name"/></label>
  23997. * <button ng-click="greet()">greet</button><br/>
  23998. * Contact:
  23999. * <ul>
  24000. * <li ng-repeat="contact in contacts">
  24001. * <select ng-model="contact.type" id="select_{{$index}}">
  24002. * <option>phone</option>
  24003. * <option>email</option>
  24004. * </select>
  24005. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24006. * <button ng-click="clearContact(contact)">clear</button>
  24007. * <button ng-click="removeContact(contact)">X</button>
  24008. * </li>
  24009. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24010. * </ul>
  24011. * </div>
  24012. * </file>
  24013. * <file name="app.js">
  24014. * angular.module('controllerExample', [])
  24015. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24016. *
  24017. * function SettingsController2($scope) {
  24018. * $scope.name = 'John Smith';
  24019. * $scope.contacts = [
  24020. * {type:'phone', value:'408 555 1212'},
  24021. * {type:'email', value:'john.smith@example.org'}
  24022. * ];
  24023. *
  24024. * $scope.greet = function() {
  24025. * alert($scope.name);
  24026. * };
  24027. *
  24028. * $scope.addContact = function() {
  24029. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24030. * };
  24031. *
  24032. * $scope.removeContact = function(contactToRemove) {
  24033. * var index = $scope.contacts.indexOf(contactToRemove);
  24034. * $scope.contacts.splice(index, 1);
  24035. * };
  24036. *
  24037. * $scope.clearContact = function(contact) {
  24038. * contact.type = 'phone';
  24039. * contact.value = '';
  24040. * };
  24041. * }
  24042. * </file>
  24043. * <file name="protractor.js" type="protractor">
  24044. * it('should check controller', function() {
  24045. * var container = element(by.id('ctrl-exmpl'));
  24046. *
  24047. * expect(container.element(by.model('name'))
  24048. * .getAttribute('value')).toBe('John Smith');
  24049. *
  24050. * var firstRepeat =
  24051. * container.element(by.repeater('contact in contacts').row(0));
  24052. * var secondRepeat =
  24053. * container.element(by.repeater('contact in contacts').row(1));
  24054. *
  24055. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24056. * .toBe('408 555 1212');
  24057. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24058. * .toBe('john.smith@example.org');
  24059. *
  24060. * firstRepeat.element(by.buttonText('clear')).click();
  24061. *
  24062. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24063. * .toBe('');
  24064. *
  24065. * container.element(by.buttonText('add')).click();
  24066. *
  24067. * expect(container.element(by.repeater('contact in contacts').row(2))
  24068. * .element(by.model('contact.value'))
  24069. * .getAttribute('value'))
  24070. * .toBe('yourname@example.org');
  24071. * });
  24072. * </file>
  24073. *</example>
  24074. */
  24075. var ngControllerDirective = [function() {
  24076. return {
  24077. restrict: 'A',
  24078. scope: true,
  24079. controller: '@',
  24080. priority: 500
  24081. };
  24082. }];
  24083. /**
  24084. * @ngdoc directive
  24085. * @name ngCsp
  24086. *
  24087. * @restrict A
  24088. * @element ANY
  24089. * @description
  24090. *
  24091. * Angular has some features that can conflict with certain restrictions that are applied when using
  24092. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24093. *
  24094. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24095. * features.
  24096. *
  24097. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24098. *
  24099. *
  24100. * The following default rules in CSP affect Angular:
  24101. *
  24102. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24103. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24104. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24105. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24106. * weaken the protections offered by CSP.)
  24107. *
  24108. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24109. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24110. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24111. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24112. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24113. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24114. *
  24115. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24116. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24117. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24118. * CSP error to be logged in the console:
  24119. *
  24120. * ```
  24121. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24122. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24123. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24124. * ```
  24125. *
  24126. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24127. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24128. * the `angular.js` file.
  24129. *
  24130. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24131. *
  24132. * You can specify which of the CSP related Angular features should be deactivated by providing
  24133. * a value for the `ng-csp` attribute. The options are as follows:
  24134. *
  24135. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24136. *
  24137. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24138. *
  24139. * You can use these values in the following combinations:
  24140. *
  24141. *
  24142. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24143. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24144. * versions of Angular.
  24145. *
  24146. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24147. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24148. * versions of Angular.
  24149. *
  24150. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24151. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24152. *
  24153. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24154. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24155. *
  24156. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24157. * styles nor use eval, which is the same as an empty: ng-csp.
  24158. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24159. *
  24160. * @example
  24161. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24162. ```html
  24163. <!doctype html>
  24164. <html ng-app ng-csp>
  24165. ...
  24166. ...
  24167. </html>
  24168. ```
  24169. * @example
  24170. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24171. <example name="example.csp" module="cspExample" ng-csp="true">
  24172. <file name="index.html">
  24173. <div ng-controller="MainController as ctrl">
  24174. <div>
  24175. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24176. <span id="counter">
  24177. {{ctrl.counter}}
  24178. </span>
  24179. </div>
  24180. <div>
  24181. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24182. <span id="evilError">
  24183. {{ctrl.evilError}}
  24184. </span>
  24185. </div>
  24186. </div>
  24187. </file>
  24188. <file name="script.js">
  24189. angular.module('cspExample', [])
  24190. .controller('MainController', function MainController() {
  24191. this.counter = 0;
  24192. this.inc = function() {
  24193. this.counter++;
  24194. };
  24195. this.evil = function() {
  24196. try {
  24197. eval('1+2'); // eslint-disable-line no-eval
  24198. } catch (e) {
  24199. this.evilError = e.message;
  24200. }
  24201. };
  24202. });
  24203. </file>
  24204. <file name="protractor.js" type="protractor">
  24205. var util, webdriver;
  24206. var incBtn = element(by.id('inc'));
  24207. var counter = element(by.id('counter'));
  24208. var evilBtn = element(by.id('evil'));
  24209. var evilError = element(by.id('evilError'));
  24210. function getAndClearSevereErrors() {
  24211. return browser.manage().logs().get('browser').then(function(browserLog) {
  24212. return browserLog.filter(function(logEntry) {
  24213. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24214. });
  24215. });
  24216. }
  24217. function clearErrors() {
  24218. getAndClearSevereErrors();
  24219. }
  24220. function expectNoErrors() {
  24221. getAndClearSevereErrors().then(function(filteredLog) {
  24222. expect(filteredLog.length).toEqual(0);
  24223. if (filteredLog.length) {
  24224. console.log('browser console errors: ' + util.inspect(filteredLog));
  24225. }
  24226. });
  24227. }
  24228. function expectError(regex) {
  24229. getAndClearSevereErrors().then(function(filteredLog) {
  24230. var found = false;
  24231. filteredLog.forEach(function(log) {
  24232. if (log.message.match(regex)) {
  24233. found = true;
  24234. }
  24235. });
  24236. if (!found) {
  24237. throw new Error('expected an error that matches ' + regex);
  24238. }
  24239. });
  24240. }
  24241. beforeEach(function() {
  24242. util = require('util');
  24243. webdriver = require('selenium-webdriver');
  24244. });
  24245. // For now, we only test on Chrome,
  24246. // as Safari does not load the page with Protractor's injected scripts,
  24247. // and Firefox webdriver always disables content security policy (#6358)
  24248. if (browser.params.browser !== 'chrome') {
  24249. return;
  24250. }
  24251. it('should not report errors when the page is loaded', function() {
  24252. // clear errors so we are not dependent on previous tests
  24253. clearErrors();
  24254. // Need to reload the page as the page is already loaded when
  24255. // we come here
  24256. browser.driver.getCurrentUrl().then(function(url) {
  24257. browser.get(url);
  24258. });
  24259. expectNoErrors();
  24260. });
  24261. it('should evaluate expressions', function() {
  24262. expect(counter.getText()).toEqual('0');
  24263. incBtn.click();
  24264. expect(counter.getText()).toEqual('1');
  24265. expectNoErrors();
  24266. });
  24267. it('should throw and report an error when using "eval"', function() {
  24268. evilBtn.click();
  24269. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24270. expectError(/Content Security Policy/);
  24271. });
  24272. </file>
  24273. </example>
  24274. */
  24275. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24276. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24277. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24278. /**
  24279. * @ngdoc directive
  24280. * @name ngClick
  24281. *
  24282. * @description
  24283. * The ngClick directive allows you to specify custom behavior when
  24284. * an element is clicked.
  24285. *
  24286. * @element ANY
  24287. * @priority 0
  24288. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24289. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24290. *
  24291. * @example
  24292. <example name="ng-click">
  24293. <file name="index.html">
  24294. <button ng-click="count = count + 1" ng-init="count=0">
  24295. Increment
  24296. </button>
  24297. <span>
  24298. count: {{count}}
  24299. </span>
  24300. </file>
  24301. <file name="protractor.js" type="protractor">
  24302. it('should check ng-click', function() {
  24303. expect(element(by.binding('count')).getText()).toMatch('0');
  24304. element(by.css('button')).click();
  24305. expect(element(by.binding('count')).getText()).toMatch('1');
  24306. });
  24307. </file>
  24308. </example>
  24309. */
  24310. /*
  24311. * A collection of directives that allows creation of custom event handlers that are defined as
  24312. * angular expressions and are compiled and executed within the current scope.
  24313. */
  24314. var ngEventDirectives = {};
  24315. // For events that might fire synchronously during DOM manipulation
  24316. // we need to execute their event handlers asynchronously using $evalAsync,
  24317. // so that they are not executed in an inconsistent state.
  24318. var forceAsyncEvents = {
  24319. 'blur': true,
  24320. 'focus': true
  24321. };
  24322. forEach(
  24323. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24324. function(eventName) {
  24325. var directiveName = directiveNormalize('ng-' + eventName);
  24326. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24327. return {
  24328. restrict: 'A',
  24329. compile: function($element, attr) {
  24330. // We expose the powerful $event object on the scope that provides access to the Window,
  24331. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  24332. // checks at the cost of speed since event handler expressions are not executed as
  24333. // frequently as regular change detection.
  24334. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  24335. return function ngEventHandler(scope, element) {
  24336. element.on(eventName, function(event) {
  24337. var callback = function() {
  24338. fn(scope, {$event:event});
  24339. };
  24340. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24341. scope.$evalAsync(callback);
  24342. } else {
  24343. scope.$apply(callback);
  24344. }
  24345. });
  24346. };
  24347. }
  24348. };
  24349. }];
  24350. }
  24351. );
  24352. /**
  24353. * @ngdoc directive
  24354. * @name ngDblclick
  24355. *
  24356. * @description
  24357. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24358. *
  24359. * @element ANY
  24360. * @priority 0
  24361. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24362. * a dblclick. (The Event object is available as `$event`)
  24363. *
  24364. * @example
  24365. <example name="ng-dblclick">
  24366. <file name="index.html">
  24367. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24368. Increment (on double click)
  24369. </button>
  24370. count: {{count}}
  24371. </file>
  24372. </example>
  24373. */
  24374. /**
  24375. * @ngdoc directive
  24376. * @name ngMousedown
  24377. *
  24378. * @description
  24379. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24380. *
  24381. * @element ANY
  24382. * @priority 0
  24383. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24384. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24385. *
  24386. * @example
  24387. <example name="ng-mousedown">
  24388. <file name="index.html">
  24389. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24390. Increment (on mouse down)
  24391. </button>
  24392. count: {{count}}
  24393. </file>
  24394. </example>
  24395. */
  24396. /**
  24397. * @ngdoc directive
  24398. * @name ngMouseup
  24399. *
  24400. * @description
  24401. * Specify custom behavior on mouseup event.
  24402. *
  24403. * @element ANY
  24404. * @priority 0
  24405. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24406. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24407. *
  24408. * @example
  24409. <example name="ng-mouseup">
  24410. <file name="index.html">
  24411. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24412. Increment (on mouse up)
  24413. </button>
  24414. count: {{count}}
  24415. </file>
  24416. </example>
  24417. */
  24418. /**
  24419. * @ngdoc directive
  24420. * @name ngMouseover
  24421. *
  24422. * @description
  24423. * Specify custom behavior on mouseover event.
  24424. *
  24425. * @element ANY
  24426. * @priority 0
  24427. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24428. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24429. *
  24430. * @example
  24431. <example name="ng-mouseover">
  24432. <file name="index.html">
  24433. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24434. Increment (when mouse is over)
  24435. </button>
  24436. count: {{count}}
  24437. </file>
  24438. </example>
  24439. */
  24440. /**
  24441. * @ngdoc directive
  24442. * @name ngMouseenter
  24443. *
  24444. * @description
  24445. * Specify custom behavior on mouseenter event.
  24446. *
  24447. * @element ANY
  24448. * @priority 0
  24449. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24450. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  24451. *
  24452. * @example
  24453. <example name="ng-mouseenter">
  24454. <file name="index.html">
  24455. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  24456. Increment (when mouse enters)
  24457. </button>
  24458. count: {{count}}
  24459. </file>
  24460. </example>
  24461. */
  24462. /**
  24463. * @ngdoc directive
  24464. * @name ngMouseleave
  24465. *
  24466. * @description
  24467. * Specify custom behavior on mouseleave event.
  24468. *
  24469. * @element ANY
  24470. * @priority 0
  24471. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  24472. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  24473. *
  24474. * @example
  24475. <example name="ng-mouseleave">
  24476. <file name="index.html">
  24477. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  24478. Increment (when mouse leaves)
  24479. </button>
  24480. count: {{count}}
  24481. </file>
  24482. </example>
  24483. */
  24484. /**
  24485. * @ngdoc directive
  24486. * @name ngMousemove
  24487. *
  24488. * @description
  24489. * Specify custom behavior on mousemove event.
  24490. *
  24491. * @element ANY
  24492. * @priority 0
  24493. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  24494. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  24495. *
  24496. * @example
  24497. <example name="ng-mousemove">
  24498. <file name="index.html">
  24499. <button ng-mousemove="count = count + 1" ng-init="count=0">
  24500. Increment (when mouse moves)
  24501. </button>
  24502. count: {{count}}
  24503. </file>
  24504. </example>
  24505. */
  24506. /**
  24507. * @ngdoc directive
  24508. * @name ngKeydown
  24509. *
  24510. * @description
  24511. * Specify custom behavior on keydown event.
  24512. *
  24513. * @element ANY
  24514. * @priority 0
  24515. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  24516. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24517. *
  24518. * @example
  24519. <example name="ng-keydown">
  24520. <file name="index.html">
  24521. <input ng-keydown="count = count + 1" ng-init="count=0">
  24522. key down count: {{count}}
  24523. </file>
  24524. </example>
  24525. */
  24526. /**
  24527. * @ngdoc directive
  24528. * @name ngKeyup
  24529. *
  24530. * @description
  24531. * Specify custom behavior on keyup event.
  24532. *
  24533. * @element ANY
  24534. * @priority 0
  24535. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  24536. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24537. *
  24538. * @example
  24539. <example name="ng-keyup">
  24540. <file name="index.html">
  24541. <p>Typing in the input box below updates the key count</p>
  24542. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  24543. <p>Typing in the input box below updates the keycode</p>
  24544. <input ng-keyup="event=$event">
  24545. <p>event keyCode: {{ event.keyCode }}</p>
  24546. <p>event altKey: {{ event.altKey }}</p>
  24547. </file>
  24548. </example>
  24549. */
  24550. /**
  24551. * @ngdoc directive
  24552. * @name ngKeypress
  24553. *
  24554. * @description
  24555. * Specify custom behavior on keypress event.
  24556. *
  24557. * @element ANY
  24558. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  24559. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  24560. * and can be interrogated for keyCode, altKey, etc.)
  24561. *
  24562. * @example
  24563. <example name="ng-keypress">
  24564. <file name="index.html">
  24565. <input ng-keypress="count = count + 1" ng-init="count=0">
  24566. key press count: {{count}}
  24567. </file>
  24568. </example>
  24569. */
  24570. /**
  24571. * @ngdoc directive
  24572. * @name ngSubmit
  24573. *
  24574. * @description
  24575. * Enables binding angular expressions to onsubmit events.
  24576. *
  24577. * Additionally it prevents the default action (which for form means sending the request to the
  24578. * server and reloading the current page), but only if the form does not contain `action`,
  24579. * `data-action`, or `x-action` attributes.
  24580. *
  24581. * <div class="alert alert-warning">
  24582. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  24583. * `ngSubmit` handlers together. See the
  24584. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  24585. * for a detailed discussion of when `ngSubmit` may be triggered.
  24586. * </div>
  24587. *
  24588. * @element form
  24589. * @priority 0
  24590. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  24591. * ({@link guide/expression#-event- Event object is available as `$event`})
  24592. *
  24593. * @example
  24594. <example module="submitExample" name="ng-submit">
  24595. <file name="index.html">
  24596. <script>
  24597. angular.module('submitExample', [])
  24598. .controller('ExampleController', ['$scope', function($scope) {
  24599. $scope.list = [];
  24600. $scope.text = 'hello';
  24601. $scope.submit = function() {
  24602. if ($scope.text) {
  24603. $scope.list.push(this.text);
  24604. $scope.text = '';
  24605. }
  24606. };
  24607. }]);
  24608. </script>
  24609. <form ng-submit="submit()" ng-controller="ExampleController">
  24610. Enter text and hit enter:
  24611. <input type="text" ng-model="text" name="text" />
  24612. <input type="submit" id="submit" value="Submit" />
  24613. <pre>list={{list}}</pre>
  24614. </form>
  24615. </file>
  24616. <file name="protractor.js" type="protractor">
  24617. it('should check ng-submit', function() {
  24618. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24619. element(by.css('#submit')).click();
  24620. expect(element(by.binding('list')).getText()).toContain('hello');
  24621. expect(element(by.model('text')).getAttribute('value')).toBe('');
  24622. });
  24623. it('should ignore empty strings', function() {
  24624. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24625. element(by.css('#submit')).click();
  24626. element(by.css('#submit')).click();
  24627. expect(element(by.binding('list')).getText()).toContain('hello');
  24628. });
  24629. </file>
  24630. </example>
  24631. */
  24632. /**
  24633. * @ngdoc directive
  24634. * @name ngFocus
  24635. *
  24636. * @description
  24637. * Specify custom behavior on focus event.
  24638. *
  24639. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  24640. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24641. * during an `$apply` to ensure a consistent state.
  24642. *
  24643. * @element window, input, select, textarea, a
  24644. * @priority 0
  24645. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  24646. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  24647. *
  24648. * @example
  24649. * See {@link ng.directive:ngClick ngClick}
  24650. */
  24651. /**
  24652. * @ngdoc directive
  24653. * @name ngBlur
  24654. *
  24655. * @description
  24656. * Specify custom behavior on blur event.
  24657. *
  24658. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  24659. * an element has lost focus.
  24660. *
  24661. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  24662. * (e.g. removing a focussed input),
  24663. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24664. * during an `$apply` to ensure a consistent state.
  24665. *
  24666. * @element window, input, select, textarea, a
  24667. * @priority 0
  24668. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  24669. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  24670. *
  24671. * @example
  24672. * See {@link ng.directive:ngClick ngClick}
  24673. */
  24674. /**
  24675. * @ngdoc directive
  24676. * @name ngCopy
  24677. *
  24678. * @description
  24679. * Specify custom behavior on copy event.
  24680. *
  24681. * @element window, input, select, textarea, a
  24682. * @priority 0
  24683. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  24684. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  24685. *
  24686. * @example
  24687. <example name="ng-copy">
  24688. <file name="index.html">
  24689. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  24690. copied: {{copied}}
  24691. </file>
  24692. </example>
  24693. */
  24694. /**
  24695. * @ngdoc directive
  24696. * @name ngCut
  24697. *
  24698. * @description
  24699. * Specify custom behavior on cut event.
  24700. *
  24701. * @element window, input, select, textarea, a
  24702. * @priority 0
  24703. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  24704. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  24705. *
  24706. * @example
  24707. <example name="ng-cut">
  24708. <file name="index.html">
  24709. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  24710. cut: {{cut}}
  24711. </file>
  24712. </example>
  24713. */
  24714. /**
  24715. * @ngdoc directive
  24716. * @name ngPaste
  24717. *
  24718. * @description
  24719. * Specify custom behavior on paste event.
  24720. *
  24721. * @element window, input, select, textarea, a
  24722. * @priority 0
  24723. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  24724. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  24725. *
  24726. * @example
  24727. <example name="ng-paste">
  24728. <file name="index.html">
  24729. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  24730. pasted: {{paste}}
  24731. </file>
  24732. </example>
  24733. */
  24734. /**
  24735. * @ngdoc directive
  24736. * @name ngIf
  24737. * @restrict A
  24738. * @multiElement
  24739. *
  24740. * @description
  24741. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  24742. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  24743. * value then the element is removed from the DOM, otherwise a clone of the
  24744. * element is reinserted into the DOM.
  24745. *
  24746. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  24747. * element in the DOM rather than changing its visibility via the `display` css property. A common
  24748. * case when this difference is significant is when using css selectors that rely on an element's
  24749. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  24750. *
  24751. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24752. * is created when the element is restored. The scope created within `ngIf` inherits from
  24753. * its parent scope using
  24754. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24755. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24756. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24757. * variable within the child scope will override (hide) the value in the parent scope.
  24758. *
  24759. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24760. * is if an element's class attribute is directly modified after it's compiled, using something like
  24761. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24762. * the added class will be lost because the original compiled state is used to regenerate the element.
  24763. *
  24764. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24765. * and `leave` effects.
  24766. *
  24767. * @animations
  24768. * | Animation | Occurs |
  24769. * |----------------------------------|-------------------------------------|
  24770. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24771. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  24772. *
  24773. * @element ANY
  24774. * @scope
  24775. * @priority 600
  24776. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  24777. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  24778. * element is added to the DOM tree.
  24779. *
  24780. * @example
  24781. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  24782. <file name="index.html">
  24783. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  24784. Show when checked:
  24785. <span ng-if="checked" class="animate-if">
  24786. This is removed when the checkbox is unchecked.
  24787. </span>
  24788. </file>
  24789. <file name="animations.css">
  24790. .animate-if {
  24791. background:white;
  24792. border:1px solid black;
  24793. padding:10px;
  24794. }
  24795. .animate-if.ng-enter, .animate-if.ng-leave {
  24796. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24797. }
  24798. .animate-if.ng-enter,
  24799. .animate-if.ng-leave.ng-leave-active {
  24800. opacity:0;
  24801. }
  24802. .animate-if.ng-leave,
  24803. .animate-if.ng-enter.ng-enter-active {
  24804. opacity:1;
  24805. }
  24806. </file>
  24807. </example>
  24808. */
  24809. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  24810. return {
  24811. multiElement: true,
  24812. transclude: 'element',
  24813. priority: 600,
  24814. terminal: true,
  24815. restrict: 'A',
  24816. $$tlb: true,
  24817. link: function($scope, $element, $attr, ctrl, $transclude) {
  24818. var block, childScope, previousElements;
  24819. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  24820. if (value) {
  24821. if (!childScope) {
  24822. $transclude(function(clone, newScope) {
  24823. childScope = newScope;
  24824. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  24825. // Note: We only need the first/last node of the cloned nodes.
  24826. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24827. // by a directive with templateUrl when its template arrives.
  24828. block = {
  24829. clone: clone
  24830. };
  24831. $animate.enter(clone, $element.parent(), $element);
  24832. });
  24833. }
  24834. } else {
  24835. if (previousElements) {
  24836. previousElements.remove();
  24837. previousElements = null;
  24838. }
  24839. if (childScope) {
  24840. childScope.$destroy();
  24841. childScope = null;
  24842. }
  24843. if (block) {
  24844. previousElements = getBlockNodes(block.clone);
  24845. $animate.leave(previousElements).done(function(response) {
  24846. if (response !== false) previousElements = null;
  24847. });
  24848. block = null;
  24849. }
  24850. }
  24851. });
  24852. }
  24853. };
  24854. }];
  24855. /**
  24856. * @ngdoc directive
  24857. * @name ngInclude
  24858. * @restrict ECA
  24859. *
  24860. * @description
  24861. * Fetches, compiles and includes an external HTML fragment.
  24862. *
  24863. * By default, the template URL is restricted to the same domain and protocol as the
  24864. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  24865. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  24866. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  24867. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  24868. * ng.$sce Strict Contextual Escaping}.
  24869. *
  24870. * In addition, the browser's
  24871. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  24872. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  24873. * policy may further restrict whether the template is successfully loaded.
  24874. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  24875. * access on some browsers.
  24876. *
  24877. * @animations
  24878. * | Animation | Occurs |
  24879. * |----------------------------------|-------------------------------------|
  24880. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  24881. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  24882. *
  24883. * The enter and leave animation occur concurrently.
  24884. *
  24885. * @scope
  24886. * @priority 400
  24887. *
  24888. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  24889. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  24890. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  24891. * <div class="alert alert-warning">
  24892. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  24893. * a function with the name on the window element, which will usually throw a
  24894. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  24895. * different form that {@link guide/directive#normalization matches} `onload`.
  24896. * </div>
  24897. *
  24898. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  24899. * $anchorScroll} to scroll the viewport after the content is loaded.
  24900. *
  24901. * - If the attribute is not set, disable scrolling.
  24902. * - If the attribute is set without value, enable scrolling.
  24903. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  24904. *
  24905. * @example
  24906. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  24907. <file name="index.html">
  24908. <div ng-controller="ExampleController">
  24909. <select ng-model="template" ng-options="t.name for t in templates">
  24910. <option value="">(blank)</option>
  24911. </select>
  24912. url of the template: <code>{{template.url}}</code>
  24913. <hr/>
  24914. <div class="slide-animate-container">
  24915. <div class="slide-animate" ng-include="template.url"></div>
  24916. </div>
  24917. </div>
  24918. </file>
  24919. <file name="script.js">
  24920. angular.module('includeExample', ['ngAnimate'])
  24921. .controller('ExampleController', ['$scope', function($scope) {
  24922. $scope.templates =
  24923. [{ name: 'template1.html', url: 'template1.html'},
  24924. { name: 'template2.html', url: 'template2.html'}];
  24925. $scope.template = $scope.templates[0];
  24926. }]);
  24927. </file>
  24928. <file name="template1.html">
  24929. Content of template1.html
  24930. </file>
  24931. <file name="template2.html">
  24932. Content of template2.html
  24933. </file>
  24934. <file name="animations.css">
  24935. .slide-animate-container {
  24936. position:relative;
  24937. background:white;
  24938. border:1px solid black;
  24939. height:40px;
  24940. overflow:hidden;
  24941. }
  24942. .slide-animate {
  24943. padding:10px;
  24944. }
  24945. .slide-animate.ng-enter, .slide-animate.ng-leave {
  24946. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24947. position:absolute;
  24948. top:0;
  24949. left:0;
  24950. right:0;
  24951. bottom:0;
  24952. display:block;
  24953. padding:10px;
  24954. }
  24955. .slide-animate.ng-enter {
  24956. top:-50px;
  24957. }
  24958. .slide-animate.ng-enter.ng-enter-active {
  24959. top:0;
  24960. }
  24961. .slide-animate.ng-leave {
  24962. top:0;
  24963. }
  24964. .slide-animate.ng-leave.ng-leave-active {
  24965. top:50px;
  24966. }
  24967. </file>
  24968. <file name="protractor.js" type="protractor">
  24969. var templateSelect = element(by.model('template'));
  24970. var includeElem = element(by.css('[ng-include]'));
  24971. it('should load template1.html', function() {
  24972. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  24973. });
  24974. it('should load template2.html', function() {
  24975. if (browser.params.browser === 'firefox') {
  24976. // Firefox can't handle using selects
  24977. // See https://github.com/angular/protractor/issues/480
  24978. return;
  24979. }
  24980. templateSelect.click();
  24981. templateSelect.all(by.css('option')).get(2).click();
  24982. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  24983. });
  24984. it('should change to blank', function() {
  24985. if (browser.params.browser === 'firefox') {
  24986. // Firefox can't handle using selects
  24987. return;
  24988. }
  24989. templateSelect.click();
  24990. templateSelect.all(by.css('option')).get(0).click();
  24991. expect(includeElem.isPresent()).toBe(false);
  24992. });
  24993. </file>
  24994. </example>
  24995. */
  24996. /**
  24997. * @ngdoc event
  24998. * @name ngInclude#$includeContentRequested
  24999. * @eventType emit on the scope ngInclude was declared in
  25000. * @description
  25001. * Emitted every time the ngInclude content is requested.
  25002. *
  25003. * @param {Object} angularEvent Synthetic event object.
  25004. * @param {String} src URL of content to load.
  25005. */
  25006. /**
  25007. * @ngdoc event
  25008. * @name ngInclude#$includeContentLoaded
  25009. * @eventType emit on the current ngInclude scope
  25010. * @description
  25011. * Emitted every time the ngInclude content is reloaded.
  25012. *
  25013. * @param {Object} angularEvent Synthetic event object.
  25014. * @param {String} src URL of content to load.
  25015. */
  25016. /**
  25017. * @ngdoc event
  25018. * @name ngInclude#$includeContentError
  25019. * @eventType emit on the scope ngInclude was declared in
  25020. * @description
  25021. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25022. *
  25023. * @param {Object} angularEvent Synthetic event object.
  25024. * @param {String} src URL of content to load.
  25025. */
  25026. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25027. function($templateRequest, $anchorScroll, $animate) {
  25028. return {
  25029. restrict: 'ECA',
  25030. priority: 400,
  25031. terminal: true,
  25032. transclude: 'element',
  25033. controller: angular.noop,
  25034. compile: function(element, attr) {
  25035. var srcExp = attr.ngInclude || attr.src,
  25036. onloadExp = attr.onload || '',
  25037. autoScrollExp = attr.autoscroll;
  25038. return function(scope, $element, $attr, ctrl, $transclude) {
  25039. var changeCounter = 0,
  25040. currentScope,
  25041. previousElement,
  25042. currentElement;
  25043. var cleanupLastIncludeContent = function() {
  25044. if (previousElement) {
  25045. previousElement.remove();
  25046. previousElement = null;
  25047. }
  25048. if (currentScope) {
  25049. currentScope.$destroy();
  25050. currentScope = null;
  25051. }
  25052. if (currentElement) {
  25053. $animate.leave(currentElement).done(function(response) {
  25054. if (response !== false) previousElement = null;
  25055. });
  25056. previousElement = currentElement;
  25057. currentElement = null;
  25058. }
  25059. };
  25060. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25061. var afterAnimation = function(response) {
  25062. if (response !== false && isDefined(autoScrollExp) &&
  25063. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25064. $anchorScroll();
  25065. }
  25066. };
  25067. var thisChangeId = ++changeCounter;
  25068. if (src) {
  25069. //set the 2nd param to true to ignore the template request error so that the inner
  25070. //contents and scope can be cleaned up.
  25071. $templateRequest(src, true).then(function(response) {
  25072. if (scope.$$destroyed) return;
  25073. if (thisChangeId !== changeCounter) return;
  25074. var newScope = scope.$new();
  25075. ctrl.template = response;
  25076. // Note: This will also link all children of ng-include that were contained in the original
  25077. // html. If that content contains controllers, ... they could pollute/change the scope.
  25078. // However, using ng-include on an element with additional content does not make sense...
  25079. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25080. // function is called before linking the content, which would apply child
  25081. // directives to non existing elements.
  25082. var clone = $transclude(newScope, function(clone) {
  25083. cleanupLastIncludeContent();
  25084. $animate.enter(clone, null, $element).done(afterAnimation);
  25085. });
  25086. currentScope = newScope;
  25087. currentElement = clone;
  25088. currentScope.$emit('$includeContentLoaded', src);
  25089. scope.$eval(onloadExp);
  25090. }, function() {
  25091. if (scope.$$destroyed) return;
  25092. if (thisChangeId === changeCounter) {
  25093. cleanupLastIncludeContent();
  25094. scope.$emit('$includeContentError', src);
  25095. }
  25096. });
  25097. scope.$emit('$includeContentRequested', src);
  25098. } else {
  25099. cleanupLastIncludeContent();
  25100. ctrl.template = null;
  25101. }
  25102. });
  25103. };
  25104. }
  25105. };
  25106. }];
  25107. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25108. // It will replace and compile the content of the element with the loaded template.
  25109. // We need this directive so that the element content is already filled when
  25110. // the link function of another directive on the same element as ngInclude
  25111. // is called.
  25112. var ngIncludeFillContentDirective = ['$compile',
  25113. function($compile) {
  25114. return {
  25115. restrict: 'ECA',
  25116. priority: -400,
  25117. require: 'ngInclude',
  25118. link: function(scope, $element, $attr, ctrl) {
  25119. if (toString.call($element[0]).match(/SVG/)) {
  25120. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25121. // support innerHTML, so detect this here and try to generate the contents
  25122. // specially.
  25123. $element.empty();
  25124. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25125. function namespaceAdaptedClone(clone) {
  25126. $element.append(clone);
  25127. }, {futureParentElement: $element});
  25128. return;
  25129. }
  25130. $element.html(ctrl.template);
  25131. $compile($element.contents())(scope);
  25132. }
  25133. };
  25134. }];
  25135. /**
  25136. * @ngdoc directive
  25137. * @name ngInit
  25138. * @restrict AC
  25139. *
  25140. * @description
  25141. * The `ngInit` directive allows you to evaluate an expression in the
  25142. * current scope.
  25143. *
  25144. * <div class="alert alert-danger">
  25145. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25146. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25147. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25148. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25149. * rather than `ngInit` to initialize values on a scope.
  25150. * </div>
  25151. *
  25152. * <div class="alert alert-warning">
  25153. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25154. * sure you have parentheses to ensure correct operator precedence:
  25155. * <pre class="prettyprint">
  25156. * `<div ng-init="test1 = ($index | toString)"></div>`
  25157. * </pre>
  25158. * </div>
  25159. *
  25160. * @priority 450
  25161. *
  25162. * @element ANY
  25163. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25164. *
  25165. * @example
  25166. <example module="initExample" name="ng-init">
  25167. <file name="index.html">
  25168. <script>
  25169. angular.module('initExample', [])
  25170. .controller('ExampleController', ['$scope', function($scope) {
  25171. $scope.list = [['a', 'b'], ['c', 'd']];
  25172. }]);
  25173. </script>
  25174. <div ng-controller="ExampleController">
  25175. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25176. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25177. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25178. </div>
  25179. </div>
  25180. </div>
  25181. </file>
  25182. <file name="protractor.js" type="protractor">
  25183. it('should alias index positions', function() {
  25184. var elements = element.all(by.css('.example-init'));
  25185. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25186. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25187. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25188. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25189. });
  25190. </file>
  25191. </example>
  25192. */
  25193. var ngInitDirective = ngDirective({
  25194. priority: 450,
  25195. compile: function() {
  25196. return {
  25197. pre: function(scope, element, attrs) {
  25198. scope.$eval(attrs.ngInit);
  25199. }
  25200. };
  25201. }
  25202. });
  25203. /**
  25204. * @ngdoc directive
  25205. * @name ngList
  25206. *
  25207. * @description
  25208. * Text input that converts between a delimited string and an array of strings. The default
  25209. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25210. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25211. *
  25212. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25213. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25214. * list item is respected. This implies that the user of the directive is responsible for
  25215. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25216. * tab or newline character.
  25217. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25218. * when joining the list items back together) and whitespace around each list item is stripped
  25219. * before it is added to the model.
  25220. *
  25221. * ### Example with Validation
  25222. *
  25223. * <example name="ngList-directive" module="listExample">
  25224. * <file name="app.js">
  25225. * angular.module('listExample', [])
  25226. * .controller('ExampleController', ['$scope', function($scope) {
  25227. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25228. * }]);
  25229. * </file>
  25230. * <file name="index.html">
  25231. * <form name="myForm" ng-controller="ExampleController">
  25232. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25233. * <span role="alert">
  25234. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25235. * Required!</span>
  25236. * </span>
  25237. * <br>
  25238. * <tt>names = {{names}}</tt><br/>
  25239. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25240. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25241. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25242. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25243. * </form>
  25244. * </file>
  25245. * <file name="protractor.js" type="protractor">
  25246. * var listInput = element(by.model('names'));
  25247. * var names = element(by.exactBinding('names'));
  25248. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25249. * var error = element(by.css('span.error'));
  25250. *
  25251. * it('should initialize to model', function() {
  25252. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25253. * expect(valid.getText()).toContain('true');
  25254. * expect(error.getCssValue('display')).toBe('none');
  25255. * });
  25256. *
  25257. * it('should be invalid if empty', function() {
  25258. * listInput.clear();
  25259. * listInput.sendKeys('');
  25260. *
  25261. * expect(names.getText()).toContain('');
  25262. * expect(valid.getText()).toContain('false');
  25263. * expect(error.getCssValue('display')).not.toBe('none');
  25264. * });
  25265. * </file>
  25266. * </example>
  25267. *
  25268. * ### Example - splitting on newline
  25269. * <example name="ngList-directive-newlines">
  25270. * <file name="index.html">
  25271. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25272. * <pre>{{ list | json }}</pre>
  25273. * </file>
  25274. * <file name="protractor.js" type="protractor">
  25275. * it("should split the text by newlines", function() {
  25276. * var listInput = element(by.model('list'));
  25277. * var output = element(by.binding('list | json'));
  25278. * listInput.sendKeys('abc\ndef\nghi');
  25279. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25280. * });
  25281. * </file>
  25282. * </example>
  25283. *
  25284. * @element input
  25285. * @param {string=} ngList optional delimiter that should be used to split the value.
  25286. */
  25287. var ngListDirective = function() {
  25288. return {
  25289. restrict: 'A',
  25290. priority: 100,
  25291. require: 'ngModel',
  25292. link: function(scope, element, attr, ctrl) {
  25293. var ngList = attr.ngList || ', ';
  25294. var trimValues = attr.ngTrim !== 'false';
  25295. var separator = trimValues ? trim(ngList) : ngList;
  25296. var parse = function(viewValue) {
  25297. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25298. if (isUndefined(viewValue)) return;
  25299. var list = [];
  25300. if (viewValue) {
  25301. forEach(viewValue.split(separator), function(value) {
  25302. if (value) list.push(trimValues ? trim(value) : value);
  25303. });
  25304. }
  25305. return list;
  25306. };
  25307. ctrl.$parsers.push(parse);
  25308. ctrl.$formatters.push(function(value) {
  25309. if (isArray(value)) {
  25310. return value.join(ngList);
  25311. }
  25312. return undefined;
  25313. });
  25314. // Override the standard $isEmpty because an empty array means the input is empty.
  25315. ctrl.$isEmpty = function(value) {
  25316. return !value || !value.length;
  25317. };
  25318. }
  25319. };
  25320. };
  25321. /* global VALID_CLASS: true,
  25322. INVALID_CLASS: true,
  25323. PRISTINE_CLASS: true,
  25324. DIRTY_CLASS: true,
  25325. UNTOUCHED_CLASS: true,
  25326. TOUCHED_CLASS: true,
  25327. PENDING_CLASS: true,
  25328. addSetValidityMethod: true,
  25329. setupValidity: true,
  25330. defaultModelOptions: false
  25331. */
  25332. var VALID_CLASS = 'ng-valid',
  25333. INVALID_CLASS = 'ng-invalid',
  25334. PRISTINE_CLASS = 'ng-pristine',
  25335. DIRTY_CLASS = 'ng-dirty',
  25336. UNTOUCHED_CLASS = 'ng-untouched',
  25337. TOUCHED_CLASS = 'ng-touched',
  25338. EMPTY_CLASS = 'ng-empty',
  25339. NOT_EMPTY_CLASS = 'ng-not-empty';
  25340. var ngModelMinErr = minErr('ngModel');
  25341. /**
  25342. * @ngdoc type
  25343. * @name ngModel.NgModelController
  25344. *
  25345. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25346. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25347. * is set.
  25348. * @property {*} $modelValue The value in the model that the control is bound to.
  25349. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25350. the control reads value from the DOM. The functions are called in array order, each passing
  25351. its return value through to the next. The last return value is forwarded to the
  25352. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25353. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25354. `$viewValue`}.
  25355. Returning `undefined` from a parser means a parse error occurred. In that case,
  25356. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25357. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25358. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25359. *
  25360. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25361. the model value changes. The functions are called in reverse array order, each passing the value through to the
  25362. next. The last return value is used as the actual DOM value.
  25363. Used to format / convert values for display in the control.
  25364. * ```js
  25365. * function formatter(value) {
  25366. * if (value) {
  25367. * return value.toUpperCase();
  25368. * }
  25369. * }
  25370. * ngModel.$formatters.push(formatter);
  25371. * ```
  25372. *
  25373. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25374. * whenever the model value changes. The key value within the object refers to the name of the
  25375. * validator while the function refers to the validation operation. The validation operation is
  25376. * provided with the model value as an argument and must return a true or false value depending
  25377. * on the response of that validation.
  25378. *
  25379. * ```js
  25380. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25381. * var value = modelValue || viewValue;
  25382. * return /[0-9]+/.test(value) &&
  25383. * /[a-z]+/.test(value) &&
  25384. * /[A-Z]+/.test(value) &&
  25385. * /\W+/.test(value);
  25386. * };
  25387. * ```
  25388. *
  25389. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25390. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25391. * is expected to return a promise when it is run during the model validation process. Once the promise
  25392. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25393. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25394. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25395. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25396. * will only run once all synchronous validators have passed.
  25397. *
  25398. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25399. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25400. *
  25401. * ```js
  25402. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25403. * var value = modelValue || viewValue;
  25404. *
  25405. * // Lookup user by username
  25406. * return $http.get('/api/users/' + value).
  25407. * then(function resolved() {
  25408. * //username exists, this means validation fails
  25409. * return $q.reject('exists');
  25410. * }, function rejected() {
  25411. * //username does not exist, therefore this validation passes
  25412. * return true;
  25413. * });
  25414. * };
  25415. * ```
  25416. *
  25417. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25418. * view value has changed. It is called with no arguments, and its return value is ignored.
  25419. * This can be used in place of additional $watches against the model value.
  25420. *
  25421. * @property {Object} $error An object hash with all failing validator ids as keys.
  25422. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25423. *
  25424. * @property {boolean} $untouched True if control has not lost focus yet.
  25425. * @property {boolean} $touched True if control has lost focus.
  25426. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25427. * @property {boolean} $dirty True if user has already interacted with the control.
  25428. * @property {boolean} $valid True if there is no error.
  25429. * @property {boolean} $invalid True if at least one error on the control.
  25430. * @property {string} $name The name attribute of the control.
  25431. *
  25432. * @description
  25433. *
  25434. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  25435. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  25436. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  25437. * listening to DOM events.
  25438. * Such DOM related logic should be provided by other directives which make use of
  25439. * `NgModelController` for data-binding to control elements.
  25440. * Angular provides this DOM logic for most {@link input `input`} elements.
  25441. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  25442. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  25443. *
  25444. * @example
  25445. * ### Custom Control Example
  25446. * This example shows how to use `NgModelController` with a custom control to achieve
  25447. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  25448. * collaborate together to achieve the desired result.
  25449. *
  25450. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  25451. * contents be edited in place by the user.
  25452. *
  25453. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  25454. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  25455. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  25456. * that content using the `$sce` service.
  25457. *
  25458. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  25459. <file name="style.css">
  25460. [contenteditable] {
  25461. border: 1px solid black;
  25462. background-color: white;
  25463. min-height: 20px;
  25464. }
  25465. .ng-invalid {
  25466. border: 1px solid red;
  25467. }
  25468. </file>
  25469. <file name="script.js">
  25470. angular.module('customControl', ['ngSanitize']).
  25471. directive('contenteditable', ['$sce', function($sce) {
  25472. return {
  25473. restrict: 'A', // only activate on element attribute
  25474. require: '?ngModel', // get a hold of NgModelController
  25475. link: function(scope, element, attrs, ngModel) {
  25476. if (!ngModel) return; // do nothing if no ng-model
  25477. // Specify how UI should be updated
  25478. ngModel.$render = function() {
  25479. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  25480. };
  25481. // Listen for change events to enable binding
  25482. element.on('blur keyup change', function() {
  25483. scope.$evalAsync(read);
  25484. });
  25485. read(); // initialize
  25486. // Write data to the model
  25487. function read() {
  25488. var html = element.html();
  25489. // When we clear the content editable the browser leaves a <br> behind
  25490. // If strip-br attribute is provided then we strip this out
  25491. if (attrs.stripBr && html === '<br>') {
  25492. html = '';
  25493. }
  25494. ngModel.$setViewValue(html);
  25495. }
  25496. }
  25497. };
  25498. }]);
  25499. </file>
  25500. <file name="index.html">
  25501. <form name="myForm">
  25502. <div contenteditable
  25503. name="myWidget" ng-model="userContent"
  25504. strip-br="true"
  25505. required>Change me!</div>
  25506. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  25507. <hr>
  25508. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  25509. </form>
  25510. </file>
  25511. <file name="protractor.js" type="protractor">
  25512. it('should data-bind and become invalid', function() {
  25513. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  25514. // SafariDriver can't handle contenteditable
  25515. // and Firefox driver can't clear contenteditables very well
  25516. return;
  25517. }
  25518. var contentEditable = element(by.css('[contenteditable]'));
  25519. var content = 'Change me!';
  25520. expect(contentEditable.getText()).toEqual(content);
  25521. contentEditable.clear();
  25522. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  25523. expect(contentEditable.getText()).toEqual('');
  25524. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  25525. });
  25526. </file>
  25527. * </example>
  25528. *
  25529. *
  25530. */
  25531. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  25532. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  25533. this.$viewValue = Number.NaN;
  25534. this.$modelValue = Number.NaN;
  25535. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  25536. this.$validators = {};
  25537. this.$asyncValidators = {};
  25538. this.$parsers = [];
  25539. this.$formatters = [];
  25540. this.$viewChangeListeners = [];
  25541. this.$untouched = true;
  25542. this.$touched = false;
  25543. this.$pristine = true;
  25544. this.$dirty = false;
  25545. this.$valid = true;
  25546. this.$invalid = false;
  25547. this.$error = {}; // keep invalid keys here
  25548. this.$$success = {}; // keep valid keys here
  25549. this.$pending = undefined; // keep pending keys here
  25550. this.$name = $interpolate($attr.name || '', false)($scope);
  25551. this.$$parentForm = nullFormCtrl;
  25552. this.$options = defaultModelOptions;
  25553. this.$$parsedNgModel = $parse($attr.ngModel);
  25554. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  25555. this.$$ngModelGet = this.$$parsedNgModel;
  25556. this.$$ngModelSet = this.$$parsedNgModelAssign;
  25557. this.$$pendingDebounce = null;
  25558. this.$$parserValid = undefined;
  25559. this.$$currentValidationRunId = 0;
  25560. this.$$scope = $scope;
  25561. this.$$attr = $attr;
  25562. this.$$element = $element;
  25563. this.$$animate = $animate;
  25564. this.$$timeout = $timeout;
  25565. this.$$parse = $parse;
  25566. this.$$q = $q;
  25567. this.$$exceptionHandler = $exceptionHandler;
  25568. setupValidity(this);
  25569. setupModelWatcher(this);
  25570. }
  25571. NgModelController.prototype = {
  25572. $$initGetterSetters: function() {
  25573. if (this.$options.getOption('getterSetter')) {
  25574. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  25575. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  25576. this.$$ngModelGet = function($scope) {
  25577. var modelValue = this.$$parsedNgModel($scope);
  25578. if (isFunction(modelValue)) {
  25579. modelValue = invokeModelGetter($scope);
  25580. }
  25581. return modelValue;
  25582. };
  25583. this.$$ngModelSet = function($scope, newValue) {
  25584. if (isFunction(this.$$parsedNgModel($scope))) {
  25585. invokeModelSetter($scope, {$$$p: newValue});
  25586. } else {
  25587. this.$$parsedNgModelAssign($scope, newValue);
  25588. }
  25589. };
  25590. } else if (!this.$$parsedNgModel.assign) {
  25591. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  25592. this.$$attr.ngModel, startingTag(this.$$element));
  25593. }
  25594. },
  25595. /**
  25596. * @ngdoc method
  25597. * @name ngModel.NgModelController#$render
  25598. *
  25599. * @description
  25600. * Called when the view needs to be updated. It is expected that the user of the ng-model
  25601. * directive will implement this method.
  25602. *
  25603. * The `$render()` method is invoked in the following situations:
  25604. *
  25605. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  25606. * committed value then `$render()` is called to update the input control.
  25607. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  25608. * the `$viewValue` are different from last time.
  25609. *
  25610. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  25611. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  25612. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  25613. * invoked if you only change a property on the objects.
  25614. */
  25615. $render: noop,
  25616. /**
  25617. * @ngdoc method
  25618. * @name ngModel.NgModelController#$isEmpty
  25619. *
  25620. * @description
  25621. * This is called when we need to determine if the value of an input is empty.
  25622. *
  25623. * For instance, the required directive does this to work out if the input has data or not.
  25624. *
  25625. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  25626. *
  25627. * You can override this for input directives whose concept of being empty is different from the
  25628. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  25629. * implies empty.
  25630. *
  25631. * @param {*} value The value of the input to check for emptiness.
  25632. * @returns {boolean} True if `value` is "empty".
  25633. */
  25634. $isEmpty: function(value) {
  25635. // eslint-disable-next-line no-self-compare
  25636. return isUndefined(value) || value === '' || value === null || value !== value;
  25637. },
  25638. $$updateEmptyClasses: function(value) {
  25639. if (this.$isEmpty(value)) {
  25640. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  25641. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  25642. } else {
  25643. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  25644. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  25645. }
  25646. },
  25647. /**
  25648. * @ngdoc method
  25649. * @name ngModel.NgModelController#$setPristine
  25650. *
  25651. * @description
  25652. * Sets the control to its pristine state.
  25653. *
  25654. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  25655. * state (`ng-pristine` class). A model is considered to be pristine when the control
  25656. * has not been changed from when first compiled.
  25657. */
  25658. $setPristine: function() {
  25659. this.$dirty = false;
  25660. this.$pristine = true;
  25661. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  25662. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  25663. },
  25664. /**
  25665. * @ngdoc method
  25666. * @name ngModel.NgModelController#$setDirty
  25667. *
  25668. * @description
  25669. * Sets the control to its dirty state.
  25670. *
  25671. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  25672. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  25673. * from when first compiled.
  25674. */
  25675. $setDirty: function() {
  25676. this.$dirty = true;
  25677. this.$pristine = false;
  25678. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  25679. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  25680. this.$$parentForm.$setDirty();
  25681. },
  25682. /**
  25683. * @ngdoc method
  25684. * @name ngModel.NgModelController#$setUntouched
  25685. *
  25686. * @description
  25687. * Sets the control to its untouched state.
  25688. *
  25689. * This method can be called to remove the `ng-touched` class and set the control to its
  25690. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  25691. * by default, however this function can be used to restore that state if the model has
  25692. * already been touched by the user.
  25693. */
  25694. $setUntouched: function() {
  25695. this.$touched = false;
  25696. this.$untouched = true;
  25697. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  25698. },
  25699. /**
  25700. * @ngdoc method
  25701. * @name ngModel.NgModelController#$setTouched
  25702. *
  25703. * @description
  25704. * Sets the control to its touched state.
  25705. *
  25706. * This method can be called to remove the `ng-untouched` class and set the control to its
  25707. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  25708. * first focused the control element and then shifted focus away from the control (blur event).
  25709. */
  25710. $setTouched: function() {
  25711. this.$touched = true;
  25712. this.$untouched = false;
  25713. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  25714. },
  25715. /**
  25716. * @ngdoc method
  25717. * @name ngModel.NgModelController#$rollbackViewValue
  25718. *
  25719. * @description
  25720. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  25721. * which may be caused by a pending debounced event or because the input is waiting for some
  25722. * future event.
  25723. *
  25724. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  25725. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  25726. * sync with the ngModel's `$modelValue`.
  25727. *
  25728. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  25729. * and reset the input to the last committed view value.
  25730. *
  25731. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  25732. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25733. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25734. *
  25735. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25736. * input which may have such events pending. This is important in order to make sure that the
  25737. * input field will be updated with the new model value and any pending operations are cancelled.
  25738. *
  25739. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25740. * <file name="app.js">
  25741. * angular.module('cancel-update-example', [])
  25742. *
  25743. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25744. * $scope.model = {value1: '', value2: ''};
  25745. *
  25746. * $scope.setEmpty = function(e, value, rollback) {
  25747. * if (e.keyCode === 27) {
  25748. * e.preventDefault();
  25749. * if (rollback) {
  25750. * $scope.myForm[value].$rollbackViewValue();
  25751. * }
  25752. * $scope.model[value] = '';
  25753. * }
  25754. * };
  25755. * }]);
  25756. * </file>
  25757. * <file name="index.html">
  25758. * <div ng-controller="CancelUpdateController">
  25759. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  25760. * empty them. Follow these steps and observe the difference:</p>
  25761. * <ol>
  25762. * <li>Type something in the input. You will see that the model is not yet updated</li>
  25763. * <li>Press the Escape key.
  25764. * <ol>
  25765. * <li> In the first example, nothing happens, because the model is already '', and no
  25766. * update is detected. If you blur the input, the model will be set to the current view.
  25767. * </li>
  25768. * <li> In the second example, the pending update is cancelled, and the input is set back
  25769. * to the last committed view value (''). Blurring the input does nothing.
  25770. * </li>
  25771. * </ol>
  25772. * </li>
  25773. * </ol>
  25774. *
  25775. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  25776. * <div>
  25777. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  25778. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  25779. * ng-keydown="setEmpty($event, 'value1')">
  25780. * value1: "{{ model.value1 }}"
  25781. * </div>
  25782. *
  25783. * <div>
  25784. * <p id="inputDescription2">With $rollbackViewValue():</p>
  25785. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  25786. * ng-keydown="setEmpty($event, 'value2', true)">
  25787. * value2: "{{ model.value2 }}"
  25788. * </div>
  25789. * </form>
  25790. * </div>
  25791. * </file>
  25792. <file name="style.css">
  25793. div {
  25794. display: table-cell;
  25795. }
  25796. div:nth-child(1) {
  25797. padding-right: 30px;
  25798. }
  25799. </file>
  25800. * </example>
  25801. */
  25802. $rollbackViewValue: function() {
  25803. this.$$timeout.cancel(this.$$pendingDebounce);
  25804. this.$viewValue = this.$$lastCommittedViewValue;
  25805. this.$render();
  25806. },
  25807. /**
  25808. * @ngdoc method
  25809. * @name ngModel.NgModelController#$validate
  25810. *
  25811. * @description
  25812. * Runs each of the registered validators (first synchronous validators and then
  25813. * asynchronous validators).
  25814. * If the validity changes to invalid, the model will be set to `undefined`,
  25815. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  25816. * If the validity changes to valid, it will set the model to the last available valid
  25817. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  25818. */
  25819. $validate: function() {
  25820. // ignore $validate before model is initialized
  25821. if (isNumberNaN(this.$modelValue)) {
  25822. return;
  25823. }
  25824. var viewValue = this.$$lastCommittedViewValue;
  25825. // Note: we use the $$rawModelValue as $modelValue might have been
  25826. // set to undefined during a view -> model update that found validation
  25827. // errors. We can't parse the view here, since that could change
  25828. // the model although neither viewValue nor the model on the scope changed
  25829. var modelValue = this.$$rawModelValue;
  25830. var prevValid = this.$valid;
  25831. var prevModelValue = this.$modelValue;
  25832. var allowInvalid = this.$options.getOption('allowInvalid');
  25833. var that = this;
  25834. this.$$runValidators(modelValue, viewValue, function(allValid) {
  25835. // If there was no change in validity, don't update the model
  25836. // This prevents changing an invalid modelValue to undefined
  25837. if (!allowInvalid && prevValid !== allValid) {
  25838. // Note: Don't check this.$valid here, as we could have
  25839. // external validators (e.g. calculated on the server),
  25840. // that just call $setValidity and need the model value
  25841. // to calculate their validity.
  25842. that.$modelValue = allValid ? modelValue : undefined;
  25843. if (that.$modelValue !== prevModelValue) {
  25844. that.$$writeModelToScope();
  25845. }
  25846. }
  25847. });
  25848. },
  25849. $$runValidators: function(modelValue, viewValue, doneCallback) {
  25850. this.$$currentValidationRunId++;
  25851. var localValidationRunId = this.$$currentValidationRunId;
  25852. var that = this;
  25853. // check parser error
  25854. if (!processParseErrors()) {
  25855. validationDone(false);
  25856. return;
  25857. }
  25858. if (!processSyncValidators()) {
  25859. validationDone(false);
  25860. return;
  25861. }
  25862. processAsyncValidators();
  25863. function processParseErrors() {
  25864. var errorKey = that.$$parserName || 'parse';
  25865. if (isUndefined(that.$$parserValid)) {
  25866. setValidity(errorKey, null);
  25867. } else {
  25868. if (!that.$$parserValid) {
  25869. forEach(that.$validators, function(v, name) {
  25870. setValidity(name, null);
  25871. });
  25872. forEach(that.$asyncValidators, function(v, name) {
  25873. setValidity(name, null);
  25874. });
  25875. }
  25876. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  25877. setValidity(errorKey, that.$$parserValid);
  25878. return that.$$parserValid;
  25879. }
  25880. return true;
  25881. }
  25882. function processSyncValidators() {
  25883. var syncValidatorsValid = true;
  25884. forEach(that.$validators, function(validator, name) {
  25885. var result = Boolean(validator(modelValue, viewValue));
  25886. syncValidatorsValid = syncValidatorsValid && result;
  25887. setValidity(name, result);
  25888. });
  25889. if (!syncValidatorsValid) {
  25890. forEach(that.$asyncValidators, function(v, name) {
  25891. setValidity(name, null);
  25892. });
  25893. return false;
  25894. }
  25895. return true;
  25896. }
  25897. function processAsyncValidators() {
  25898. var validatorPromises = [];
  25899. var allValid = true;
  25900. forEach(that.$asyncValidators, function(validator, name) {
  25901. var promise = validator(modelValue, viewValue);
  25902. if (!isPromiseLike(promise)) {
  25903. throw ngModelMinErr('nopromise',
  25904. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  25905. }
  25906. setValidity(name, undefined);
  25907. validatorPromises.push(promise.then(function() {
  25908. setValidity(name, true);
  25909. }, function() {
  25910. allValid = false;
  25911. setValidity(name, false);
  25912. }));
  25913. });
  25914. if (!validatorPromises.length) {
  25915. validationDone(true);
  25916. } else {
  25917. that.$$q.all(validatorPromises).then(function() {
  25918. validationDone(allValid);
  25919. }, noop);
  25920. }
  25921. }
  25922. function setValidity(name, isValid) {
  25923. if (localValidationRunId === that.$$currentValidationRunId) {
  25924. that.$setValidity(name, isValid);
  25925. }
  25926. }
  25927. function validationDone(allValid) {
  25928. if (localValidationRunId === that.$$currentValidationRunId) {
  25929. doneCallback(allValid);
  25930. }
  25931. }
  25932. },
  25933. /**
  25934. * @ngdoc method
  25935. * @name ngModel.NgModelController#$commitViewValue
  25936. *
  25937. * @description
  25938. * Commit a pending update to the `$modelValue`.
  25939. *
  25940. * Updates may be pending by a debounced event or because the input is waiting for a some future
  25941. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  25942. * usually handles calling this in response to input events.
  25943. */
  25944. $commitViewValue: function() {
  25945. var viewValue = this.$viewValue;
  25946. this.$$timeout.cancel(this.$$pendingDebounce);
  25947. // If the view value has not changed then we should just exit, except in the case where there is
  25948. // a native validator on the element. In this case the validation state may have changed even though
  25949. // the viewValue has stayed empty.
  25950. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  25951. return;
  25952. }
  25953. this.$$updateEmptyClasses(viewValue);
  25954. this.$$lastCommittedViewValue = viewValue;
  25955. // change to dirty
  25956. if (this.$pristine) {
  25957. this.$setDirty();
  25958. }
  25959. this.$$parseAndValidate();
  25960. },
  25961. $$parseAndValidate: function() {
  25962. var viewValue = this.$$lastCommittedViewValue;
  25963. var modelValue = viewValue;
  25964. var that = this;
  25965. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  25966. if (this.$$parserValid) {
  25967. for (var i = 0; i < this.$parsers.length; i++) {
  25968. modelValue = this.$parsers[i](modelValue);
  25969. if (isUndefined(modelValue)) {
  25970. this.$$parserValid = false;
  25971. break;
  25972. }
  25973. }
  25974. }
  25975. if (isNumberNaN(this.$modelValue)) {
  25976. // this.$modelValue has not been touched yet...
  25977. this.$modelValue = this.$$ngModelGet(this.$$scope);
  25978. }
  25979. var prevModelValue = this.$modelValue;
  25980. var allowInvalid = this.$options.getOption('allowInvalid');
  25981. this.$$rawModelValue = modelValue;
  25982. if (allowInvalid) {
  25983. this.$modelValue = modelValue;
  25984. writeToModelIfNeeded();
  25985. }
  25986. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  25987. // This can happen if e.g. $setViewValue is called from inside a parser
  25988. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  25989. if (!allowInvalid) {
  25990. // Note: Don't check this.$valid here, as we could have
  25991. // external validators (e.g. calculated on the server),
  25992. // that just call $setValidity and need the model value
  25993. // to calculate their validity.
  25994. that.$modelValue = allValid ? modelValue : undefined;
  25995. writeToModelIfNeeded();
  25996. }
  25997. });
  25998. function writeToModelIfNeeded() {
  25999. if (that.$modelValue !== prevModelValue) {
  26000. that.$$writeModelToScope();
  26001. }
  26002. }
  26003. },
  26004. $$writeModelToScope: function() {
  26005. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26006. forEach(this.$viewChangeListeners, function(listener) {
  26007. try {
  26008. listener();
  26009. } catch (e) {
  26010. // eslint-disable-next-line no-invalid-this
  26011. this.$$exceptionHandler(e);
  26012. }
  26013. }, this);
  26014. },
  26015. /**
  26016. * @ngdoc method
  26017. * @name ngModel.NgModelController#$setViewValue
  26018. *
  26019. * @description
  26020. * Update the view value.
  26021. *
  26022. * This method should be called when a control wants to change the view value; typically,
  26023. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26024. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26025. * calls it when an option is selected.
  26026. *
  26027. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26028. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26029. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  26030. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  26031. * in the `$viewChangeListeners` list, are called.
  26032. *
  26033. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26034. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26035. * `updateOn` events is triggered on the DOM element.
  26036. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26037. * directive is used with a custom debounce for this particular event.
  26038. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26039. * is specified, once the timer runs out.
  26040. *
  26041. * When used with standard inputs, the view value will always be a string (which is in some cases
  26042. * parsed into another type, such as a `Date` object for `input[date]`.)
  26043. * However, custom controls might also pass objects to this method. In this case, we should make
  26044. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26045. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26046. * the property of the object then ngModel will not realize that the object has changed and
  26047. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26048. * not change properties of the copy once it has been passed to `$setViewValue`.
  26049. * Otherwise you may cause the model value on the scope to change incorrectly.
  26050. *
  26051. * <div class="alert alert-info">
  26052. * In any case, the value passed to the method should always reflect the current value
  26053. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26054. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26055. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26056. * the control's DOM value in any way. If we want to change the control's DOM value
  26057. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26058. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26059. * to update the DOM, and finally call `$validate` on it.
  26060. * </div>
  26061. *
  26062. * @param {*} value value from the view.
  26063. * @param {string} trigger Event that triggered the update.
  26064. */
  26065. $setViewValue: function(value, trigger) {
  26066. this.$viewValue = value;
  26067. if (this.$options.getOption('updateOnDefault')) {
  26068. this.$$debounceViewValueCommit(trigger);
  26069. }
  26070. },
  26071. $$debounceViewValueCommit: function(trigger) {
  26072. var debounceDelay = this.$options.getOption('debounce');
  26073. if (isNumber(debounceDelay[trigger])) {
  26074. debounceDelay = debounceDelay[trigger];
  26075. } else if (isNumber(debounceDelay['default'])) {
  26076. debounceDelay = debounceDelay['default'];
  26077. }
  26078. this.$$timeout.cancel(this.$$pendingDebounce);
  26079. var that = this;
  26080. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26081. this.$$pendingDebounce = this.$$timeout(function() {
  26082. that.$commitViewValue();
  26083. }, debounceDelay);
  26084. } else if (this.$$scope.$root.$$phase) {
  26085. this.$commitViewValue();
  26086. } else {
  26087. this.$$scope.$apply(function() {
  26088. that.$commitViewValue();
  26089. });
  26090. }
  26091. }
  26092. };
  26093. function setupModelWatcher(ctrl) {
  26094. // model -> value
  26095. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26096. // 1. scope value is 'a'
  26097. // 2. user enters 'b'
  26098. // 3. ng-change kicks in and reverts scope value to 'a'
  26099. // -> scope value did not change since the last digest as
  26100. // ng-change executes in apply phase
  26101. // 4. view should be changed back to 'a'
  26102. ctrl.$$scope.$watch(function ngModelWatch() {
  26103. var modelValue = ctrl.$$ngModelGet(ctrl.$$scope);
  26104. // if scope model value and ngModel value are out of sync
  26105. // TODO(perf): why not move this to the action fn?
  26106. if (modelValue !== ctrl.$modelValue &&
  26107. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26108. // eslint-disable-next-line no-self-compare
  26109. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26110. ) {
  26111. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26112. ctrl.$$parserValid = undefined;
  26113. var formatters = ctrl.$formatters,
  26114. idx = formatters.length;
  26115. var viewValue = modelValue;
  26116. while (idx--) {
  26117. viewValue = formatters[idx](viewValue);
  26118. }
  26119. if (ctrl.$viewValue !== viewValue) {
  26120. ctrl.$$updateEmptyClasses(viewValue);
  26121. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26122. ctrl.$render();
  26123. // It is possible that model and view value have been updated during render
  26124. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26125. }
  26126. }
  26127. return modelValue;
  26128. });
  26129. }
  26130. /**
  26131. * @ngdoc method
  26132. * @name ngModel.NgModelController#$setValidity
  26133. *
  26134. * @description
  26135. * Change the validity state, and notify the form.
  26136. *
  26137. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26138. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26139. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26140. *
  26141. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26142. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26143. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26144. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26145. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26146. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  26147. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26148. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26149. * Skipped is used by Angular when validators do not run because of parse errors and
  26150. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26151. */
  26152. addSetValidityMethod({
  26153. clazz: NgModelController,
  26154. set: function(object, property) {
  26155. object[property] = true;
  26156. },
  26157. unset: function(object, property) {
  26158. delete object[property];
  26159. }
  26160. });
  26161. /**
  26162. * @ngdoc directive
  26163. * @name ngModel
  26164. *
  26165. * @element input
  26166. * @priority 1
  26167. *
  26168. * @description
  26169. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26170. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26171. * which is created and exposed by this directive.
  26172. *
  26173. * `ngModel` is responsible for:
  26174. *
  26175. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26176. * require.
  26177. * - Providing validation behavior (i.e. required, number, email, url).
  26178. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26179. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26180. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26181. * - Registering the control with its parent {@link ng.directive:form form}.
  26182. *
  26183. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26184. * current scope. If the property doesn't already exist on this scope, it will be created
  26185. * implicitly and added to the scope.
  26186. *
  26187. * For best practices on using `ngModel`, see:
  26188. *
  26189. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26190. *
  26191. * For basic examples, how to use `ngModel`, see:
  26192. *
  26193. * - {@link ng.directive:input input}
  26194. * - {@link input[text] text}
  26195. * - {@link input[checkbox] checkbox}
  26196. * - {@link input[radio] radio}
  26197. * - {@link input[number] number}
  26198. * - {@link input[email] email}
  26199. * - {@link input[url] url}
  26200. * - {@link input[date] date}
  26201. * - {@link input[datetime-local] datetime-local}
  26202. * - {@link input[time] time}
  26203. * - {@link input[month] month}
  26204. * - {@link input[week] week}
  26205. * - {@link ng.directive:select select}
  26206. * - {@link ng.directive:textarea textarea}
  26207. *
  26208. * # Complex Models (objects or collections)
  26209. *
  26210. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26211. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26212. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26213. *
  26214. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26215. *
  26216. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26217. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26218. * if the select is given the `multiple` attribute.
  26219. *
  26220. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26221. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26222. * not trigger a re-rendering of the model.
  26223. *
  26224. * # CSS classes
  26225. * The following CSS classes are added and removed on the associated input/select/textarea element
  26226. * depending on the validity of the model.
  26227. *
  26228. * - `ng-valid`: the model is valid
  26229. * - `ng-invalid`: the model is invalid
  26230. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26231. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26232. * - `ng-pristine`: the control hasn't been interacted with yet
  26233. * - `ng-dirty`: the control has been interacted with
  26234. * - `ng-touched`: the control has been blurred
  26235. * - `ng-untouched`: the control hasn't been blurred
  26236. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26237. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26238. * by the {@link ngModel.NgModelController#$isEmpty} method
  26239. * - `ng-not-empty`: the view contains a non-empty value
  26240. *
  26241. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26242. *
  26243. * ## Animation Hooks
  26244. *
  26245. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26246. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26247. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26248. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26249. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26250. *
  26251. * The following example shows a simple way to utilize CSS transitions to style an input element
  26252. * that has been rendered as invalid after it has been validated:
  26253. *
  26254. * <pre>
  26255. * //be sure to include ngAnimate as a module to hook into more
  26256. * //advanced animations
  26257. * .my-input {
  26258. * transition:0.5s linear all;
  26259. * background: white;
  26260. * }
  26261. * .my-input.ng-invalid {
  26262. * background: red;
  26263. * color:white;
  26264. * }
  26265. * </pre>
  26266. *
  26267. * @example
  26268. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26269. <file name="index.html">
  26270. <script>
  26271. angular.module('inputExample', [])
  26272. .controller('ExampleController', ['$scope', function($scope) {
  26273. $scope.val = '1';
  26274. }]);
  26275. </script>
  26276. <style>
  26277. .my-input {
  26278. transition:all linear 0.5s;
  26279. background: transparent;
  26280. }
  26281. .my-input.ng-invalid {
  26282. color:white;
  26283. background: red;
  26284. }
  26285. </style>
  26286. <p id="inputDescription">
  26287. Update input to see transitions when valid/invalid.
  26288. Integer is a valid value.
  26289. </p>
  26290. <form name="testForm" ng-controller="ExampleController">
  26291. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26292. aria-describedby="inputDescription" />
  26293. </form>
  26294. </file>
  26295. * </example>
  26296. *
  26297. * ## Binding to a getter/setter
  26298. *
  26299. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26300. * function that returns a representation of the model when called with zero arguments, and sets
  26301. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26302. * for models that have an internal representation that's different from what the model exposes
  26303. * to the view.
  26304. *
  26305. * <div class="alert alert-success">
  26306. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26307. * frequently than other parts of your code.
  26308. * </div>
  26309. *
  26310. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26311. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26312. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26313. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26314. *
  26315. * The following example shows how to use `ngModel` with a getter/setter:
  26316. *
  26317. * @example
  26318. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26319. <file name="index.html">
  26320. <div ng-controller="ExampleController">
  26321. <form name="userForm">
  26322. <label>Name:
  26323. <input type="text" name="userName"
  26324. ng-model="user.name"
  26325. ng-model-options="{ getterSetter: true }" />
  26326. </label>
  26327. </form>
  26328. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26329. </div>
  26330. </file>
  26331. <file name="app.js">
  26332. angular.module('getterSetterExample', [])
  26333. .controller('ExampleController', ['$scope', function($scope) {
  26334. var _name = 'Brian';
  26335. $scope.user = {
  26336. name: function(newName) {
  26337. // Note that newName can be undefined for two reasons:
  26338. // 1. Because it is called as a getter and thus called with no arguments
  26339. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26340. // input is invalid
  26341. return arguments.length ? (_name = newName) : _name;
  26342. }
  26343. };
  26344. }]);
  26345. </file>
  26346. * </example>
  26347. */
  26348. var ngModelDirective = ['$rootScope', function($rootScope) {
  26349. return {
  26350. restrict: 'A',
  26351. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26352. controller: NgModelController,
  26353. // Prelink needs to run before any input directive
  26354. // so that we can set the NgModelOptions in NgModelController
  26355. // before anyone else uses it.
  26356. priority: 1,
  26357. compile: function ngModelCompile(element) {
  26358. // Setup initial state of the control
  26359. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26360. return {
  26361. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26362. var modelCtrl = ctrls[0],
  26363. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26364. optionsCtrl = ctrls[2];
  26365. if (optionsCtrl) {
  26366. modelCtrl.$options = optionsCtrl.$options;
  26367. }
  26368. modelCtrl.$$initGetterSetters();
  26369. // notify others, especially parent forms
  26370. formCtrl.$addControl(modelCtrl);
  26371. attr.$observe('name', function(newValue) {
  26372. if (modelCtrl.$name !== newValue) {
  26373. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26374. }
  26375. });
  26376. scope.$on('$destroy', function() {
  26377. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26378. });
  26379. },
  26380. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26381. var modelCtrl = ctrls[0];
  26382. if (modelCtrl.$options.getOption('updateOn')) {
  26383. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26384. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26385. });
  26386. }
  26387. function setTouched() {
  26388. modelCtrl.$setTouched();
  26389. }
  26390. element.on('blur', function() {
  26391. if (modelCtrl.$touched) return;
  26392. if ($rootScope.$$phase) {
  26393. scope.$evalAsync(setTouched);
  26394. } else {
  26395. scope.$apply(setTouched);
  26396. }
  26397. });
  26398. }
  26399. };
  26400. }
  26401. };
  26402. }];
  26403. /* exported defaultModelOptions */
  26404. var defaultModelOptions;
  26405. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26406. /**
  26407. * @ngdoc type
  26408. * @name ModelOptions
  26409. * @description
  26410. * A container for the options set by the {@link ngModelOptions} directive
  26411. */
  26412. function ModelOptions(options) {
  26413. this.$$options = options;
  26414. }
  26415. ModelOptions.prototype = {
  26416. /**
  26417. * @ngdoc method
  26418. * @name ModelOptions#getOption
  26419. * @param {string} name the name of the option to retrieve
  26420. * @returns {*} the value of the option
  26421. * @description
  26422. * Returns the value of the given option
  26423. */
  26424. getOption: function(name) {
  26425. return this.$$options[name];
  26426. },
  26427. /**
  26428. * @ngdoc method
  26429. * @name ModelOptions#createChild
  26430. * @param {Object} options a hash of options for the new child that will override the parent's options
  26431. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  26432. */
  26433. createChild: function(options) {
  26434. var inheritAll = false;
  26435. // make a shallow copy
  26436. options = extend({}, options);
  26437. // Inherit options from the parent if specified by the value `"$inherit"`
  26438. forEach(options, /* @this */ function(option, key) {
  26439. if (option === '$inherit') {
  26440. if (key === '*') {
  26441. inheritAll = true;
  26442. } else {
  26443. options[key] = this.$$options[key];
  26444. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  26445. if (key === 'updateOn') {
  26446. options.updateOnDefault = this.$$options.updateOnDefault;
  26447. }
  26448. }
  26449. } else {
  26450. if (key === 'updateOn') {
  26451. // If the `updateOn` property contains the `default` event then we have to remove
  26452. // it from the event list and set the `updateOnDefault` flag.
  26453. options.updateOnDefault = false;
  26454. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  26455. options.updateOnDefault = true;
  26456. return ' ';
  26457. }));
  26458. }
  26459. }
  26460. }, this);
  26461. if (inheritAll) {
  26462. // We have a property of the form: `"*": "$inherit"`
  26463. delete options['*'];
  26464. defaults(options, this.$$options);
  26465. }
  26466. // Finally add in any missing defaults
  26467. defaults(options, defaultModelOptions.$$options);
  26468. return new ModelOptions(options);
  26469. }
  26470. };
  26471. defaultModelOptions = new ModelOptions({
  26472. updateOn: '',
  26473. updateOnDefault: true,
  26474. debounce: 0,
  26475. getterSetter: false,
  26476. allowInvalid: false,
  26477. timezone: null
  26478. });
  26479. /**
  26480. * @ngdoc directive
  26481. * @name ngModelOptions
  26482. *
  26483. * @description
  26484. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  26485. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  26486. * directives will use the options of their nearest `ngModelOptions` ancestor.
  26487. *
  26488. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  26489. * an Angular expression. This expression should evaluate to an object, whose properties contain
  26490. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  26491. *
  26492. * ## Inheriting Options
  26493. *
  26494. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  26495. * directive by giving it the value of `"$inherit"`.
  26496. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  26497. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  26498. * will be used.
  26499. *
  26500. * For example given the following fragment of HTML
  26501. *
  26502. *
  26503. * ```html
  26504. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26505. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  26506. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  26507. * </form>
  26508. * </div>
  26509. * ```
  26510. *
  26511. * the `input` element will have the following settings
  26512. *
  26513. * ```js
  26514. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  26515. * ```
  26516. *
  26517. * Notice that the `debounce` setting was not inherited and used the default value instead.
  26518. *
  26519. * You can specify that all undefined settings are automatically inherited from an ancestor by
  26520. * including a property with key of `"*"` and value of `"$inherit"`.
  26521. *
  26522. * For example given the following fragment of HTML
  26523. *
  26524. *
  26525. * ```html
  26526. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26527. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  26528. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  26529. * </form>
  26530. * </div>
  26531. * ```
  26532. *
  26533. * the `input` element will have the following settings
  26534. *
  26535. * ```js
  26536. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  26537. * ```
  26538. *
  26539. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  26540. *
  26541. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  26542. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  26543. *
  26544. *
  26545. * ## Triggering and debouncing model updates
  26546. *
  26547. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  26548. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  26549. * a timer expires; this timer will be reset after another change takes place.
  26550. *
  26551. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  26552. * be different from the value in the actual model. This means that if you update the model you
  26553. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  26554. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  26555. *
  26556. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  26557. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  26558. * important because `form` controllers are published to the related scope under the name in their
  26559. * `name` attribute.
  26560. *
  26561. * Any pending changes will take place immediately when an enclosing form is submitted via the
  26562. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  26563. * to have access to the updated model.
  26564. *
  26565. * The following example shows how to override immediate updates. Changes on the inputs within the
  26566. * form will update the model only when the control loses focus (blur event). If `escape` key is
  26567. * pressed while the input field is focused, the value is reset to the value in the current model.
  26568. *
  26569. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  26570. * <file name="index.html">
  26571. * <div ng-controller="ExampleController">
  26572. * <form name="userForm">
  26573. * <label>
  26574. * Name:
  26575. * <input type="text" name="userName"
  26576. * ng-model="user.name"
  26577. * ng-model-options="{ updateOn: 'blur' }"
  26578. * ng-keyup="cancel($event)" />
  26579. * </label><br />
  26580. * <label>
  26581. * Other data:
  26582. * <input type="text" ng-model="user.data" />
  26583. * </label><br />
  26584. * </form>
  26585. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26586. * </div>
  26587. * </file>
  26588. * <file name="app.js">
  26589. * angular.module('optionsExample', [])
  26590. * .controller('ExampleController', ['$scope', function($scope) {
  26591. * $scope.user = { name: 'say', data: '' };
  26592. *
  26593. * $scope.cancel = function(e) {
  26594. * if (e.keyCode === 27) {
  26595. * $scope.userForm.userName.$rollbackViewValue();
  26596. * }
  26597. * };
  26598. * }]);
  26599. * </file>
  26600. * <file name="protractor.js" type="protractor">
  26601. * var model = element(by.binding('user.name'));
  26602. * var input = element(by.model('user.name'));
  26603. * var other = element(by.model('user.data'));
  26604. *
  26605. * it('should allow custom events', function() {
  26606. * input.sendKeys(' hello');
  26607. * input.click();
  26608. * expect(model.getText()).toEqual('say');
  26609. * other.click();
  26610. * expect(model.getText()).toEqual('say hello');
  26611. * });
  26612. *
  26613. * it('should $rollbackViewValue when model changes', function() {
  26614. * input.sendKeys(' hello');
  26615. * expect(input.getAttribute('value')).toEqual('say hello');
  26616. * input.sendKeys(protractor.Key.ESCAPE);
  26617. * expect(input.getAttribute('value')).toEqual('say');
  26618. * other.click();
  26619. * expect(model.getText()).toEqual('say');
  26620. * });
  26621. * </file>
  26622. * </example>
  26623. *
  26624. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  26625. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  26626. *
  26627. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  26628. * <file name="index.html">
  26629. * <div ng-controller="ExampleController">
  26630. * <form name="userForm">
  26631. * Name:
  26632. * <input type="text" name="userName"
  26633. * ng-model="user.name"
  26634. * ng-model-options="{ debounce: 1000 }" />
  26635. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  26636. * </form>
  26637. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26638. * </div>
  26639. * </file>
  26640. * <file name="app.js">
  26641. * angular.module('optionsExample', [])
  26642. * .controller('ExampleController', ['$scope', function($scope) {
  26643. * $scope.user = { name: 'say' };
  26644. * }]);
  26645. * </file>
  26646. * </example>
  26647. *
  26648. * ## Model updates and validation
  26649. *
  26650. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  26651. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  26652. * the model will still be updated even if the value is invalid.
  26653. *
  26654. *
  26655. * ## Connecting to the scope
  26656. *
  26657. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  26658. * on the scope refers to a "getter/setter" function rather than the value itself.
  26659. *
  26660. * The following example shows how to bind to getter/setters:
  26661. *
  26662. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  26663. * <file name="index.html">
  26664. * <div ng-controller="ExampleController">
  26665. * <form name="userForm">
  26666. * <label>
  26667. * Name:
  26668. * <input type="text" name="userName"
  26669. * ng-model="user.name"
  26670. * ng-model-options="{ getterSetter: true }" />
  26671. * </label>
  26672. * </form>
  26673. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26674. * </div>
  26675. * </file>
  26676. * <file name="app.js">
  26677. * angular.module('getterSetterExample', [])
  26678. * .controller('ExampleController', ['$scope', function($scope) {
  26679. * var _name = 'Brian';
  26680. * $scope.user = {
  26681. * name: function(newName) {
  26682. * return angular.isDefined(newName) ? (_name = newName) : _name;
  26683. * }
  26684. * };
  26685. * }]);
  26686. * </file>
  26687. * </example>
  26688. *
  26689. *
  26690. * ## Specifying timezones
  26691. *
  26692. * You can specify the timezone that date/time input directives expect by providing its name in the
  26693. * `timezone` property.
  26694. *
  26695. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  26696. * and its descendents. Valid keys are:
  26697. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  26698. * events using an space delimited list. There is a special event called `default` that
  26699. * matches the default events belonging to the control.
  26700. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  26701. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  26702. * custom value for each event. For example:
  26703. * ```
  26704. * ng-model-options="{
  26705. * updateOn: 'default blur',
  26706. * debounce: { 'default': 500, 'blur': 0 }
  26707. * }"
  26708. * ```
  26709. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  26710. * not validate correctly instead of the default behavior of setting the model to undefined.
  26711. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  26712. * `ngModel` as getters/setters.
  26713. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  26714. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  26715. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  26716. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  26717. * If not specified, the timezone of the browser will be used.
  26718. *
  26719. */
  26720. var ngModelOptionsDirective = function() {
  26721. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  26722. function NgModelOptionsController($attrs, $scope) {
  26723. this.$$attrs = $attrs;
  26724. this.$$scope = $scope;
  26725. }
  26726. NgModelOptionsController.prototype = {
  26727. $onInit: function() {
  26728. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  26729. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  26730. this.$options = parentOptions.createChild(modelOptionsDefinition);
  26731. }
  26732. };
  26733. return {
  26734. restrict: 'A',
  26735. // ngModelOptions needs to run before ngModel and input directives
  26736. priority: 10,
  26737. require: {parentCtrl: '?^^ngModelOptions'},
  26738. bindToController: true,
  26739. controller: NgModelOptionsController
  26740. };
  26741. };
  26742. // shallow copy over values from `src` that are not already specified on `dst`
  26743. function defaults(dst, src) {
  26744. forEach(src, function(value, key) {
  26745. if (!isDefined(dst[key])) {
  26746. dst[key] = value;
  26747. }
  26748. });
  26749. }
  26750. /**
  26751. * @ngdoc directive
  26752. * @name ngNonBindable
  26753. * @restrict AC
  26754. * @priority 1000
  26755. *
  26756. * @description
  26757. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  26758. * DOM element. This is useful if the element contains what appears to be Angular directives and
  26759. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  26760. * displays snippets of code, for instance.
  26761. *
  26762. * @element ANY
  26763. *
  26764. * @example
  26765. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  26766. * but the one wrapped in `ngNonBindable` is left alone.
  26767. *
  26768. * @example
  26769. <example name="ng-non-bindable">
  26770. <file name="index.html">
  26771. <div>Normal: {{1 + 2}}</div>
  26772. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  26773. </file>
  26774. <file name="protractor.js" type="protractor">
  26775. it('should check ng-non-bindable', function() {
  26776. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  26777. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  26778. });
  26779. </file>
  26780. </example>
  26781. */
  26782. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  26783. /* exported ngOptionsDirective */
  26784. /* global jqLiteRemove */
  26785. var ngOptionsMinErr = minErr('ngOptions');
  26786. /**
  26787. * @ngdoc directive
  26788. * @name ngOptions
  26789. * @restrict A
  26790. *
  26791. * @description
  26792. *
  26793. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  26794. * elements for the `<select>` element using the array or object obtained by evaluating the
  26795. * `ngOptions` comprehension expression.
  26796. *
  26797. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  26798. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  26799. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  26800. * comprehension expression
  26801. * - reduced memory consumption by not creating a new scope for each repeated instance
  26802. * - increased render speed by creating the options in a documentFragment instead of individually
  26803. *
  26804. * When an item in the `<select>` menu is selected, the array element or object property
  26805. * represented by the selected option will be bound to the model identified by the `ngModel`
  26806. * directive.
  26807. *
  26808. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  26809. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  26810. * option. See example below for demonstration.
  26811. *
  26812. * ## Complex Models (objects or collections)
  26813. *
  26814. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26815. * binding the select to a model that is an object or a collection.
  26816. *
  26817. * One issue occurs if you want to preselect an option. For example, if you set
  26818. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  26819. * because the objects are not identical. So by default, you should always reference the item in your collection
  26820. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  26821. *
  26822. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  26823. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  26824. * collection items have an id property, you would `track by item.id`.
  26825. *
  26826. * A different issue with objects or collections is that ngModel won't detect if an object property or
  26827. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  26828. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  26829. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  26830. * has not changed identity, but only a property on the object or an item in the collection changes.
  26831. *
  26832. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  26833. * if the model is an array). This means that changing a property deeper than the first level inside the
  26834. * object/collection will not trigger a re-rendering.
  26835. *
  26836. * ## `select` **`as`**
  26837. *
  26838. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  26839. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  26840. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  26841. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  26842. *
  26843. *
  26844. * ### `select` **`as`** and **`track by`**
  26845. *
  26846. * <div class="alert alert-warning">
  26847. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  26848. * </div>
  26849. *
  26850. * Given this array of items on the $scope:
  26851. *
  26852. * ```js
  26853. * $scope.items = [{
  26854. * id: 1,
  26855. * label: 'aLabel',
  26856. * subItem: { name: 'aSubItem' }
  26857. * }, {
  26858. * id: 2,
  26859. * label: 'bLabel',
  26860. * subItem: { name: 'bSubItem' }
  26861. * }];
  26862. * ```
  26863. *
  26864. * This will work:
  26865. *
  26866. * ```html
  26867. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  26868. * ```
  26869. * ```js
  26870. * $scope.selected = $scope.items[0];
  26871. * ```
  26872. *
  26873. * but this will not work:
  26874. *
  26875. * ```html
  26876. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  26877. * ```
  26878. * ```js
  26879. * $scope.selected = $scope.items[0].subItem;
  26880. * ```
  26881. *
  26882. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  26883. * `items` array. Because the selected option has been set programmatically in the controller, the
  26884. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  26885. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  26886. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  26887. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  26888. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  26889. *
  26890. *
  26891. * @param {string} ngModel Assignable angular expression to data-bind to.
  26892. * @param {string=} name Property name of the form under which the control is published.
  26893. * @param {string=} required The control is considered valid only if value is entered.
  26894. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  26895. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  26896. * `required` when you want to data-bind to the `required` attribute.
  26897. * @param {comprehension_expression=} ngOptions in one of the following forms:
  26898. *
  26899. * * for array data sources:
  26900. * * `label` **`for`** `value` **`in`** `array`
  26901. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  26902. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  26903. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  26904. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26905. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26906. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  26907. * (for including a filter with `track by`)
  26908. * * for object data sources:
  26909. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26910. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26911. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26912. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26913. * * `select` **`as`** `label` **`group by`** `group`
  26914. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26915. * * `select` **`as`** `label` **`disable when`** `disable`
  26916. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26917. *
  26918. * Where:
  26919. *
  26920. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  26921. * * `value`: local variable which will refer to each item in the `array` or each property value
  26922. * of `object` during iteration.
  26923. * * `key`: local variable which will refer to a property name in `object` during iteration.
  26924. * * `label`: The result of this expression will be the label for `<option>` element. The
  26925. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  26926. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  26927. * element. If not specified, `select` expression will default to `value`.
  26928. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  26929. * DOM element.
  26930. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  26931. * element. Return `true` to disable.
  26932. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  26933. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  26934. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  26935. * even when the options are recreated (e.g. reloaded from the server).
  26936. *
  26937. * @example
  26938. <example module="selectExample" name="select">
  26939. <file name="index.html">
  26940. <script>
  26941. angular.module('selectExample', [])
  26942. .controller('ExampleController', ['$scope', function($scope) {
  26943. $scope.colors = [
  26944. {name:'black', shade:'dark'},
  26945. {name:'white', shade:'light', notAnOption: true},
  26946. {name:'red', shade:'dark'},
  26947. {name:'blue', shade:'dark', notAnOption: true},
  26948. {name:'yellow', shade:'light', notAnOption: false}
  26949. ];
  26950. $scope.myColor = $scope.colors[2]; // red
  26951. }]);
  26952. </script>
  26953. <div ng-controller="ExampleController">
  26954. <ul>
  26955. <li ng-repeat="color in colors">
  26956. <label>Name: <input ng-model="color.name"></label>
  26957. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  26958. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  26959. </li>
  26960. <li>
  26961. <button ng-click="colors.push({})">add</button>
  26962. </li>
  26963. </ul>
  26964. <hr/>
  26965. <label>Color (null not allowed):
  26966. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  26967. </label><br/>
  26968. <label>Color (null allowed):
  26969. <span class="nullable">
  26970. <select ng-model="myColor" ng-options="color.name for color in colors">
  26971. <option value="">-- choose color --</option>
  26972. </select>
  26973. </span></label><br/>
  26974. <label>Color grouped by shade:
  26975. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  26976. </select>
  26977. </label><br/>
  26978. <label>Color grouped by shade, with some disabled:
  26979. <select ng-model="myColor"
  26980. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  26981. </select>
  26982. </label><br/>
  26983. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  26984. <br/>
  26985. <hr/>
  26986. Currently selected: {{ {selected_color:myColor} }}
  26987. <div style="border:solid 1px black; height:20px"
  26988. ng-style="{'background-color':myColor.name}">
  26989. </div>
  26990. </div>
  26991. </file>
  26992. <file name="protractor.js" type="protractor">
  26993. it('should check ng-options', function() {
  26994. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  26995. element.all(by.model('myColor')).first().click();
  26996. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  26997. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  26998. element(by.css('.nullable select[ng-model="myColor"]')).click();
  26999. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27000. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27001. });
  27002. </file>
  27003. </example>
  27004. */
  27005. /* eslint-disable max-len */
  27006. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27007. 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]+?))?$/;
  27008. // 1: value expression (valueFn)
  27009. // 2: label expression (displayFn)
  27010. // 3: group by expression (groupByFn)
  27011. // 4: disable when expression (disableWhenFn)
  27012. // 5: array item variable name
  27013. // 6: object item key variable name
  27014. // 7: object item value variable name
  27015. // 8: collection expression
  27016. // 9: track by expression
  27017. /* eslint-enable */
  27018. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27019. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27020. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27021. if (!(match)) {
  27022. throw ngOptionsMinErr('iexp',
  27023. 'Expected expression in form of ' +
  27024. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27025. ' but got \'{0}\'. Element: {1}',
  27026. optionsExp, startingTag(selectElement));
  27027. }
  27028. // Extract the parts from the ngOptions expression
  27029. // The variable name for the value of the item in the collection
  27030. var valueName = match[5] || match[7];
  27031. // The variable name for the key of the item in the collection
  27032. var keyName = match[6];
  27033. // An expression that generates the viewValue for an option if there is a label expression
  27034. var selectAs = / as /.test(match[0]) && match[1];
  27035. // An expression that is used to track the id of each object in the options collection
  27036. var trackBy = match[9];
  27037. // An expression that generates the viewValue for an option if there is no label expression
  27038. var valueFn = $parse(match[2] ? match[1] : valueName);
  27039. var selectAsFn = selectAs && $parse(selectAs);
  27040. var viewValueFn = selectAsFn || valueFn;
  27041. var trackByFn = trackBy && $parse(trackBy);
  27042. // Get the value by which we are going to track the option
  27043. // if we have a trackFn then use that (passing scope and locals)
  27044. // otherwise just hash the given viewValue
  27045. var getTrackByValueFn = trackBy ?
  27046. function(value, locals) { return trackByFn(scope, locals); } :
  27047. function getHashOfValue(value) { return hashKey(value); };
  27048. var getTrackByValue = function(value, key) {
  27049. return getTrackByValueFn(value, getLocals(value, key));
  27050. };
  27051. var displayFn = $parse(match[2] || match[1]);
  27052. var groupByFn = $parse(match[3] || '');
  27053. var disableWhenFn = $parse(match[4] || '');
  27054. var valuesFn = $parse(match[8]);
  27055. var locals = {};
  27056. var getLocals = keyName ? function(value, key) {
  27057. locals[keyName] = key;
  27058. locals[valueName] = value;
  27059. return locals;
  27060. } : function(value) {
  27061. locals[valueName] = value;
  27062. return locals;
  27063. };
  27064. function Option(selectValue, viewValue, label, group, disabled) {
  27065. this.selectValue = selectValue;
  27066. this.viewValue = viewValue;
  27067. this.label = label;
  27068. this.group = group;
  27069. this.disabled = disabled;
  27070. }
  27071. function getOptionValuesKeys(optionValues) {
  27072. var optionValuesKeys;
  27073. if (!keyName && isArrayLike(optionValues)) {
  27074. optionValuesKeys = optionValues;
  27075. } else {
  27076. // if object, extract keys, in enumeration order, unsorted
  27077. optionValuesKeys = [];
  27078. for (var itemKey in optionValues) {
  27079. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27080. optionValuesKeys.push(itemKey);
  27081. }
  27082. }
  27083. }
  27084. return optionValuesKeys;
  27085. }
  27086. return {
  27087. trackBy: trackBy,
  27088. getTrackByValue: getTrackByValue,
  27089. getWatchables: $parse(valuesFn, function(optionValues) {
  27090. // Create a collection of things that we would like to watch (watchedArray)
  27091. // so that they can all be watched using a single $watchCollection
  27092. // that only runs the handler once if anything changes
  27093. var watchedArray = [];
  27094. optionValues = optionValues || [];
  27095. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27096. var optionValuesLength = optionValuesKeys.length;
  27097. for (var index = 0; index < optionValuesLength; index++) {
  27098. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27099. var value = optionValues[key];
  27100. var locals = getLocals(value, key);
  27101. var selectValue = getTrackByValueFn(value, locals);
  27102. watchedArray.push(selectValue);
  27103. // Only need to watch the displayFn if there is a specific label expression
  27104. if (match[2] || match[1]) {
  27105. var label = displayFn(scope, locals);
  27106. watchedArray.push(label);
  27107. }
  27108. // Only need to watch the disableWhenFn if there is a specific disable expression
  27109. if (match[4]) {
  27110. var disableWhen = disableWhenFn(scope, locals);
  27111. watchedArray.push(disableWhen);
  27112. }
  27113. }
  27114. return watchedArray;
  27115. }),
  27116. getOptions: function() {
  27117. var optionItems = [];
  27118. var selectValueMap = {};
  27119. // The option values were already computed in the `getWatchables` fn,
  27120. // which must have been called to trigger `getOptions`
  27121. var optionValues = valuesFn(scope) || [];
  27122. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27123. var optionValuesLength = optionValuesKeys.length;
  27124. for (var index = 0; index < optionValuesLength; index++) {
  27125. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27126. var value = optionValues[key];
  27127. var locals = getLocals(value, key);
  27128. var viewValue = viewValueFn(scope, locals);
  27129. var selectValue = getTrackByValueFn(viewValue, locals);
  27130. var label = displayFn(scope, locals);
  27131. var group = groupByFn(scope, locals);
  27132. var disabled = disableWhenFn(scope, locals);
  27133. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27134. optionItems.push(optionItem);
  27135. selectValueMap[selectValue] = optionItem;
  27136. }
  27137. return {
  27138. items: optionItems,
  27139. selectValueMap: selectValueMap,
  27140. getOptionFromViewValue: function(value) {
  27141. return selectValueMap[getTrackByValue(value)];
  27142. },
  27143. getViewValueFromOption: function(option) {
  27144. // If the viewValue could be an object that may be mutated by the application,
  27145. // we need to make a copy and not return the reference to the value on the option.
  27146. return trackBy ? copy(option.viewValue) : option.viewValue;
  27147. }
  27148. };
  27149. }
  27150. };
  27151. }
  27152. // we can't just jqLite('<option>') since jqLite is not smart enough
  27153. // to create it in <select> and IE barfs otherwise.
  27154. var optionTemplate = window.document.createElement('option'),
  27155. optGroupTemplate = window.document.createElement('optgroup');
  27156. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27157. var selectCtrl = ctrls[0];
  27158. var ngModelCtrl = ctrls[1];
  27159. var multiple = attr.multiple;
  27160. // The emptyOption allows the application developer to provide their own custom "empty"
  27161. // option when the viewValue does not match any of the option values.
  27162. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27163. if (children[i].value === '') {
  27164. selectCtrl.hasEmptyOption = true;
  27165. selectCtrl.emptyOption = children.eq(i);
  27166. break;
  27167. }
  27168. }
  27169. var providedEmptyOption = !!selectCtrl.emptyOption;
  27170. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27171. unknownOption.val('?');
  27172. var options;
  27173. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27174. // This stores the newly created options before they are appended to the select.
  27175. // Since the contents are removed from the fragment when it is appended,
  27176. // we only need to create it once.
  27177. var listFragment = $document[0].createDocumentFragment();
  27178. // Overwrite the implementation. ngOptions doesn't use hashes
  27179. selectCtrl.generateUnknownOptionValue = function(val) {
  27180. return '?';
  27181. };
  27182. // Update the controller methods for multiple selectable options
  27183. if (!multiple) {
  27184. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27185. var selectedOption = options.selectValueMap[selectElement.val()];
  27186. var option = options.getOptionFromViewValue(value);
  27187. // Make sure to remove the selected attribute from the previously selected option
  27188. // Otherwise, screen readers might get confused
  27189. if (selectedOption) selectedOption.element.removeAttribute('selected');
  27190. if (option) {
  27191. // Don't update the option when it is already selected.
  27192. // For example, the browser will select the first option by default. In that case,
  27193. // most properties are set automatically - except the `selected` attribute, which we
  27194. // set always
  27195. if (selectElement[0].value !== option.selectValue) {
  27196. selectCtrl.removeUnknownOption();
  27197. selectCtrl.unselectEmptyOption();
  27198. selectElement[0].value = option.selectValue;
  27199. option.element.selected = true;
  27200. }
  27201. option.element.setAttribute('selected', 'selected');
  27202. } else {
  27203. if (providedEmptyOption) {
  27204. selectCtrl.selectEmptyOption();
  27205. } else if (selectCtrl.unknownOption.parent().length) {
  27206. selectCtrl.updateUnknownOption(value);
  27207. } else {
  27208. selectCtrl.renderUnknownOption(value);
  27209. }
  27210. }
  27211. };
  27212. selectCtrl.readValue = function readNgOptionsValue() {
  27213. var selectedOption = options.selectValueMap[selectElement.val()];
  27214. if (selectedOption && !selectedOption.disabled) {
  27215. selectCtrl.unselectEmptyOption();
  27216. selectCtrl.removeUnknownOption();
  27217. return options.getViewValueFromOption(selectedOption);
  27218. }
  27219. return null;
  27220. };
  27221. // If we are using `track by` then we must watch the tracked value on the model
  27222. // since ngModel only watches for object identity change
  27223. // FIXME: When a user selects an option, this watch will fire needlessly
  27224. if (ngOptions.trackBy) {
  27225. scope.$watch(
  27226. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27227. function() { ngModelCtrl.$render(); }
  27228. );
  27229. }
  27230. } else {
  27231. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  27232. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  27233. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  27234. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  27235. options.items.forEach(function(option) {
  27236. if (option.element.selected && !includes(selectedOptions, option)) {
  27237. option.element.selected = false;
  27238. }
  27239. });
  27240. };
  27241. selectCtrl.readValue = function readNgOptionsMultiple() {
  27242. var selectedValues = selectElement.val() || [],
  27243. selections = [];
  27244. forEach(selectedValues, function(value) {
  27245. var option = options.selectValueMap[value];
  27246. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27247. });
  27248. return selections;
  27249. };
  27250. // If we are using `track by` then we must watch these tracked values on the model
  27251. // since ngModel only watches for object identity change
  27252. if (ngOptions.trackBy) {
  27253. scope.$watchCollection(function() {
  27254. if (isArray(ngModelCtrl.$viewValue)) {
  27255. return ngModelCtrl.$viewValue.map(function(value) {
  27256. return ngOptions.getTrackByValue(value);
  27257. });
  27258. }
  27259. }, function() {
  27260. ngModelCtrl.$render();
  27261. });
  27262. }
  27263. }
  27264. if (providedEmptyOption) {
  27265. // we need to remove it before calling selectElement.empty() because otherwise IE will
  27266. // remove the label from the element. wtf?
  27267. selectCtrl.emptyOption.remove();
  27268. // compile the element since there might be bindings in it
  27269. $compile(selectCtrl.emptyOption)(scope);
  27270. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  27271. // This means the empty option has currently no actual DOM node, probably because
  27272. // it has been modified by a transclusion directive.
  27273. selectCtrl.hasEmptyOption = false;
  27274. // Redefine the registerOption function, which will catch
  27275. // options that are added by ngIf etc. (rendering of the node is async because of
  27276. // lazy transclusion)
  27277. selectCtrl.registerOption = function(optionScope, optionEl) {
  27278. if (optionEl.val() === '') {
  27279. selectCtrl.hasEmptyOption = true;
  27280. selectCtrl.emptyOption = optionEl;
  27281. selectCtrl.emptyOption.removeClass('ng-scope');
  27282. // This ensures the new empty option is selected if previously no option was selected
  27283. ngModelCtrl.$render();
  27284. optionEl.on('$destroy', function() {
  27285. selectCtrl.hasEmptyOption = false;
  27286. selectCtrl.emptyOption = undefined;
  27287. });
  27288. }
  27289. };
  27290. } else {
  27291. // remove the class, which is added automatically because we recompile the element and it
  27292. // becomes the compilation root
  27293. selectCtrl.emptyOption.removeClass('ng-scope');
  27294. }
  27295. }
  27296. selectElement.empty();
  27297. // We need to do this here to ensure that the options object is defined
  27298. // when we first hit it in writeNgOptionsValue
  27299. updateOptions();
  27300. // We will re-render the option elements if the option values or labels change
  27301. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27302. // ------------------------------------------------------------------ //
  27303. function addOptionElement(option, parent) {
  27304. var optionElement = optionTemplate.cloneNode(false);
  27305. parent.appendChild(optionElement);
  27306. updateOptionElement(option, optionElement);
  27307. }
  27308. function getAndUpdateSelectedOption(viewValue) {
  27309. var option = options.getOptionFromViewValue(viewValue);
  27310. var element = option && option.element;
  27311. if (element && !element.selected) element.selected = true;
  27312. return option;
  27313. }
  27314. function updateOptionElement(option, element) {
  27315. option.element = element;
  27316. element.disabled = option.disabled;
  27317. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  27318. // selects in certain circumstances when multiple selects are next to each other and display
  27319. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27320. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27321. // This is unfortunately untestable with unit / e2e tests
  27322. if (option.label !== element.label) {
  27323. element.label = option.label;
  27324. element.textContent = option.label;
  27325. }
  27326. element.value = option.selectValue;
  27327. }
  27328. function updateOptions() {
  27329. var previousValue = options && selectCtrl.readValue();
  27330. // We must remove all current options, but cannot simply set innerHTML = null
  27331. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27332. // must preserve.
  27333. // Instead, iterate over the current option elements and remove them or their optgroup
  27334. // parents
  27335. if (options) {
  27336. for (var i = options.items.length - 1; i >= 0; i--) {
  27337. var option = options.items[i];
  27338. if (isDefined(option.group)) {
  27339. jqLiteRemove(option.element.parentNode);
  27340. } else {
  27341. jqLiteRemove(option.element);
  27342. }
  27343. }
  27344. }
  27345. options = ngOptions.getOptions();
  27346. var groupElementMap = {};
  27347. // Ensure that the empty option is always there if it was explicitly provided
  27348. if (providedEmptyOption) {
  27349. selectElement.prepend(selectCtrl.emptyOption);
  27350. }
  27351. options.items.forEach(function addOption(option) {
  27352. var groupElement;
  27353. if (isDefined(option.group)) {
  27354. // This option is to live in a group
  27355. // See if we have already created this group
  27356. groupElement = groupElementMap[option.group];
  27357. if (!groupElement) {
  27358. groupElement = optGroupTemplate.cloneNode(false);
  27359. listFragment.appendChild(groupElement);
  27360. // Update the label on the group element
  27361. // "null" is special cased because of Safari
  27362. groupElement.label = option.group === null ? 'null' : option.group;
  27363. // Store it for use later
  27364. groupElementMap[option.group] = groupElement;
  27365. }
  27366. addOptionElement(option, groupElement);
  27367. } else {
  27368. // This option is not in a group
  27369. addOptionElement(option, listFragment);
  27370. }
  27371. });
  27372. selectElement[0].appendChild(listFragment);
  27373. ngModelCtrl.$render();
  27374. // Check to see if the value has changed due to the update to the options
  27375. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27376. var nextValue = selectCtrl.readValue();
  27377. var isNotPrimitive = ngOptions.trackBy || multiple;
  27378. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27379. ngModelCtrl.$setViewValue(nextValue);
  27380. ngModelCtrl.$render();
  27381. }
  27382. }
  27383. }
  27384. }
  27385. return {
  27386. restrict: 'A',
  27387. terminal: true,
  27388. require: ['select', 'ngModel'],
  27389. link: {
  27390. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27391. // Deactivate the SelectController.register method to prevent
  27392. // option directives from accidentally registering themselves
  27393. // (and unwanted $destroy handlers etc.)
  27394. ctrls[0].registerOption = noop;
  27395. },
  27396. post: ngOptionsPostLink
  27397. }
  27398. };
  27399. }];
  27400. /**
  27401. * @ngdoc directive
  27402. * @name ngPluralize
  27403. * @restrict EA
  27404. *
  27405. * @description
  27406. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27407. * These rules are bundled with angular.js, but can be overridden
  27408. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27409. * by specifying the mappings between
  27410. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27411. * and the strings to be displayed.
  27412. *
  27413. * # Plural categories and explicit number rules
  27414. * There are two
  27415. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27416. * in Angular's default en-US locale: "one" and "other".
  27417. *
  27418. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  27419. * any number that is not 1), an explicit number rule can only match one number. For example, the
  27420. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  27421. * and explicit number rules throughout the rest of this documentation.
  27422. *
  27423. * # Configuring ngPluralize
  27424. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  27425. * You can also provide an optional attribute, `offset`.
  27426. *
  27427. * The value of the `count` attribute can be either a string or an {@link guide/expression
  27428. * Angular expression}; these are evaluated on the current scope for its bound value.
  27429. *
  27430. * The `when` attribute specifies the mappings between plural categories and the actual
  27431. * string to be displayed. The value of the attribute should be a JSON object.
  27432. *
  27433. * The following example shows how to configure ngPluralize:
  27434. *
  27435. * ```html
  27436. * <ng-pluralize count="personCount"
  27437. when="{'0': 'Nobody is viewing.',
  27438. * 'one': '1 person is viewing.',
  27439. * 'other': '{} people are viewing.'}">
  27440. * </ng-pluralize>
  27441. *```
  27442. *
  27443. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  27444. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  27445. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  27446. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  27447. * show "a dozen people are viewing".
  27448. *
  27449. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  27450. * into pluralized strings. In the previous example, Angular will replace `{}` with
  27451. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  27452. * for <span ng-non-bindable>{{numberExpression}}</span>.
  27453. *
  27454. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  27455. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  27456. *
  27457. * # Configuring ngPluralize with offset
  27458. * The `offset` attribute allows further customization of pluralized text, which can result in
  27459. * a better user experience. For example, instead of the message "4 people are viewing this document",
  27460. * you might display "John, Kate and 2 others are viewing this document".
  27461. * The offset attribute allows you to offset a number by any desired value.
  27462. * Let's take a look at an example:
  27463. *
  27464. * ```html
  27465. * <ng-pluralize count="personCount" offset=2
  27466. * when="{'0': 'Nobody is viewing.',
  27467. * '1': '{{person1}} is viewing.',
  27468. * '2': '{{person1}} and {{person2}} are viewing.',
  27469. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27470. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27471. * </ng-pluralize>
  27472. * ```
  27473. *
  27474. * Notice that we are still using two plural categories(one, other), but we added
  27475. * three explicit number rules 0, 1 and 2.
  27476. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  27477. * When three people view the document, no explicit number rule is found, so
  27478. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  27479. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  27480. * is shown.
  27481. *
  27482. * Note that when you specify offsets, you must provide explicit number rules for
  27483. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  27484. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  27485. * plural categories "one" and "other".
  27486. *
  27487. * @param {string|expression} count The variable to be bound to.
  27488. * @param {string} when The mapping between plural category to its corresponding strings.
  27489. * @param {number=} offset Offset to deduct from the total number.
  27490. *
  27491. * @example
  27492. <example module="pluralizeExample" name="ng-pluralize">
  27493. <file name="index.html">
  27494. <script>
  27495. angular.module('pluralizeExample', [])
  27496. .controller('ExampleController', ['$scope', function($scope) {
  27497. $scope.person1 = 'Igor';
  27498. $scope.person2 = 'Misko';
  27499. $scope.personCount = 1;
  27500. }]);
  27501. </script>
  27502. <div ng-controller="ExampleController">
  27503. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  27504. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  27505. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  27506. <!--- Example with simple pluralization rules for en locale --->
  27507. Without Offset:
  27508. <ng-pluralize count="personCount"
  27509. when="{'0': 'Nobody is viewing.',
  27510. 'one': '1 person is viewing.',
  27511. 'other': '{} people are viewing.'}">
  27512. </ng-pluralize><br>
  27513. <!--- Example with offset --->
  27514. With Offset(2):
  27515. <ng-pluralize count="personCount" offset=2
  27516. when="{'0': 'Nobody is viewing.',
  27517. '1': '{{person1}} is viewing.',
  27518. '2': '{{person1}} and {{person2}} are viewing.',
  27519. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27520. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27521. </ng-pluralize>
  27522. </div>
  27523. </file>
  27524. <file name="protractor.js" type="protractor">
  27525. it('should show correct pluralized string', function() {
  27526. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  27527. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27528. var countInput = element(by.model('personCount'));
  27529. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  27530. expect(withOffset.getText()).toEqual('Igor is viewing.');
  27531. countInput.clear();
  27532. countInput.sendKeys('0');
  27533. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  27534. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  27535. countInput.clear();
  27536. countInput.sendKeys('2');
  27537. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  27538. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  27539. countInput.clear();
  27540. countInput.sendKeys('3');
  27541. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  27542. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  27543. countInput.clear();
  27544. countInput.sendKeys('4');
  27545. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  27546. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  27547. });
  27548. it('should show data-bound names', function() {
  27549. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27550. var personCount = element(by.model('personCount'));
  27551. var person1 = element(by.model('person1'));
  27552. var person2 = element(by.model('person2'));
  27553. personCount.clear();
  27554. personCount.sendKeys('4');
  27555. person1.clear();
  27556. person1.sendKeys('Di');
  27557. person2.clear();
  27558. person2.sendKeys('Vojta');
  27559. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  27560. });
  27561. </file>
  27562. </example>
  27563. */
  27564. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  27565. var BRACE = /{}/g,
  27566. IS_WHEN = /^when(Minus)?(.+)$/;
  27567. return {
  27568. link: function(scope, element, attr) {
  27569. var numberExp = attr.count,
  27570. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  27571. offset = attr.offset || 0,
  27572. whens = scope.$eval(whenExp) || {},
  27573. whensExpFns = {},
  27574. startSymbol = $interpolate.startSymbol(),
  27575. endSymbol = $interpolate.endSymbol(),
  27576. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  27577. watchRemover = angular.noop,
  27578. lastCount;
  27579. forEach(attr, function(expression, attributeName) {
  27580. var tmpMatch = IS_WHEN.exec(attributeName);
  27581. if (tmpMatch) {
  27582. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  27583. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  27584. }
  27585. });
  27586. forEach(whens, function(expression, key) {
  27587. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  27588. });
  27589. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  27590. var count = parseFloat(newVal);
  27591. var countIsNaN = isNumberNaN(count);
  27592. if (!countIsNaN && !(count in whens)) {
  27593. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  27594. // Otherwise, check it against pluralization rules in $locale service.
  27595. count = $locale.pluralCat(count - offset);
  27596. }
  27597. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  27598. // In JS `NaN !== NaN`, so we have to explicitly check.
  27599. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  27600. watchRemover();
  27601. var whenExpFn = whensExpFns[count];
  27602. if (isUndefined(whenExpFn)) {
  27603. if (newVal != null) {
  27604. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  27605. }
  27606. watchRemover = noop;
  27607. updateElementText();
  27608. } else {
  27609. watchRemover = scope.$watch(whenExpFn, updateElementText);
  27610. }
  27611. lastCount = count;
  27612. }
  27613. });
  27614. function updateElementText(newText) {
  27615. element.text(newText || '');
  27616. }
  27617. }
  27618. };
  27619. }];
  27620. /* exported ngRepeatDirective */
  27621. /**
  27622. * @ngdoc directive
  27623. * @name ngRepeat
  27624. * @multiElement
  27625. *
  27626. * @description
  27627. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  27628. * instance gets its own scope, where the given loop variable is set to the current collection item,
  27629. * and `$index` is set to the item index or key.
  27630. *
  27631. * Special properties are exposed on the local scope of each template instance, including:
  27632. *
  27633. * | Variable | Type | Details |
  27634. * |-----------|-----------------|-----------------------------------------------------------------------------|
  27635. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  27636. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  27637. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  27638. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  27639. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  27640. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  27641. *
  27642. * <div class="alert alert-info">
  27643. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  27644. * This may be useful when, for instance, nesting ngRepeats.
  27645. * </div>
  27646. *
  27647. *
  27648. * # Iterating over object properties
  27649. *
  27650. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  27651. * syntax:
  27652. *
  27653. * ```js
  27654. * <div ng-repeat="(key, value) in myObj"> ... </div>
  27655. * ```
  27656. *
  27657. * However, there are a few limitations compared to array iteration:
  27658. *
  27659. * - The JavaScript specification does not define the order of keys
  27660. * returned for an object, so Angular relies on the order returned by the browser
  27661. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  27662. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  27663. * and reinstated. See the
  27664. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  27665. *
  27666. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  27667. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  27668. *
  27669. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  27670. * objects, and will throw an error if used with one.
  27671. *
  27672. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  27673. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  27674. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  27675. * or implement a `$watch` on the object yourself.
  27676. *
  27677. *
  27678. * # Tracking and Duplicates
  27679. *
  27680. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  27681. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  27682. *
  27683. * * When an item is added, a new instance of the template is added to the DOM.
  27684. * * When an item is removed, its template instance is removed from the DOM.
  27685. * * When items are reordered, their respective templates are reordered in the DOM.
  27686. *
  27687. * To minimize creation of DOM elements, `ngRepeat` uses a function
  27688. * to "keep track" of all items in the collection and their corresponding DOM elements.
  27689. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  27690. * already have DOM elements, and will not re-render them.
  27691. *
  27692. * The default tracking function (which tracks items by their identity) does not allow
  27693. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  27694. * to maintain a one-to-one mapping between collection items and DOM elements.
  27695. *
  27696. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  27697. * with your own using the `track by` expression.
  27698. *
  27699. * For example, you may track items by the index of each item in the collection, using the
  27700. * special scope property `$index`:
  27701. * ```html
  27702. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  27703. * {{n}}
  27704. * </div>
  27705. * ```
  27706. *
  27707. * You may also use arbitrary expressions in `track by`, including references to custom functions
  27708. * on the scope:
  27709. * ```html
  27710. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  27711. * {{n}}
  27712. * </div>
  27713. * ```
  27714. *
  27715. * <div class="alert alert-success">
  27716. * If you are working with objects that have a unique identifier property, you should track
  27717. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  27718. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  27719. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  27720. * this significantly improves rendering performance. If you don't have a unique identifier,
  27721. * `track by $index` can also provide a performance boost.
  27722. * </div>
  27723. *
  27724. * ```html
  27725. * <div ng-repeat="model in collection track by model.id">
  27726. * {{model.name}}
  27727. * </div>
  27728. * ```
  27729. *
  27730. * <br />
  27731. * <div class="alert alert-warning">
  27732. * Avoid using `track by $index` when the repeated template contains
  27733. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  27734. * element will always be matched with the `nth` item of the array, so the bindings on that element
  27735. * will not be updated even when the corresponding item changes, essentially causing the view to get
  27736. * out-of-sync with the underlying data.
  27737. * </div>
  27738. *
  27739. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  27740. * `$id` function, which tracks items by their identity:
  27741. * ```html
  27742. * <div ng-repeat="obj in collection track by $id(obj)">
  27743. * {{obj.prop}}
  27744. * </div>
  27745. * ```
  27746. *
  27747. * <br />
  27748. * <div class="alert alert-warning">
  27749. * **Note:** `track by` must always be the last expression:
  27750. * </div>
  27751. * ```
  27752. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  27753. * {{model.name}}
  27754. * </div>
  27755. * ```
  27756. *
  27757. *
  27758. * # Special repeat start and end points
  27759. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  27760. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  27761. * 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)
  27762. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  27763. *
  27764. * The example below makes use of this feature:
  27765. * ```html
  27766. * <header ng-repeat-start="item in items">
  27767. * Header {{ item }}
  27768. * </header>
  27769. * <div class="body">
  27770. * Body {{ item }}
  27771. * </div>
  27772. * <footer ng-repeat-end>
  27773. * Footer {{ item }}
  27774. * </footer>
  27775. * ```
  27776. *
  27777. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  27778. * ```html
  27779. * <header>
  27780. * Header A
  27781. * </header>
  27782. * <div class="body">
  27783. * Body A
  27784. * </div>
  27785. * <footer>
  27786. * Footer A
  27787. * </footer>
  27788. * <header>
  27789. * Header B
  27790. * </header>
  27791. * <div class="body">
  27792. * Body B
  27793. * </div>
  27794. * <footer>
  27795. * Footer B
  27796. * </footer>
  27797. * ```
  27798. *
  27799. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  27800. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  27801. *
  27802. * @animations
  27803. * | Animation | Occurs |
  27804. * |----------------------------------|-------------------------------------|
  27805. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  27806. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  27807. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  27808. *
  27809. * See the example below for defining CSS animations with ngRepeat.
  27810. *
  27811. * @element ANY
  27812. * @scope
  27813. * @priority 1000
  27814. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  27815. * formats are currently supported:
  27816. *
  27817. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  27818. * is a scope expression giving the collection to enumerate.
  27819. *
  27820. * For example: `album in artist.albums`.
  27821. *
  27822. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  27823. * and `expression` is the scope expression giving the collection to enumerate.
  27824. *
  27825. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  27826. *
  27827. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  27828. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  27829. * is specified, ng-repeat associates elements by identity. It is an error to have
  27830. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  27831. * mapped to the same DOM element, which is not possible.)
  27832. *
  27833. * Note that the tracking expression must come last, after any filters, and the alias expression.
  27834. *
  27835. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  27836. * will be associated by item identity in the array.
  27837. *
  27838. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  27839. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  27840. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  27841. * element in the same way in the DOM.
  27842. *
  27843. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  27844. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  27845. * property is same.
  27846. *
  27847. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  27848. * to items in conjunction with a tracking expression.
  27849. *
  27850. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  27851. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  27852. * when a filter is active on the repeater, but the filtered result set is empty.
  27853. *
  27854. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  27855. * the items have been processed through the filter.
  27856. *
  27857. * 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
  27858. * (and not as operator, inside an expression).
  27859. *
  27860. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  27861. *
  27862. * @example
  27863. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  27864. * results by name or by age. New (entering) and removed (leaving) items are animated.
  27865. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  27866. <file name="index.html">
  27867. <div ng-controller="repeatController">
  27868. I have {{friends.length}} friends. They are:
  27869. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  27870. <ul class="example-animate-container">
  27871. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  27872. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  27873. </li>
  27874. <li class="animate-repeat" ng-if="results.length === 0">
  27875. <strong>No results found...</strong>
  27876. </li>
  27877. </ul>
  27878. </div>
  27879. </file>
  27880. <file name="script.js">
  27881. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  27882. $scope.friends = [
  27883. {name:'John', age:25, gender:'boy'},
  27884. {name:'Jessie', age:30, gender:'girl'},
  27885. {name:'Johanna', age:28, gender:'girl'},
  27886. {name:'Joy', age:15, gender:'girl'},
  27887. {name:'Mary', age:28, gender:'girl'},
  27888. {name:'Peter', age:95, gender:'boy'},
  27889. {name:'Sebastian', age:50, gender:'boy'},
  27890. {name:'Erika', age:27, gender:'girl'},
  27891. {name:'Patrick', age:40, gender:'boy'},
  27892. {name:'Samantha', age:60, gender:'girl'}
  27893. ];
  27894. });
  27895. </file>
  27896. <file name="animations.css">
  27897. .example-animate-container {
  27898. background:white;
  27899. border:1px solid black;
  27900. list-style:none;
  27901. margin:0;
  27902. padding:0 10px;
  27903. }
  27904. .animate-repeat {
  27905. line-height:30px;
  27906. list-style:none;
  27907. box-sizing:border-box;
  27908. }
  27909. .animate-repeat.ng-move,
  27910. .animate-repeat.ng-enter,
  27911. .animate-repeat.ng-leave {
  27912. transition:all linear 0.5s;
  27913. }
  27914. .animate-repeat.ng-leave.ng-leave-active,
  27915. .animate-repeat.ng-move,
  27916. .animate-repeat.ng-enter {
  27917. opacity:0;
  27918. max-height:0;
  27919. }
  27920. .animate-repeat.ng-leave,
  27921. .animate-repeat.ng-move.ng-move-active,
  27922. .animate-repeat.ng-enter.ng-enter-active {
  27923. opacity:1;
  27924. max-height:30px;
  27925. }
  27926. </file>
  27927. <file name="protractor.js" type="protractor">
  27928. var friends = element.all(by.repeater('friend in friends'));
  27929. it('should render initial data set', function() {
  27930. expect(friends.count()).toBe(10);
  27931. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  27932. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  27933. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  27934. expect(element(by.binding('friends.length')).getText())
  27935. .toMatch("I have 10 friends. They are:");
  27936. });
  27937. it('should update repeater when filter predicate changes', function() {
  27938. expect(friends.count()).toBe(10);
  27939. element(by.model('q')).sendKeys('ma');
  27940. expect(friends.count()).toBe(2);
  27941. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  27942. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  27943. });
  27944. </file>
  27945. </example>
  27946. */
  27947. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  27948. var NG_REMOVED = '$$NG_REMOVED';
  27949. var ngRepeatMinErr = minErr('ngRepeat');
  27950. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  27951. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  27952. scope[valueIdentifier] = value;
  27953. if (keyIdentifier) scope[keyIdentifier] = key;
  27954. scope.$index = index;
  27955. scope.$first = (index === 0);
  27956. scope.$last = (index === (arrayLength - 1));
  27957. scope.$middle = !(scope.$first || scope.$last);
  27958. // eslint-disable-next-line no-bitwise
  27959. scope.$odd = !(scope.$even = (index & 1) === 0);
  27960. };
  27961. var getBlockStart = function(block) {
  27962. return block.clone[0];
  27963. };
  27964. var getBlockEnd = function(block) {
  27965. return block.clone[block.clone.length - 1];
  27966. };
  27967. return {
  27968. restrict: 'A',
  27969. multiElement: true,
  27970. transclude: 'element',
  27971. priority: 1000,
  27972. terminal: true,
  27973. $$tlb: true,
  27974. compile: function ngRepeatCompile($element, $attr) {
  27975. var expression = $attr.ngRepeat;
  27976. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  27977. 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*$/);
  27978. if (!match) {
  27979. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  27980. expression);
  27981. }
  27982. var lhs = match[1];
  27983. var rhs = match[2];
  27984. var aliasAs = match[3];
  27985. var trackByExp = match[4];
  27986. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  27987. if (!match) {
  27988. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  27989. lhs);
  27990. }
  27991. var valueIdentifier = match[3] || match[1];
  27992. var keyIdentifier = match[2];
  27993. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  27994. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  27995. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  27996. aliasAs);
  27997. }
  27998. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  27999. var hashFnLocals = {$id: hashKey};
  28000. if (trackByExp) {
  28001. trackByExpGetter = $parse(trackByExp);
  28002. } else {
  28003. trackByIdArrayFn = function(key, value) {
  28004. return hashKey(value);
  28005. };
  28006. trackByIdObjFn = function(key) {
  28007. return key;
  28008. };
  28009. }
  28010. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28011. if (trackByExpGetter) {
  28012. trackByIdExpFn = function(key, value, index) {
  28013. // assign key, value, and $index to the locals so that they can be used in hash functions
  28014. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28015. hashFnLocals[valueIdentifier] = value;
  28016. hashFnLocals.$index = index;
  28017. return trackByExpGetter($scope, hashFnLocals);
  28018. };
  28019. }
  28020. // Store a list of elements from previous run. This is a hash where key is the item from the
  28021. // iterator, and the value is objects with following properties.
  28022. // - scope: bound scope
  28023. // - element: previous element.
  28024. // - index: position
  28025. //
  28026. // We are using no-proto object so that we don't need to guard against inherited props via
  28027. // hasOwnProperty.
  28028. var lastBlockMap = createMap();
  28029. //watch props
  28030. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28031. var index, length,
  28032. previousNode = $element[0], // node that cloned nodes should be inserted after
  28033. // initialized to the comment node anchor
  28034. nextNode,
  28035. // Same as lastBlockMap but it has the current state. It will become the
  28036. // lastBlockMap on the next iteration.
  28037. nextBlockMap = createMap(),
  28038. collectionLength,
  28039. key, value, // key/value of iteration
  28040. trackById,
  28041. trackByIdFn,
  28042. collectionKeys,
  28043. block, // last object information {scope, element, id}
  28044. nextBlockOrder,
  28045. elementsToRemove;
  28046. if (aliasAs) {
  28047. $scope[aliasAs] = collection;
  28048. }
  28049. if (isArrayLike(collection)) {
  28050. collectionKeys = collection;
  28051. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28052. } else {
  28053. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28054. // if object, extract keys, in enumeration order, unsorted
  28055. collectionKeys = [];
  28056. for (var itemKey in collection) {
  28057. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28058. collectionKeys.push(itemKey);
  28059. }
  28060. }
  28061. }
  28062. collectionLength = collectionKeys.length;
  28063. nextBlockOrder = new Array(collectionLength);
  28064. // locate existing items
  28065. for (index = 0; index < collectionLength; index++) {
  28066. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28067. value = collection[key];
  28068. trackById = trackByIdFn(key, value, index);
  28069. if (lastBlockMap[trackById]) {
  28070. // found previously seen block
  28071. block = lastBlockMap[trackById];
  28072. delete lastBlockMap[trackById];
  28073. nextBlockMap[trackById] = block;
  28074. nextBlockOrder[index] = block;
  28075. } else if (nextBlockMap[trackById]) {
  28076. // if collision detected. restore lastBlockMap and throw an error
  28077. forEach(nextBlockOrder, function(block) {
  28078. if (block && block.scope) lastBlockMap[block.id] = block;
  28079. });
  28080. throw ngRepeatMinErr('dupes',
  28081. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28082. expression, trackById, value);
  28083. } else {
  28084. // new never before seen block
  28085. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28086. nextBlockMap[trackById] = true;
  28087. }
  28088. }
  28089. // remove leftover items
  28090. for (var blockKey in lastBlockMap) {
  28091. block = lastBlockMap[blockKey];
  28092. elementsToRemove = getBlockNodes(block.clone);
  28093. $animate.leave(elementsToRemove);
  28094. if (elementsToRemove[0].parentNode) {
  28095. // if the element was not removed yet because of pending animation, mark it as deleted
  28096. // so that we can ignore it later
  28097. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28098. elementsToRemove[index][NG_REMOVED] = true;
  28099. }
  28100. }
  28101. block.scope.$destroy();
  28102. }
  28103. // we are not using forEach for perf reasons (trying to avoid #call)
  28104. for (index = 0; index < collectionLength; index++) {
  28105. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28106. value = collection[key];
  28107. block = nextBlockOrder[index];
  28108. if (block.scope) {
  28109. // if we have already seen this object, then we need to reuse the
  28110. // associated scope/element
  28111. nextNode = previousNode;
  28112. // skip nodes that are already pending removal via leave animation
  28113. do {
  28114. nextNode = nextNode.nextSibling;
  28115. } while (nextNode && nextNode[NG_REMOVED]);
  28116. if (getBlockStart(block) !== nextNode) {
  28117. // existing item which got moved
  28118. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28119. }
  28120. previousNode = getBlockEnd(block);
  28121. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28122. } else {
  28123. // new item which we don't know about
  28124. $transclude(function ngRepeatTransclude(clone, scope) {
  28125. block.scope = scope;
  28126. // http://jsperf.com/clone-vs-createcomment
  28127. var endNode = ngRepeatEndComment.cloneNode(false);
  28128. clone[clone.length++] = endNode;
  28129. $animate.enter(clone, null, previousNode);
  28130. previousNode = endNode;
  28131. // Note: We only need the first/last node of the cloned nodes.
  28132. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28133. // by a directive with templateUrl when its template arrives.
  28134. block.clone = clone;
  28135. nextBlockMap[block.id] = block;
  28136. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28137. });
  28138. }
  28139. }
  28140. lastBlockMap = nextBlockMap;
  28141. });
  28142. };
  28143. }
  28144. };
  28145. }];
  28146. var NG_HIDE_CLASS = 'ng-hide';
  28147. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28148. /**
  28149. * @ngdoc directive
  28150. * @name ngShow
  28151. * @multiElement
  28152. *
  28153. * @description
  28154. * The `ngShow` directive shows or hides the given HTML element based on the expression
  28155. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  28156. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  28157. * in AngularJS and sets the display style to none (using an !important flag).
  28158. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  28159. *
  28160. * ```html
  28161. * <!-- when $scope.myValue is truthy (element is visible) -->
  28162. * <div ng-show="myValue"></div>
  28163. *
  28164. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28165. * <div ng-show="myValue" class="ng-hide"></div>
  28166. * ```
  28167. *
  28168. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  28169. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  28170. * from the element causing the element not to appear hidden.
  28171. *
  28172. * ## Why is !important used?
  28173. *
  28174. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  28175. * can be easily overridden by heavier selectors. For example, something as simple
  28176. * as changing the display style on a HTML list item would make hidden elements appear visible.
  28177. * This also becomes a bigger issue when dealing with CSS frameworks.
  28178. *
  28179. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  28180. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  28181. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  28182. *
  28183. * ### Overriding `.ng-hide`
  28184. *
  28185. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  28186. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  28187. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  28188. * with extra animation classes that can be added.
  28189. *
  28190. * ```css
  28191. * .ng-hide:not(.ng-hide-animate) {
  28192. * /&#42; this is just another form of hiding an element &#42;/
  28193. * display: block!important;
  28194. * position: absolute;
  28195. * top: -9999px;
  28196. * left: -9999px;
  28197. * }
  28198. * ```
  28199. *
  28200. * By default you don't need to override in CSS anything and the animations will work around the display style.
  28201. *
  28202. * ## A note about animations with `ngShow`
  28203. *
  28204. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  28205. * is true and false. This system works like the animation system present with ngClass except that
  28206. * you must also include the !important flag to override the display property
  28207. * so that you can perform an animation when the element is hidden during the time of the animation.
  28208. *
  28209. * ```css
  28210. * //
  28211. * //a working example can be found at the bottom of this page
  28212. * //
  28213. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28214. * /&#42; this is required as of 1.3x to properly
  28215. * apply all styling in a show/hide animation &#42;/
  28216. * transition: 0s linear all;
  28217. * }
  28218. *
  28219. * .my-element.ng-hide-add-active,
  28220. * .my-element.ng-hide-remove-active {
  28221. * /&#42; the transition is defined in the active class &#42;/
  28222. * transition: 1s linear all;
  28223. * }
  28224. *
  28225. * .my-element.ng-hide-add { ... }
  28226. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28227. * .my-element.ng-hide-remove { ... }
  28228. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28229. * ```
  28230. *
  28231. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  28232. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  28233. *
  28234. * @animations
  28235. * | Animation | Occurs |
  28236. * |----------------------------------|-------------------------------------|
  28237. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |
  28238. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  28239. *
  28240. * @element ANY
  28241. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  28242. * then the element is shown or hidden respectively.
  28243. *
  28244. * @example
  28245. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show">
  28246. <file name="index.html">
  28247. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  28248. <div>
  28249. Show:
  28250. <div class="check-element animate-show" ng-show="checked">
  28251. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  28252. </div>
  28253. </div>
  28254. <div>
  28255. Hide:
  28256. <div class="check-element animate-show" ng-hide="checked">
  28257. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  28258. </div>
  28259. </div>
  28260. </file>
  28261. <file name="glyphicons.css">
  28262. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  28263. </file>
  28264. <file name="animations.css">
  28265. .animate-show {
  28266. line-height: 20px;
  28267. opacity: 1;
  28268. padding: 10px;
  28269. border: 1px solid black;
  28270. background: white;
  28271. }
  28272. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  28273. transition: all linear 0.5s;
  28274. }
  28275. .animate-show.ng-hide {
  28276. line-height: 0;
  28277. opacity: 0;
  28278. padding: 0 10px;
  28279. }
  28280. .check-element {
  28281. padding: 10px;
  28282. border: 1px solid black;
  28283. background: white;
  28284. }
  28285. </file>
  28286. <file name="protractor.js" type="protractor">
  28287. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  28288. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  28289. it('should check ng-show / ng-hide', function() {
  28290. expect(thumbsUp.isDisplayed()).toBeFalsy();
  28291. expect(thumbsDown.isDisplayed()).toBeTruthy();
  28292. element(by.model('checked')).click();
  28293. expect(thumbsUp.isDisplayed()).toBeTruthy();
  28294. expect(thumbsDown.isDisplayed()).toBeFalsy();
  28295. });
  28296. </file>
  28297. </example>
  28298. */
  28299. var ngShowDirective = ['$animate', function($animate) {
  28300. return {
  28301. restrict: 'A',
  28302. multiElement: true,
  28303. link: function(scope, element, attr) {
  28304. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28305. // we're adding a temporary, animation-specific class for ng-hide since this way
  28306. // we can control when the element is actually displayed on screen without having
  28307. // to have a global/greedy CSS selector that breaks when other animations are run.
  28308. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28309. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28310. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28311. });
  28312. });
  28313. }
  28314. };
  28315. }];
  28316. /**
  28317. * @ngdoc directive
  28318. * @name ngHide
  28319. * @multiElement
  28320. *
  28321. * @description
  28322. * The `ngHide` directive shows or hides the given HTML element based on the expression
  28323. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  28324. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  28325. * in AngularJS and sets the display style to none (using an !important flag).
  28326. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  28327. *
  28328. * ```html
  28329. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28330. * <div ng-hide="myValue" class="ng-hide"></div>
  28331. *
  28332. * <!-- when $scope.myValue is falsy (element is visible) -->
  28333. * <div ng-hide="myValue"></div>
  28334. * ```
  28335. *
  28336. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  28337. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  28338. * from the element causing the element not to appear hidden.
  28339. *
  28340. * ## Why is !important used?
  28341. *
  28342. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  28343. * can be easily overridden by heavier selectors. For example, something as simple
  28344. * as changing the display style on a HTML list item would make hidden elements appear visible.
  28345. * This also becomes a bigger issue when dealing with CSS frameworks.
  28346. *
  28347. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  28348. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  28349. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  28350. *
  28351. * ### Overriding `.ng-hide`
  28352. *
  28353. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  28354. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  28355. * class in CSS:
  28356. *
  28357. * ```css
  28358. * .ng-hide {
  28359. * /&#42; this is just another form of hiding an element &#42;/
  28360. * display: block!important;
  28361. * position: absolute;
  28362. * top: -9999px;
  28363. * left: -9999px;
  28364. * }
  28365. * ```
  28366. *
  28367. * By default you don't need to override in CSS anything and the animations will work around the display style.
  28368. *
  28369. * ## A note about animations with `ngHide`
  28370. *
  28371. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  28372. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  28373. * CSS class is added and removed for you instead of your own CSS class.
  28374. *
  28375. * ```css
  28376. * //
  28377. * //a working example can be found at the bottom of this page
  28378. * //
  28379. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28380. * transition: 0.5s linear all;
  28381. * }
  28382. *
  28383. * .my-element.ng-hide-add { ... }
  28384. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28385. * .my-element.ng-hide-remove { ... }
  28386. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28387. * ```
  28388. *
  28389. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  28390. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  28391. *
  28392. * @animations
  28393. * | Animation | Occurs |
  28394. * |----------------------------------|-------------------------------------|
  28395. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  28396. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  28397. *
  28398. *
  28399. * @element ANY
  28400. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  28401. * the element is shown or hidden respectively.
  28402. *
  28403. * @example
  28404. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide">
  28405. <file name="index.html">
  28406. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  28407. <div>
  28408. Show:
  28409. <div class="check-element animate-hide" ng-show="checked">
  28410. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  28411. </div>
  28412. </div>
  28413. <div>
  28414. Hide:
  28415. <div class="check-element animate-hide" ng-hide="checked">
  28416. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  28417. </div>
  28418. </div>
  28419. </file>
  28420. <file name="glyphicons.css">
  28421. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  28422. </file>
  28423. <file name="animations.css">
  28424. .animate-hide {
  28425. transition: all linear 0.5s;
  28426. line-height: 20px;
  28427. opacity: 1;
  28428. padding: 10px;
  28429. border: 1px solid black;
  28430. background: white;
  28431. }
  28432. .animate-hide.ng-hide {
  28433. line-height: 0;
  28434. opacity: 0;
  28435. padding: 0 10px;
  28436. }
  28437. .check-element {
  28438. padding: 10px;
  28439. border: 1px solid black;
  28440. background: white;
  28441. }
  28442. </file>
  28443. <file name="protractor.js" type="protractor">
  28444. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  28445. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  28446. it('should check ng-show / ng-hide', function() {
  28447. expect(thumbsUp.isDisplayed()).toBeFalsy();
  28448. expect(thumbsDown.isDisplayed()).toBeTruthy();
  28449. element(by.model('checked')).click();
  28450. expect(thumbsUp.isDisplayed()).toBeTruthy();
  28451. expect(thumbsDown.isDisplayed()).toBeFalsy();
  28452. });
  28453. </file>
  28454. </example>
  28455. */
  28456. var ngHideDirective = ['$animate', function($animate) {
  28457. return {
  28458. restrict: 'A',
  28459. multiElement: true,
  28460. link: function(scope, element, attr) {
  28461. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  28462. // The comment inside of the ngShowDirective explains why we add and
  28463. // remove a temporary class for the show/hide animation
  28464. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  28465. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28466. });
  28467. });
  28468. }
  28469. };
  28470. }];
  28471. /**
  28472. * @ngdoc directive
  28473. * @name ngStyle
  28474. * @restrict AC
  28475. *
  28476. * @description
  28477. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  28478. *
  28479. * @knownIssue
  28480. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  28481. * attribute, when using the `ngStyle` directive on the same element.
  28482. * See {@link guide/interpolation#known-issues here} for more info.
  28483. *
  28484. * @element ANY
  28485. * @param {expression} ngStyle
  28486. *
  28487. * {@link guide/expression Expression} which evals to an
  28488. * object whose keys are CSS style names and values are corresponding values for those CSS
  28489. * keys.
  28490. *
  28491. * Since some CSS style names are not valid keys for an object, they must be quoted.
  28492. * See the 'background-color' style in the example below.
  28493. *
  28494. * @example
  28495. <example name="ng-style">
  28496. <file name="index.html">
  28497. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  28498. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  28499. <input type="button" value="clear" ng-click="myStyle={}">
  28500. <br/>
  28501. <span ng-style="myStyle">Sample Text</span>
  28502. <pre>myStyle={{myStyle}}</pre>
  28503. </file>
  28504. <file name="style.css">
  28505. span {
  28506. color: black;
  28507. }
  28508. </file>
  28509. <file name="protractor.js" type="protractor">
  28510. var colorSpan = element(by.css('span'));
  28511. it('should check ng-style', function() {
  28512. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28513. element(by.css('input[value=\'set color\']')).click();
  28514. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  28515. element(by.css('input[value=clear]')).click();
  28516. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28517. });
  28518. </file>
  28519. </example>
  28520. */
  28521. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  28522. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  28523. if (oldStyles && (newStyles !== oldStyles)) {
  28524. forEach(oldStyles, function(val, style) { element.css(style, '');});
  28525. }
  28526. if (newStyles) element.css(newStyles);
  28527. }, true);
  28528. });
  28529. /**
  28530. * @ngdoc directive
  28531. * @name ngSwitch
  28532. * @restrict EA
  28533. *
  28534. * @description
  28535. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  28536. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  28537. * as specified in the template.
  28538. *
  28539. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  28540. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  28541. * matches the value obtained from the evaluated expression. In other words, you define a container element
  28542. * (where you place the directive), place an expression on the **`on="..."` attribute**
  28543. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  28544. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  28545. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  28546. * attribute is displayed.
  28547. *
  28548. * <div class="alert alert-info">
  28549. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  28550. * as literal string values to match against.
  28551. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  28552. * value of the expression `$scope.someVal`.
  28553. * </div>
  28554. * @animations
  28555. * | Animation | Occurs |
  28556. * |----------------------------------|-------------------------------------|
  28557. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  28558. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  28559. *
  28560. * @usage
  28561. *
  28562. * ```
  28563. * <ANY ng-switch="expression">
  28564. * <ANY ng-switch-when="matchValue1">...</ANY>
  28565. * <ANY ng-switch-when="matchValue2">...</ANY>
  28566. * <ANY ng-switch-default>...</ANY>
  28567. * </ANY>
  28568. * ```
  28569. *
  28570. *
  28571. * @scope
  28572. * @priority 1200
  28573. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  28574. * On child elements add:
  28575. *
  28576. * * `ngSwitchWhen`: the case statement to match against. If match then this
  28577. * case will be displayed. If the same match appears multiple times, all the
  28578. * elements will be displayed. It is possible to associate multiple values to
  28579. * the same `ngSwitchWhen` by defining the optional attribute
  28580. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  28581. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  28582. * if any of the `ngSwitch` evaluates to any of these tokens.
  28583. * * `ngSwitchDefault`: the default case when no other case match. If there
  28584. * are multiple default cases, all of them will be displayed when no other
  28585. * case match.
  28586. *
  28587. *
  28588. * @example
  28589. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  28590. <file name="index.html">
  28591. <div ng-controller="ExampleController">
  28592. <select ng-model="selection" ng-options="item for item in items">
  28593. </select>
  28594. <code>selection={{selection}}</code>
  28595. <hr/>
  28596. <div class="animate-switch-container"
  28597. ng-switch on="selection">
  28598. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  28599. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  28600. <div class="animate-switch" ng-switch-default>default</div>
  28601. </div>
  28602. </div>
  28603. </file>
  28604. <file name="script.js">
  28605. angular.module('switchExample', ['ngAnimate'])
  28606. .controller('ExampleController', ['$scope', function($scope) {
  28607. $scope.items = ['settings', 'home', 'options', 'other'];
  28608. $scope.selection = $scope.items[0];
  28609. }]);
  28610. </file>
  28611. <file name="animations.css">
  28612. .animate-switch-container {
  28613. position:relative;
  28614. background:white;
  28615. border:1px solid black;
  28616. height:40px;
  28617. overflow:hidden;
  28618. }
  28619. .animate-switch {
  28620. padding:10px;
  28621. }
  28622. .animate-switch.ng-animate {
  28623. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  28624. position:absolute;
  28625. top:0;
  28626. left:0;
  28627. right:0;
  28628. bottom:0;
  28629. }
  28630. .animate-switch.ng-leave.ng-leave-active,
  28631. .animate-switch.ng-enter {
  28632. top:-50px;
  28633. }
  28634. .animate-switch.ng-leave,
  28635. .animate-switch.ng-enter.ng-enter-active {
  28636. top:0;
  28637. }
  28638. </file>
  28639. <file name="protractor.js" type="protractor">
  28640. var switchElem = element(by.css('[ng-switch]'));
  28641. var select = element(by.model('selection'));
  28642. it('should start in settings', function() {
  28643. expect(switchElem.getText()).toMatch(/Settings Div/);
  28644. });
  28645. it('should change to home', function() {
  28646. select.all(by.css('option')).get(1).click();
  28647. expect(switchElem.getText()).toMatch(/Home Span/);
  28648. });
  28649. it('should change to settings via "options"', function() {
  28650. select.all(by.css('option')).get(2).click();
  28651. expect(switchElem.getText()).toMatch(/Settings Div/);
  28652. });
  28653. it('should select default', function() {
  28654. select.all(by.css('option')).get(3).click();
  28655. expect(switchElem.getText()).toMatch(/default/);
  28656. });
  28657. </file>
  28658. </example>
  28659. */
  28660. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  28661. return {
  28662. require: 'ngSwitch',
  28663. // asks for $scope to fool the BC controller module
  28664. controller: ['$scope', function NgSwitchController() {
  28665. this.cases = {};
  28666. }],
  28667. link: function(scope, element, attr, ngSwitchController) {
  28668. var watchExpr = attr.ngSwitch || attr.on,
  28669. selectedTranscludes = [],
  28670. selectedElements = [],
  28671. previousLeaveAnimations = [],
  28672. selectedScopes = [];
  28673. var spliceFactory = function(array, index) {
  28674. return function(response) {
  28675. if (response !== false) array.splice(index, 1);
  28676. };
  28677. };
  28678. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  28679. var i, ii;
  28680. // Start with the last, in case the array is modified during the loop
  28681. while (previousLeaveAnimations.length) {
  28682. $animate.cancel(previousLeaveAnimations.pop());
  28683. }
  28684. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  28685. var selected = getBlockNodes(selectedElements[i].clone);
  28686. selectedScopes[i].$destroy();
  28687. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  28688. runner.done(spliceFactory(previousLeaveAnimations, i));
  28689. }
  28690. selectedElements.length = 0;
  28691. selectedScopes.length = 0;
  28692. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  28693. forEach(selectedTranscludes, function(selectedTransclude) {
  28694. selectedTransclude.transclude(function(caseElement, selectedScope) {
  28695. selectedScopes.push(selectedScope);
  28696. var anchor = selectedTransclude.element;
  28697. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  28698. var block = { clone: caseElement };
  28699. selectedElements.push(block);
  28700. $animate.enter(caseElement, anchor.parent(), anchor);
  28701. });
  28702. });
  28703. }
  28704. });
  28705. }
  28706. };
  28707. }];
  28708. var ngSwitchWhenDirective = ngDirective({
  28709. transclude: 'element',
  28710. priority: 1200,
  28711. require: '^ngSwitch',
  28712. multiElement: true,
  28713. link: function(scope, element, attrs, ctrl, $transclude) {
  28714. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  28715. // Filter duplicate cases
  28716. function(element, index, array) { return array[index - 1] !== element; }
  28717. );
  28718. forEach(cases, function(whenCase) {
  28719. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  28720. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  28721. });
  28722. }
  28723. });
  28724. var ngSwitchDefaultDirective = ngDirective({
  28725. transclude: 'element',
  28726. priority: 1200,
  28727. require: '^ngSwitch',
  28728. multiElement: true,
  28729. link: function(scope, element, attr, ctrl, $transclude) {
  28730. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  28731. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  28732. }
  28733. });
  28734. /**
  28735. * @ngdoc directive
  28736. * @name ngTransclude
  28737. * @restrict EAC
  28738. *
  28739. * @description
  28740. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  28741. *
  28742. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  28743. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  28744. *
  28745. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  28746. * content of this element will be removed before the transcluded content is inserted.
  28747. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  28748. * content in the case that no transcluded content is provided.
  28749. *
  28750. * @element ANY
  28751. *
  28752. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  28753. * or its value is the same as the name of the attribute then the default slot is used.
  28754. *
  28755. * @example
  28756. * ### Basic transclusion
  28757. * This example demonstrates basic transclusion of content into a component directive.
  28758. * <example name="simpleTranscludeExample" module="transcludeExample">
  28759. * <file name="index.html">
  28760. * <script>
  28761. * angular.module('transcludeExample', [])
  28762. * .directive('pane', function(){
  28763. * return {
  28764. * restrict: 'E',
  28765. * transclude: true,
  28766. * scope: { title:'@' },
  28767. * template: '<div style="border: 1px solid black;">' +
  28768. * '<div style="background-color: gray">{{title}}</div>' +
  28769. * '<ng-transclude></ng-transclude>' +
  28770. * '</div>'
  28771. * };
  28772. * })
  28773. * .controller('ExampleController', ['$scope', function($scope) {
  28774. * $scope.title = 'Lorem Ipsum';
  28775. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  28776. * }]);
  28777. * </script>
  28778. * <div ng-controller="ExampleController">
  28779. * <input ng-model="title" aria-label="title"> <br/>
  28780. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28781. * <pane title="{{title}}"><span>{{text}}</span></pane>
  28782. * </div>
  28783. * </file>
  28784. * <file name="protractor.js" type="protractor">
  28785. * it('should have transcluded', function() {
  28786. * var titleElement = element(by.model('title'));
  28787. * titleElement.clear();
  28788. * titleElement.sendKeys('TITLE');
  28789. * var textElement = element(by.model('text'));
  28790. * textElement.clear();
  28791. * textElement.sendKeys('TEXT');
  28792. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  28793. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  28794. * });
  28795. * </file>
  28796. * </example>
  28797. *
  28798. * @example
  28799. * ### Transclude fallback content
  28800. * This example shows how to use `NgTransclude` with fallback content, that
  28801. * is displayed if no transcluded content is provided.
  28802. *
  28803. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  28804. * <file name="index.html">
  28805. * <script>
  28806. * angular.module('transcludeFallbackContentExample', [])
  28807. * .directive('myButton', function(){
  28808. * return {
  28809. * restrict: 'E',
  28810. * transclude: true,
  28811. * scope: true,
  28812. * template: '<button style="cursor: pointer;">' +
  28813. * '<ng-transclude>' +
  28814. * '<b style="color: red;">Button1</b>' +
  28815. * '</ng-transclude>' +
  28816. * '</button>'
  28817. * };
  28818. * });
  28819. * </script>
  28820. * <!-- fallback button content -->
  28821. * <my-button id="fallback"></my-button>
  28822. * <!-- modified button content -->
  28823. * <my-button id="modified">
  28824. * <i style="color: green;">Button2</i>
  28825. * </my-button>
  28826. * </file>
  28827. * <file name="protractor.js" type="protractor">
  28828. * it('should have different transclude element content', function() {
  28829. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  28830. * expect(element(by.id('modified')).getText()).toBe('Button2');
  28831. * });
  28832. * </file>
  28833. * </example>
  28834. *
  28835. * @example
  28836. * ### Multi-slot transclusion
  28837. * This example demonstrates using multi-slot transclusion in a component directive.
  28838. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  28839. * <file name="index.html">
  28840. * <style>
  28841. * .title, .footer {
  28842. * background-color: gray
  28843. * }
  28844. * </style>
  28845. * <div ng-controller="ExampleController">
  28846. * <input ng-model="title" aria-label="title"> <br/>
  28847. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28848. * <pane>
  28849. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  28850. * <pane-body><p>{{text}}</p></pane-body>
  28851. * </pane>
  28852. * </div>
  28853. * </file>
  28854. * <file name="app.js">
  28855. * angular.module('multiSlotTranscludeExample', [])
  28856. * .directive('pane', function() {
  28857. * return {
  28858. * restrict: 'E',
  28859. * transclude: {
  28860. * 'title': '?paneTitle',
  28861. * 'body': 'paneBody',
  28862. * 'footer': '?paneFooter'
  28863. * },
  28864. * template: '<div style="border: 1px solid black;">' +
  28865. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  28866. * '<div ng-transclude="body"></div>' +
  28867. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  28868. * '</div>'
  28869. * };
  28870. * })
  28871. * .controller('ExampleController', ['$scope', function($scope) {
  28872. * $scope.title = 'Lorem Ipsum';
  28873. * $scope.link = 'https://google.com';
  28874. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  28875. * }]);
  28876. * </file>
  28877. * <file name="protractor.js" type="protractor">
  28878. * it('should have transcluded the title and the body', function() {
  28879. * var titleElement = element(by.model('title'));
  28880. * titleElement.clear();
  28881. * titleElement.sendKeys('TITLE');
  28882. * var textElement = element(by.model('text'));
  28883. * textElement.clear();
  28884. * textElement.sendKeys('TEXT');
  28885. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  28886. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  28887. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  28888. * });
  28889. * </file>
  28890. * </example>
  28891. */
  28892. var ngTranscludeMinErr = minErr('ngTransclude');
  28893. var ngTranscludeDirective = ['$compile', function($compile) {
  28894. return {
  28895. restrict: 'EAC',
  28896. terminal: true,
  28897. compile: function ngTranscludeCompile(tElement) {
  28898. // Remove and cache any original content to act as a fallback
  28899. var fallbackLinkFn = $compile(tElement.contents());
  28900. tElement.empty();
  28901. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  28902. if (!$transclude) {
  28903. throw ngTranscludeMinErr('orphan',
  28904. 'Illegal use of ngTransclude directive in the template! ' +
  28905. 'No parent directive that requires a transclusion found. ' +
  28906. 'Element: {0}',
  28907. startingTag($element));
  28908. }
  28909. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  28910. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  28911. $attrs.ngTransclude = '';
  28912. }
  28913. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  28914. // If the slot is required and no transclusion content is provided then this call will throw an error
  28915. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  28916. // If the slot is optional and no transclusion content is provided then use the fallback content
  28917. if (slotName && !$transclude.isSlotFilled(slotName)) {
  28918. useFallbackContent();
  28919. }
  28920. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  28921. if (clone.length && notWhitespace(clone)) {
  28922. $element.append(clone);
  28923. } else {
  28924. useFallbackContent();
  28925. // There is nothing linked against the transcluded scope since no content was available,
  28926. // so it should be safe to clean up the generated scope.
  28927. transcludedScope.$destroy();
  28928. }
  28929. }
  28930. function useFallbackContent() {
  28931. // Since this is the fallback content rather than the transcluded content,
  28932. // we link against the scope of this directive rather than the transcluded scope
  28933. fallbackLinkFn($scope, function(clone) {
  28934. $element.append(clone);
  28935. });
  28936. }
  28937. function notWhitespace(nodes) {
  28938. for (var i = 0, ii = nodes.length; i < ii; i++) {
  28939. var node = nodes[i];
  28940. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  28941. return true;
  28942. }
  28943. }
  28944. }
  28945. };
  28946. }
  28947. };
  28948. }];
  28949. /**
  28950. * @ngdoc directive
  28951. * @name script
  28952. * @restrict E
  28953. *
  28954. * @description
  28955. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  28956. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  28957. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  28958. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  28959. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  28960. *
  28961. * @param {string} type Must be set to `'text/ng-template'`.
  28962. * @param {string} id Cache name of the template.
  28963. *
  28964. * @example
  28965. <example name="script-tag">
  28966. <file name="index.html">
  28967. <script type="text/ng-template" id="/tpl.html">
  28968. Content of the template.
  28969. </script>
  28970. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  28971. <div id="tpl-content" ng-include src="currentTpl"></div>
  28972. </file>
  28973. <file name="protractor.js" type="protractor">
  28974. it('should load template defined inside script tag', function() {
  28975. element(by.css('#tpl-link')).click();
  28976. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  28977. });
  28978. </file>
  28979. </example>
  28980. */
  28981. var scriptDirective = ['$templateCache', function($templateCache) {
  28982. return {
  28983. restrict: 'E',
  28984. terminal: true,
  28985. compile: function(element, attr) {
  28986. if (attr.type === 'text/ng-template') {
  28987. var templateUrl = attr.id,
  28988. text = element[0].text;
  28989. $templateCache.put(templateUrl, text);
  28990. }
  28991. }
  28992. };
  28993. }];
  28994. /* exported selectDirective, optionDirective */
  28995. var noopNgModelController = { $setViewValue: noop, $render: noop };
  28996. /**
  28997. * @ngdoc type
  28998. * @name select.SelectController
  28999. * @description
  29000. * The controller for the `<select>` directive. This provides support for reading
  29001. * and writing the selected value(s) of the control and also coordinates dynamically
  29002. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  29003. */
  29004. var SelectController =
  29005. ['$element', '$scope', /** @this */ function($element, $scope) {
  29006. var self = this,
  29007. optionsMap = new HashMap();
  29008. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  29009. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  29010. self.ngModelCtrl = noopNgModelController;
  29011. self.multiple = false;
  29012. // The "unknown" option is one that is prepended to the list if the viewValue
  29013. // does not match any of the options. When it is rendered the value of the unknown
  29014. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  29015. //
  29016. // We can't just jqLite('<option>') since jqLite is not smart enough
  29017. // to create it in <select> and IE barfs otherwise.
  29018. self.unknownOption = jqLite(window.document.createElement('option'));
  29019. // The empty option is an option with the value '' that te application developer can
  29020. // provide inside the select. When the model changes to a value that doesn't match an option,
  29021. // it is selected - so if an empty option is provided, no unknown option is generated.
  29022. // However, the empty option is not removed when the model matches an option. It is always selectable
  29023. // and indicates that a "null" selection has been made.
  29024. self.hasEmptyOption = false;
  29025. self.emptyOption = undefined;
  29026. self.renderUnknownOption = function(val) {
  29027. var unknownVal = self.generateUnknownOptionValue(val);
  29028. self.unknownOption.val(unknownVal);
  29029. $element.prepend(self.unknownOption);
  29030. setOptionAsSelected(self.unknownOption);
  29031. $element.val(unknownVal);
  29032. };
  29033. self.updateUnknownOption = function(val) {
  29034. var unknownVal = self.generateUnknownOptionValue(val);
  29035. self.unknownOption.val(unknownVal);
  29036. setOptionAsSelected(self.unknownOption);
  29037. $element.val(unknownVal);
  29038. };
  29039. self.generateUnknownOptionValue = function(val) {
  29040. return '? ' + hashKey(val) + ' ?';
  29041. };
  29042. self.removeUnknownOption = function() {
  29043. if (self.unknownOption.parent()) self.unknownOption.remove();
  29044. };
  29045. self.selectEmptyOption = function() {
  29046. if (self.emptyOption) {
  29047. $element.val('');
  29048. setOptionAsSelected(self.emptyOption);
  29049. }
  29050. };
  29051. self.unselectEmptyOption = function() {
  29052. if (self.hasEmptyOption) {
  29053. self.emptyOption.removeAttr('selected');
  29054. }
  29055. };
  29056. $scope.$on('$destroy', function() {
  29057. // disable unknown option so that we don't do work when the whole select is being destroyed
  29058. self.renderUnknownOption = noop;
  29059. });
  29060. // Read the value of the select control, the implementation of this changes depending
  29061. // upon whether the select can have multiple values and whether ngOptions is at work.
  29062. self.readValue = function readSingleValue() {
  29063. var val = $element.val();
  29064. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  29065. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  29066. if (self.hasOption(realVal)) {
  29067. return realVal;
  29068. }
  29069. return null;
  29070. };
  29071. // Write the value to the select control, the implementation of this changes depending
  29072. // upon whether the select can have multiple values and whether ngOptions is at work.
  29073. self.writeValue = function writeSingleValue(value) {
  29074. // Make sure to remove the selected attribute from the previously selected option
  29075. // Otherwise, screen readers might get confused
  29076. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  29077. if (currentlySelectedOption) currentlySelectedOption.removeAttribute('selected');
  29078. if (self.hasOption(value)) {
  29079. self.removeUnknownOption();
  29080. var hashedVal = hashKey(value);
  29081. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  29082. // Set selected attribute and property on selected option for screen readers
  29083. var selectedOption = $element[0].options[$element[0].selectedIndex];
  29084. setOptionAsSelected(jqLite(selectedOption));
  29085. } else {
  29086. if (value == null && self.emptyOption) {
  29087. self.removeUnknownOption();
  29088. self.selectEmptyOption();
  29089. } else if (self.unknownOption.parent().length) {
  29090. self.updateUnknownOption(value);
  29091. } else {
  29092. self.renderUnknownOption(value);
  29093. }
  29094. }
  29095. };
  29096. // Tell the select control that an option, with the given value, has been added
  29097. self.addOption = function(value, element) {
  29098. // Skip comment nodes, as they only pollute the `optionsMap`
  29099. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29100. assertNotHasOwnProperty(value, '"option value"');
  29101. if (value === '') {
  29102. self.hasEmptyOption = true;
  29103. self.emptyOption = element;
  29104. }
  29105. var count = optionsMap.get(value) || 0;
  29106. optionsMap.put(value, count + 1);
  29107. // Only render at the end of a digest. This improves render performance when many options
  29108. // are added during a digest and ensures all relevant options are correctly marked as selected
  29109. scheduleRender();
  29110. };
  29111. // Tell the select control that an option, with the given value, has been removed
  29112. self.removeOption = function(value) {
  29113. var count = optionsMap.get(value);
  29114. if (count) {
  29115. if (count === 1) {
  29116. optionsMap.remove(value);
  29117. if (value === '') {
  29118. self.hasEmptyOption = false;
  29119. self.emptyOption = undefined;
  29120. }
  29121. } else {
  29122. optionsMap.put(value, count - 1);
  29123. }
  29124. }
  29125. };
  29126. // Check whether the select control has an option matching the given value
  29127. self.hasOption = function(value) {
  29128. return !!optionsMap.get(value);
  29129. };
  29130. var renderScheduled = false;
  29131. function scheduleRender() {
  29132. if (renderScheduled) return;
  29133. renderScheduled = true;
  29134. $scope.$$postDigest(function() {
  29135. renderScheduled = false;
  29136. self.ngModelCtrl.$render();
  29137. });
  29138. }
  29139. var updateScheduled = false;
  29140. function scheduleViewValueUpdate(renderAfter) {
  29141. if (updateScheduled) return;
  29142. updateScheduled = true;
  29143. $scope.$$postDigest(function() {
  29144. if ($scope.$$destroyed) return;
  29145. updateScheduled = false;
  29146. self.ngModelCtrl.$setViewValue(self.readValue());
  29147. if (renderAfter) self.ngModelCtrl.$render();
  29148. });
  29149. }
  29150. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29151. if (optionAttrs.$attr.ngValue) {
  29152. // The value attribute is set by ngValue
  29153. var oldVal, hashedVal = NaN;
  29154. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29155. var removal;
  29156. var previouslySelected = optionElement.prop('selected');
  29157. if (isDefined(hashedVal)) {
  29158. self.removeOption(oldVal);
  29159. delete self.selectValueMap[hashedVal];
  29160. removal = true;
  29161. }
  29162. hashedVal = hashKey(newVal);
  29163. oldVal = newVal;
  29164. self.selectValueMap[hashedVal] = newVal;
  29165. self.addOption(newVal, optionElement);
  29166. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29167. // from firing a second time. Other $observers on value will also get the result of the
  29168. // ngValue expression, not the hashed value
  29169. optionElement.attr('value', hashedVal);
  29170. if (removal && previouslySelected) {
  29171. scheduleViewValueUpdate();
  29172. }
  29173. });
  29174. } else if (interpolateValueFn) {
  29175. // The value attribute is interpolated
  29176. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29177. // This method is overwritten in ngOptions and has side-effects!
  29178. self.readValue();
  29179. var removal;
  29180. var previouslySelected = optionElement.prop('selected');
  29181. if (isDefined(oldVal)) {
  29182. self.removeOption(oldVal);
  29183. removal = true;
  29184. }
  29185. oldVal = newVal;
  29186. self.addOption(newVal, optionElement);
  29187. if (removal && previouslySelected) {
  29188. scheduleViewValueUpdate();
  29189. }
  29190. });
  29191. } else if (interpolateTextFn) {
  29192. // The text content is interpolated
  29193. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  29194. optionAttrs.$set('value', newVal);
  29195. var previouslySelected = optionElement.prop('selected');
  29196. if (oldVal !== newVal) {
  29197. self.removeOption(oldVal);
  29198. }
  29199. self.addOption(newVal, optionElement);
  29200. if (oldVal && previouslySelected) {
  29201. scheduleViewValueUpdate();
  29202. }
  29203. });
  29204. } else {
  29205. // The value attribute is static
  29206. self.addOption(optionAttrs.value, optionElement);
  29207. }
  29208. optionAttrs.$observe('disabled', function(newVal) {
  29209. // Since model updates will also select disabled options (like ngOptions),
  29210. // we only have to handle options becoming disabled, not enabled
  29211. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  29212. if (self.multiple) {
  29213. scheduleViewValueUpdate(true);
  29214. } else {
  29215. self.ngModelCtrl.$setViewValue(null);
  29216. self.ngModelCtrl.$render();
  29217. }
  29218. }
  29219. });
  29220. optionElement.on('$destroy', function() {
  29221. var currentValue = self.readValue();
  29222. var removeValue = optionAttrs.value;
  29223. self.removeOption(removeValue);
  29224. self.ngModelCtrl.$render();
  29225. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  29226. currentValue === removeValue
  29227. ) {
  29228. // When multiple (selected) options are destroyed at the same time, we don't want
  29229. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  29230. scheduleViewValueUpdate(true);
  29231. }
  29232. });
  29233. };
  29234. function setOptionAsSelected(optionEl) {
  29235. optionEl.prop('selected', true); // needed for IE
  29236. optionEl.attr('selected', true);
  29237. }
  29238. }];
  29239. /**
  29240. * @ngdoc directive
  29241. * @name select
  29242. * @restrict E
  29243. *
  29244. * @description
  29245. * HTML `select` element with angular data-binding.
  29246. *
  29247. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  29248. * between the scope and the `<select>` control (including setting default values).
  29249. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  29250. * {@link ngOptions `ngOptions`} directives.
  29251. *
  29252. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  29253. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  29254. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  29255. * Value and textContent can be interpolated.
  29256. *
  29257. * ## Matching model and option values
  29258. *
  29259. * In general, the match between the model and an option is evaluated by strictly comparing the model
  29260. * value against the value of the available options.
  29261. *
  29262. * If you are setting the option value with the option's `value` attribute, or textContent, the
  29263. * value will always be a `string` which means that the model value must also be a string.
  29264. * Otherwise the `select` directive cannot match them correctly.
  29265. *
  29266. * To bind the model to a non-string value, you can use one of the following strategies:
  29267. * - the {@link ng.ngOptions `ngOptions`} directive
  29268. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  29269. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  29270. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  29271. * - model $parsers / $formatters to convert the string value
  29272. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  29273. *
  29274. * If the viewValue of `ngModel` does not match any of the options, then the control
  29275. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  29276. *
  29277. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29278. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29279. * option. See example below for demonstration.
  29280. *
  29281. * ## Choosing between `ngRepeat` and `ngOptions`
  29282. *
  29283. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  29284. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  29285. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29286. * comprehension expression
  29287. * - reduced memory consumption by not creating a new scope for each repeated instance
  29288. * - increased render speed by creating the options in a documentFragment instead of individually
  29289. *
  29290. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  29291. * Chrome and Internet Explorer / Edge.
  29292. *
  29293. *
  29294. * @param {string} ngModel Assignable angular expression to data-bind to.
  29295. * @param {string=} name Property name of the form under which the control is published.
  29296. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  29297. * bound to the model as an array.
  29298. * @param {string=} required Sets `required` validation error key if the value is not entered.
  29299. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  29300. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  29301. * when you want to data-bind to the required attribute.
  29302. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  29303. * interaction with the select element.
  29304. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  29305. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  29306. *
  29307. * @example
  29308. * ### Simple `select` elements with static options
  29309. *
  29310. * <example name="static-select" module="staticSelect">
  29311. * <file name="index.html">
  29312. * <div ng-controller="ExampleController">
  29313. * <form name="myForm">
  29314. * <label for="singleSelect"> Single select: </label><br>
  29315. * <select name="singleSelect" ng-model="data.singleSelect">
  29316. * <option value="option-1">Option 1</option>
  29317. * <option value="option-2">Option 2</option>
  29318. * </select><br>
  29319. *
  29320. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  29321. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  29322. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  29323. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  29324. * <option value="option-2">Option 2</option>
  29325. * </select><br>
  29326. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29327. * <tt>singleSelect = {{data.singleSelect}}</tt>
  29328. *
  29329. * <hr>
  29330. * <label for="multipleSelect"> Multiple select: </label><br>
  29331. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  29332. * <option value="option-1">Option 1</option>
  29333. * <option value="option-2">Option 2</option>
  29334. * <option value="option-3">Option 3</option>
  29335. * </select><br>
  29336. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  29337. * </form>
  29338. * </div>
  29339. * </file>
  29340. * <file name="app.js">
  29341. * angular.module('staticSelect', [])
  29342. * .controller('ExampleController', ['$scope', function($scope) {
  29343. * $scope.data = {
  29344. * singleSelect: null,
  29345. * multipleSelect: [],
  29346. * option1: 'option-1'
  29347. * };
  29348. *
  29349. * $scope.forceUnknownOption = function() {
  29350. * $scope.data.singleSelect = 'nonsense';
  29351. * };
  29352. * }]);
  29353. * </file>
  29354. *</example>
  29355. *
  29356. * ### Using `ngRepeat` to generate `select` options
  29357. * <example name="select-ngrepeat" module="ngrepeatSelect">
  29358. * <file name="index.html">
  29359. * <div ng-controller="ExampleController">
  29360. * <form name="myForm">
  29361. * <label for="repeatSelect"> Repeat select: </label>
  29362. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  29363. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  29364. * </select>
  29365. * </form>
  29366. * <hr>
  29367. * <tt>model = {{data.model}}</tt><br/>
  29368. * </div>
  29369. * </file>
  29370. * <file name="app.js">
  29371. * angular.module('ngrepeatSelect', [])
  29372. * .controller('ExampleController', ['$scope', function($scope) {
  29373. * $scope.data = {
  29374. * model: null,
  29375. * availableOptions: [
  29376. * {id: '1', name: 'Option A'},
  29377. * {id: '2', name: 'Option B'},
  29378. * {id: '3', name: 'Option C'}
  29379. * ]
  29380. * };
  29381. * }]);
  29382. * </file>
  29383. *</example>
  29384. *
  29385. * ### Using `ngValue` to bind the model to an array of objects
  29386. * <example name="select-ngvalue" module="ngvalueSelect">
  29387. * <file name="index.html">
  29388. * <div ng-controller="ExampleController">
  29389. * <form name="myForm">
  29390. * <label for="ngvalueselect"> ngvalue select: </label>
  29391. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  29392. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  29393. * </select>
  29394. * </form>
  29395. * <hr>
  29396. * <pre>model = {{data.model | json}}</pre><br/>
  29397. * </div>
  29398. * </file>
  29399. * <file name="app.js">
  29400. * angular.module('ngvalueSelect', [])
  29401. * .controller('ExampleController', ['$scope', function($scope) {
  29402. * $scope.data = {
  29403. * model: null,
  29404. * availableOptions: [
  29405. {value: 'myString', name: 'string'},
  29406. {value: 1, name: 'integer'},
  29407. {value: true, name: 'boolean'},
  29408. {value: null, name: 'null'},
  29409. {value: {prop: 'value'}, name: 'object'},
  29410. {value: ['a'], name: 'array'}
  29411. * ]
  29412. * };
  29413. * }]);
  29414. * </file>
  29415. *</example>
  29416. *
  29417. * ### Using `select` with `ngOptions` and setting a default value
  29418. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  29419. *
  29420. * <example name="select-with-default-values" module="defaultValueSelect">
  29421. * <file name="index.html">
  29422. * <div ng-controller="ExampleController">
  29423. * <form name="myForm">
  29424. * <label for="mySelect">Make a choice:</label>
  29425. * <select name="mySelect" id="mySelect"
  29426. * ng-options="option.name for option in data.availableOptions track by option.id"
  29427. * ng-model="data.selectedOption"></select>
  29428. * </form>
  29429. * <hr>
  29430. * <tt>option = {{data.selectedOption}}</tt><br/>
  29431. * </div>
  29432. * </file>
  29433. * <file name="app.js">
  29434. * angular.module('defaultValueSelect', [])
  29435. * .controller('ExampleController', ['$scope', function($scope) {
  29436. * $scope.data = {
  29437. * availableOptions: [
  29438. * {id: '1', name: 'Option A'},
  29439. * {id: '2', name: 'Option B'},
  29440. * {id: '3', name: 'Option C'}
  29441. * ],
  29442. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  29443. * };
  29444. * }]);
  29445. * </file>
  29446. *</example>
  29447. *
  29448. *
  29449. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  29450. *
  29451. * <example name="select-with-non-string-options" module="nonStringSelect">
  29452. * <file name="index.html">
  29453. * <select ng-model="model.id" convert-to-number>
  29454. * <option value="0">Zero</option>
  29455. * <option value="1">One</option>
  29456. * <option value="2">Two</option>
  29457. * </select>
  29458. * {{ model }}
  29459. * </file>
  29460. * <file name="app.js">
  29461. * angular.module('nonStringSelect', [])
  29462. * .run(function($rootScope) {
  29463. * $rootScope.model = { id: 2 };
  29464. * })
  29465. * .directive('convertToNumber', function() {
  29466. * return {
  29467. * require: 'ngModel',
  29468. * link: function(scope, element, attrs, ngModel) {
  29469. * ngModel.$parsers.push(function(val) {
  29470. * return parseInt(val, 10);
  29471. * });
  29472. * ngModel.$formatters.push(function(val) {
  29473. * return '' + val;
  29474. * });
  29475. * }
  29476. * };
  29477. * });
  29478. * </file>
  29479. * <file name="protractor.js" type="protractor">
  29480. * it('should initialize to model', function() {
  29481. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  29482. * });
  29483. * </file>
  29484. * </example>
  29485. *
  29486. */
  29487. var selectDirective = function() {
  29488. return {
  29489. restrict: 'E',
  29490. require: ['select', '?ngModel'],
  29491. controller: SelectController,
  29492. priority: 1,
  29493. link: {
  29494. pre: selectPreLink,
  29495. post: selectPostLink
  29496. }
  29497. };
  29498. function selectPreLink(scope, element, attr, ctrls) {
  29499. var selectCtrl = ctrls[0];
  29500. var ngModelCtrl = ctrls[1];
  29501. // if ngModel is not defined, we don't need to do anything but set the registerOption
  29502. // function to noop, so options don't get added internally
  29503. if (!ngModelCtrl) {
  29504. selectCtrl.registerOption = noop;
  29505. return;
  29506. }
  29507. selectCtrl.ngModelCtrl = ngModelCtrl;
  29508. // When the selected item(s) changes we delegate getting the value of the select control
  29509. // to the `readValue` method, which can be changed if the select can have multiple
  29510. // selected values or if the options are being generated by `ngOptions`
  29511. element.on('change', function() {
  29512. selectCtrl.removeUnknownOption();
  29513. scope.$apply(function() {
  29514. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  29515. });
  29516. });
  29517. // If the select allows multiple values then we need to modify how we read and write
  29518. // values from and to the control; also what it means for the value to be empty and
  29519. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  29520. // doesn't trigger rendering if only an item in the array changes.
  29521. if (attr.multiple) {
  29522. selectCtrl.multiple = true;
  29523. // Read value now needs to check each option to see if it is selected
  29524. selectCtrl.readValue = function readMultipleValue() {
  29525. var array = [];
  29526. forEach(element.find('option'), function(option) {
  29527. if (option.selected && !option.disabled) {
  29528. var val = option.value;
  29529. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  29530. }
  29531. });
  29532. return array;
  29533. };
  29534. // Write value now needs to set the selected property of each matching option
  29535. selectCtrl.writeValue = function writeMultipleValue(value) {
  29536. var items = new HashMap(value);
  29537. forEach(element.find('option'), function(option) {
  29538. option.selected = isDefined(items.get(option.value)) || isDefined(items.get(selectCtrl.selectValueMap[option.value]));
  29539. });
  29540. };
  29541. // we have to do it on each watch since ngModel watches reference, but
  29542. // we need to work of an array, so we need to see if anything was inserted/removed
  29543. var lastView, lastViewRef = NaN;
  29544. scope.$watch(function selectMultipleWatch() {
  29545. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  29546. lastView = shallowCopy(ngModelCtrl.$viewValue);
  29547. ngModelCtrl.$render();
  29548. }
  29549. lastViewRef = ngModelCtrl.$viewValue;
  29550. });
  29551. // If we are a multiple select then value is now a collection
  29552. // so the meaning of $isEmpty changes
  29553. ngModelCtrl.$isEmpty = function(value) {
  29554. return !value || value.length === 0;
  29555. };
  29556. }
  29557. }
  29558. function selectPostLink(scope, element, attrs, ctrls) {
  29559. // if ngModel is not defined, we don't need to do anything
  29560. var ngModelCtrl = ctrls[1];
  29561. if (!ngModelCtrl) return;
  29562. var selectCtrl = ctrls[0];
  29563. // We delegate rendering to the `writeValue` method, which can be changed
  29564. // if the select can have multiple selected values or if the options are being
  29565. // generated by `ngOptions`.
  29566. // This must be done in the postLink fn to prevent $render to be called before
  29567. // all nodes have been linked correctly.
  29568. ngModelCtrl.$render = function() {
  29569. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  29570. };
  29571. }
  29572. };
  29573. // The option directive is purely designed to communicate the existence (or lack of)
  29574. // of dynamically created (and destroyed) option elements to their containing select
  29575. // directive via its controller.
  29576. var optionDirective = ['$interpolate', function($interpolate) {
  29577. return {
  29578. restrict: 'E',
  29579. priority: 100,
  29580. compile: function(element, attr) {
  29581. var interpolateValueFn, interpolateTextFn;
  29582. if (isDefined(attr.ngValue)) {
  29583. // Will be handled by registerOption
  29584. } else if (isDefined(attr.value)) {
  29585. // If the value attribute is defined, check if it contains an interpolation
  29586. interpolateValueFn = $interpolate(attr.value, true);
  29587. } else {
  29588. // If the value attribute is not defined then we fall back to the
  29589. // text content of the option element, which may be interpolated
  29590. interpolateTextFn = $interpolate(element.text(), true);
  29591. if (!interpolateTextFn) {
  29592. attr.$set('value', element.text());
  29593. }
  29594. }
  29595. return function(scope, element, attr) {
  29596. // This is an optimization over using ^^ since we don't want to have to search
  29597. // all the way to the root of the DOM for every single option element
  29598. var selectCtrlName = '$selectController',
  29599. parent = element.parent(),
  29600. selectCtrl = parent.data(selectCtrlName) ||
  29601. parent.parent().data(selectCtrlName); // in case we are in optgroup
  29602. if (selectCtrl) {
  29603. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  29604. }
  29605. };
  29606. }
  29607. };
  29608. }];
  29609. /**
  29610. * @ngdoc directive
  29611. * @name ngRequired
  29612. * @restrict A
  29613. *
  29614. * @description
  29615. *
  29616. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29617. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  29618. * applied to custom controls.
  29619. *
  29620. * The directive sets the `required` attribute on the element if the Angular expression inside
  29621. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  29622. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  29623. * for more info.
  29624. *
  29625. * The validator will set the `required` error key to true if the `required` attribute is set and
  29626. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  29627. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  29628. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  29629. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  29630. *
  29631. * @example
  29632. * <example name="ngRequiredDirective" module="ngRequiredExample">
  29633. * <file name="index.html">
  29634. * <script>
  29635. * angular.module('ngRequiredExample', [])
  29636. * .controller('ExampleController', ['$scope', function($scope) {
  29637. * $scope.required = true;
  29638. * }]);
  29639. * </script>
  29640. * <div ng-controller="ExampleController">
  29641. * <form name="form">
  29642. * <label for="required">Toggle required: </label>
  29643. * <input type="checkbox" ng-model="required" id="required" />
  29644. * <br>
  29645. * <label for="input">This input must be filled if `required` is true: </label>
  29646. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  29647. * <hr>
  29648. * required error set? = <code>{{form.input.$error.required}}</code><br>
  29649. * model = <code>{{model}}</code>
  29650. * </form>
  29651. * </div>
  29652. * </file>
  29653. * <file name="protractor.js" type="protractor">
  29654. var required = element(by.binding('form.input.$error.required'));
  29655. var model = element(by.binding('model'));
  29656. var input = element(by.id('input'));
  29657. it('should set the required error', function() {
  29658. expect(required.getText()).toContain('true');
  29659. input.sendKeys('123');
  29660. expect(required.getText()).not.toContain('true');
  29661. expect(model.getText()).toContain('123');
  29662. });
  29663. * </file>
  29664. * </example>
  29665. */
  29666. var requiredDirective = function() {
  29667. return {
  29668. restrict: 'A',
  29669. require: '?ngModel',
  29670. link: function(scope, elm, attr, ctrl) {
  29671. if (!ctrl) return;
  29672. attr.required = true; // force truthy in case we are on non input element
  29673. ctrl.$validators.required = function(modelValue, viewValue) {
  29674. return !attr.required || !ctrl.$isEmpty(viewValue);
  29675. };
  29676. attr.$observe('required', function() {
  29677. ctrl.$validate();
  29678. });
  29679. }
  29680. };
  29681. };
  29682. /**
  29683. * @ngdoc directive
  29684. * @name ngPattern
  29685. *
  29686. * @description
  29687. *
  29688. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29689. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29690. *
  29691. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29692. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  29693. * `ngPattern` attribute value:
  29694. * * If the expression evaluates to a RegExp object, then this is used directly.
  29695. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  29696. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  29697. *
  29698. * <div class="alert alert-info">
  29699. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  29700. * start at the index of the last search's match, thus not taking the whole input value into
  29701. * account.
  29702. * </div>
  29703. *
  29704. * <div class="alert alert-info">
  29705. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  29706. * differences:
  29707. * <ol>
  29708. * <li>
  29709. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  29710. * not available.
  29711. * </li>
  29712. * <li>
  29713. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  29714. * interpolated.
  29715. * </li>
  29716. * </ol>
  29717. * </div>
  29718. *
  29719. * @example
  29720. * <example name="ngPatternDirective" module="ngPatternExample">
  29721. * <file name="index.html">
  29722. * <script>
  29723. * angular.module('ngPatternExample', [])
  29724. * .controller('ExampleController', ['$scope', function($scope) {
  29725. * $scope.regex = '\\d+';
  29726. * }]);
  29727. * </script>
  29728. * <div ng-controller="ExampleController">
  29729. * <form name="form">
  29730. * <label for="regex">Set a pattern (regex string): </label>
  29731. * <input type="text" ng-model="regex" id="regex" />
  29732. * <br>
  29733. * <label for="input">This input is restricted by the current pattern: </label>
  29734. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  29735. * <hr>
  29736. * input valid? = <code>{{form.input.$valid}}</code><br>
  29737. * model = <code>{{model}}</code>
  29738. * </form>
  29739. * </div>
  29740. * </file>
  29741. * <file name="protractor.js" type="protractor">
  29742. var model = element(by.binding('model'));
  29743. var input = element(by.id('input'));
  29744. it('should validate the input with the default pattern', function() {
  29745. input.sendKeys('aaa');
  29746. expect(model.getText()).not.toContain('aaa');
  29747. input.clear().then(function() {
  29748. input.sendKeys('123');
  29749. expect(model.getText()).toContain('123');
  29750. });
  29751. });
  29752. * </file>
  29753. * </example>
  29754. */
  29755. var patternDirective = function() {
  29756. return {
  29757. restrict: 'A',
  29758. require: '?ngModel',
  29759. link: function(scope, elm, attr, ctrl) {
  29760. if (!ctrl) return;
  29761. var regexp, patternExp = attr.ngPattern || attr.pattern;
  29762. attr.$observe('pattern', function(regex) {
  29763. if (isString(regex) && regex.length > 0) {
  29764. regex = new RegExp('^' + regex + '$');
  29765. }
  29766. if (regex && !regex.test) {
  29767. throw minErr('ngPattern')('noregexp',
  29768. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  29769. regex, startingTag(elm));
  29770. }
  29771. regexp = regex || undefined;
  29772. ctrl.$validate();
  29773. });
  29774. ctrl.$validators.pattern = function(modelValue, viewValue) {
  29775. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  29776. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  29777. };
  29778. }
  29779. };
  29780. };
  29781. /**
  29782. * @ngdoc directive
  29783. * @name ngMaxlength
  29784. *
  29785. * @description
  29786. *
  29787. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29788. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29789. *
  29790. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29791. * is longer than the integer obtained by evaluating the Angular expression given in the
  29792. * `ngMaxlength` attribute value.
  29793. *
  29794. * <div class="alert alert-info">
  29795. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  29796. * differences:
  29797. * <ol>
  29798. * <li>
  29799. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  29800. * validation is not available.
  29801. * </li>
  29802. * <li>
  29803. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  29804. * interpolated.
  29805. * </li>
  29806. * </ol>
  29807. * </div>
  29808. *
  29809. * @example
  29810. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  29811. * <file name="index.html">
  29812. * <script>
  29813. * angular.module('ngMaxlengthExample', [])
  29814. * .controller('ExampleController', ['$scope', function($scope) {
  29815. * $scope.maxlength = 5;
  29816. * }]);
  29817. * </script>
  29818. * <div ng-controller="ExampleController">
  29819. * <form name="form">
  29820. * <label for="maxlength">Set a maxlength: </label>
  29821. * <input type="number" ng-model="maxlength" id="maxlength" />
  29822. * <br>
  29823. * <label for="input">This input is restricted by the current maxlength: </label>
  29824. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  29825. * <hr>
  29826. * input valid? = <code>{{form.input.$valid}}</code><br>
  29827. * model = <code>{{model}}</code>
  29828. * </form>
  29829. * </div>
  29830. * </file>
  29831. * <file name="protractor.js" type="protractor">
  29832. var model = element(by.binding('model'));
  29833. var input = element(by.id('input'));
  29834. it('should validate the input with the default maxlength', function() {
  29835. input.sendKeys('abcdef');
  29836. expect(model.getText()).not.toContain('abcdef');
  29837. input.clear().then(function() {
  29838. input.sendKeys('abcde');
  29839. expect(model.getText()).toContain('abcde');
  29840. });
  29841. });
  29842. * </file>
  29843. * </example>
  29844. */
  29845. var maxlengthDirective = function() {
  29846. return {
  29847. restrict: 'A',
  29848. require: '?ngModel',
  29849. link: function(scope, elm, attr, ctrl) {
  29850. if (!ctrl) return;
  29851. var maxlength = -1;
  29852. attr.$observe('maxlength', function(value) {
  29853. var intVal = toInt(value);
  29854. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  29855. ctrl.$validate();
  29856. });
  29857. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  29858. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  29859. };
  29860. }
  29861. };
  29862. };
  29863. /**
  29864. * @ngdoc directive
  29865. * @name ngMinlength
  29866. *
  29867. * @description
  29868. *
  29869. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29870. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29871. *
  29872. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29873. * is shorter than the integer obtained by evaluating the Angular expression given in the
  29874. * `ngMinlength` attribute value.
  29875. *
  29876. * <div class="alert alert-info">
  29877. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  29878. * differences:
  29879. * <ol>
  29880. * <li>
  29881. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  29882. * validation is not available.
  29883. * </li>
  29884. * <li>
  29885. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  29886. * interpolated.
  29887. * </li>
  29888. * </ol>
  29889. * </div>
  29890. *
  29891. * @example
  29892. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  29893. * <file name="index.html">
  29894. * <script>
  29895. * angular.module('ngMinlengthExample', [])
  29896. * .controller('ExampleController', ['$scope', function($scope) {
  29897. * $scope.minlength = 3;
  29898. * }]);
  29899. * </script>
  29900. * <div ng-controller="ExampleController">
  29901. * <form name="form">
  29902. * <label for="minlength">Set a minlength: </label>
  29903. * <input type="number" ng-model="minlength" id="minlength" />
  29904. * <br>
  29905. * <label for="input">This input is restricted by the current minlength: </label>
  29906. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  29907. * <hr>
  29908. * input valid? = <code>{{form.input.$valid}}</code><br>
  29909. * model = <code>{{model}}</code>
  29910. * </form>
  29911. * </div>
  29912. * </file>
  29913. * <file name="protractor.js" type="protractor">
  29914. var model = element(by.binding('model'));
  29915. var input = element(by.id('input'));
  29916. it('should validate the input with the default minlength', function() {
  29917. input.sendKeys('ab');
  29918. expect(model.getText()).not.toContain('ab');
  29919. input.sendKeys('abc');
  29920. expect(model.getText()).toContain('abc');
  29921. });
  29922. * </file>
  29923. * </example>
  29924. */
  29925. var minlengthDirective = function() {
  29926. return {
  29927. restrict: 'A',
  29928. require: '?ngModel',
  29929. link: function(scope, elm, attr, ctrl) {
  29930. if (!ctrl) return;
  29931. var minlength = 0;
  29932. attr.$observe('minlength', function(value) {
  29933. minlength = toInt(value) || 0;
  29934. ctrl.$validate();
  29935. });
  29936. ctrl.$validators.minlength = function(modelValue, viewValue) {
  29937. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  29938. };
  29939. }
  29940. };
  29941. };
  29942. if (window.angular.bootstrap) {
  29943. // AngularJS is already loaded, so we can return here...
  29944. if (window.console) {
  29945. console.log('WARNING: Tried to load angular more than once.');
  29946. }
  29947. return;
  29948. }
  29949. // try to bind to jquery now so that one can write jqLite(fn)
  29950. // but we will rebind on bootstrap again.
  29951. bindJQuery();
  29952. publishExternalAPI(angular);
  29953. angular.module("ngLocale", [], ["$provide", function($provide) {
  29954. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  29955. function getDecimals(n) {
  29956. n = n + '';
  29957. var i = n.indexOf('.');
  29958. return (i == -1) ? 0 : n.length - i - 1;
  29959. }
  29960. function getVF(n, opt_precision) {
  29961. var v = opt_precision;
  29962. if (undefined === v) {
  29963. v = Math.min(getDecimals(n), 3);
  29964. }
  29965. var base = Math.pow(10, v);
  29966. var f = ((n * base) | 0) % base;
  29967. return {v: v, f: f};
  29968. }
  29969. $provide.value("$locale", {
  29970. "DATETIME_FORMATS": {
  29971. "AMPMS": [
  29972. "AM",
  29973. "PM"
  29974. ],
  29975. "DAY": [
  29976. "Sunday",
  29977. "Monday",
  29978. "Tuesday",
  29979. "Wednesday",
  29980. "Thursday",
  29981. "Friday",
  29982. "Saturday"
  29983. ],
  29984. "ERANAMES": [
  29985. "Before Christ",
  29986. "Anno Domini"
  29987. ],
  29988. "ERAS": [
  29989. "BC",
  29990. "AD"
  29991. ],
  29992. "FIRSTDAYOFWEEK": 6,
  29993. "MONTH": [
  29994. "January",
  29995. "February",
  29996. "March",
  29997. "April",
  29998. "May",
  29999. "June",
  30000. "July",
  30001. "August",
  30002. "September",
  30003. "October",
  30004. "November",
  30005. "December"
  30006. ],
  30007. "SHORTDAY": [
  30008. "Sun",
  30009. "Mon",
  30010. "Tue",
  30011. "Wed",
  30012. "Thu",
  30013. "Fri",
  30014. "Sat"
  30015. ],
  30016. "SHORTMONTH": [
  30017. "Jan",
  30018. "Feb",
  30019. "Mar",
  30020. "Apr",
  30021. "May",
  30022. "Jun",
  30023. "Jul",
  30024. "Aug",
  30025. "Sep",
  30026. "Oct",
  30027. "Nov",
  30028. "Dec"
  30029. ],
  30030. "STANDALONEMONTH": [
  30031. "January",
  30032. "February",
  30033. "March",
  30034. "April",
  30035. "May",
  30036. "June",
  30037. "July",
  30038. "August",
  30039. "September",
  30040. "October",
  30041. "November",
  30042. "December"
  30043. ],
  30044. "WEEKENDRANGE": [
  30045. 5,
  30046. 6
  30047. ],
  30048. "fullDate": "EEEE, MMMM d, y",
  30049. "longDate": "MMMM d, y",
  30050. "medium": "MMM d, y h:mm:ss a",
  30051. "mediumDate": "MMM d, y",
  30052. "mediumTime": "h:mm:ss a",
  30053. "short": "M/d/yy h:mm a",
  30054. "shortDate": "M/d/yy",
  30055. "shortTime": "h:mm a"
  30056. },
  30057. "NUMBER_FORMATS": {
  30058. "CURRENCY_SYM": "$",
  30059. "DECIMAL_SEP": ".",
  30060. "GROUP_SEP": ",",
  30061. "PATTERNS": [
  30062. {
  30063. "gSize": 3,
  30064. "lgSize": 3,
  30065. "maxFrac": 3,
  30066. "minFrac": 0,
  30067. "minInt": 1,
  30068. "negPre": "-",
  30069. "negSuf": "",
  30070. "posPre": "",
  30071. "posSuf": ""
  30072. },
  30073. {
  30074. "gSize": 3,
  30075. "lgSize": 3,
  30076. "maxFrac": 2,
  30077. "minFrac": 2,
  30078. "minInt": 1,
  30079. "negPre": "-\u00a4",
  30080. "negSuf": "",
  30081. "posPre": "\u00a4",
  30082. "posSuf": ""
  30083. }
  30084. ]
  30085. },
  30086. "id": "en-us",
  30087. "localeID": "en_US",
  30088. "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
  30089. });
  30090. }]);
  30091. jqLite(function() {
  30092. angularInit(window.document, bootstrap);
  30093. });
  30094. })(window);
  30095. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');