angular.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600
  1. /**
  2. * @license AngularJS v1.8.2
  3. * (c) 2010-2020 Google LLC. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /* exported
  8. minErrConfig,
  9. errorHandlingConfig,
  10. isValidObjectMaxDepth
  11. */
  12. var minErrConfig = {
  13. objectMaxDepth: 5,
  14. urlErrorParamsEnabled: true
  15. };
  16. /**
  17. * @ngdoc function
  18. * @name angular.errorHandlingConfig
  19. * @module ng
  20. * @kind function
  21. *
  22. * @description
  23. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  24. * current configuration if used as a getter. The following options are supported:
  25. *
  26. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  27. *
  28. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  29. *
  30. * @param {Object=} config - The configuration object. May only contain the options that need to be
  31. * updated. Supported keys:
  32. *
  33. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  34. * non-positive or non-numeric value, removes the max depth limit.
  35. * Default: 5
  36. *
  37. * * `urlErrorParamsEnabled` **{Boolean}** - Specifies whether the generated error url will
  38. * contain the parameters of the thrown error. Disabling the parameters can be useful if the
  39. * generated error url is very long.
  40. *
  41. * Default: true. When used without argument, it returns the current value.
  42. */
  43. function errorHandlingConfig(config) {
  44. if (isObject(config)) {
  45. if (isDefined(config.objectMaxDepth)) {
  46. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  47. }
  48. if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) {
  49. minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled;
  50. }
  51. } else {
  52. return minErrConfig;
  53. }
  54. }
  55. /**
  56. * @private
  57. * @param {Number} maxDepth
  58. * @return {boolean}
  59. */
  60. function isValidObjectMaxDepth(maxDepth) {
  61. return isNumber(maxDepth) && maxDepth > 0;
  62. }
  63. /**
  64. * @description
  65. *
  66. * This object provides a utility for producing rich Error messages within
  67. * AngularJS. It can be called as follows:
  68. *
  69. * var exampleMinErr = minErr('example');
  70. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  71. *
  72. * The above creates an instance of minErr in the example namespace. The
  73. * resulting error will have a namespaced error code of example.one. The
  74. * resulting error will replace {0} with the value of foo, and {1} with the
  75. * value of bar. The object is not restricted in the number of arguments it can
  76. * take.
  77. *
  78. * If fewer arguments are specified than necessary for interpolation, the extra
  79. * interpolation markers will be preserved in the final string.
  80. *
  81. * Since data will be parsed statically during a build step, some restrictions
  82. * are applied with respect to how minErr instances are created and called.
  83. * Instances should have names of the form namespaceMinErr for a minErr created
  84. * using minErr('namespace'). Error codes, namespaces and template strings
  85. * should all be static strings, not variables or general expressions.
  86. *
  87. * @param {string} module The namespace to use for the new minErr instance.
  88. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  89. * error from returned function, for cases when a particular type of error is useful.
  90. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  91. */
  92. function minErr(module, ErrorConstructor) {
  93. ErrorConstructor = ErrorConstructor || Error;
  94. var url = 'https://errors.angularjs.org/1.8.2/';
  95. var regex = url.replace('.', '\\.') + '[\\s\\S]*';
  96. var errRegExp = new RegExp(regex, 'g');
  97. return function() {
  98. var code = arguments[0],
  99. template = arguments[1],
  100. message = '[' + (module ? module + ':' : '') + code + '] ',
  101. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  102. return toDebugString(arg, minErrConfig.objectMaxDepth);
  103. }),
  104. paramPrefix, i;
  105. // A minErr message has two parts: the message itself and the url that contains the
  106. // encoded message.
  107. // The message's parameters can contain other error messages which also include error urls.
  108. // To prevent the messages from getting too long, we strip the error urls from the parameters.
  109. message += template.replace(/\{\d+\}/g, function(match) {
  110. var index = +match.slice(1, -1);
  111. if (index < templateArgs.length) {
  112. return templateArgs[index].replace(errRegExp, '');
  113. }
  114. return match;
  115. });
  116. message += '\n' + url + (module ? module + '/' : '') + code;
  117. if (minErrConfig.urlErrorParamsEnabled) {
  118. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  119. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  120. }
  121. }
  122. return new ErrorConstructor(message);
  123. };
  124. }
  125. /* We need to tell ESLint what variables are being exported */
  126. /* exported
  127. angular,
  128. msie,
  129. jqLite,
  130. jQuery,
  131. slice,
  132. splice,
  133. push,
  134. toString,
  135. minErrConfig,
  136. errorHandlingConfig,
  137. isValidObjectMaxDepth,
  138. ngMinErr,
  139. angularModule,
  140. uid,
  141. REGEX_STRING_REGEXP,
  142. VALIDITY_STATE_PROPERTY,
  143. lowercase,
  144. uppercase,
  145. nodeName_,
  146. isArrayLike,
  147. forEach,
  148. forEachSorted,
  149. reverseParams,
  150. nextUid,
  151. setHashKey,
  152. extend,
  153. toInt,
  154. inherit,
  155. merge,
  156. noop,
  157. identity,
  158. valueFn,
  159. isUndefined,
  160. isDefined,
  161. isObject,
  162. isBlankObject,
  163. isString,
  164. isNumber,
  165. isNumberNaN,
  166. isDate,
  167. isError,
  168. isArray,
  169. isFunction,
  170. isRegExp,
  171. isWindow,
  172. isScope,
  173. isFile,
  174. isFormData,
  175. isBlob,
  176. isBoolean,
  177. isPromiseLike,
  178. trim,
  179. escapeForRegexp,
  180. isElement,
  181. makeMap,
  182. includes,
  183. arrayRemove,
  184. copy,
  185. simpleCompare,
  186. equals,
  187. csp,
  188. jq,
  189. concat,
  190. sliceArgs,
  191. bind,
  192. toJsonReplacer,
  193. toJson,
  194. fromJson,
  195. convertTimezoneToLocal,
  196. timezoneToOffset,
  197. addDateMinutes,
  198. startingTag,
  199. tryDecodeURIComponent,
  200. parseKeyValue,
  201. toKeyValue,
  202. encodeUriSegment,
  203. encodeUriQuery,
  204. angularInit,
  205. bootstrap,
  206. getTestability,
  207. snake_case,
  208. bindJQuery,
  209. assertArg,
  210. assertArgFn,
  211. assertNotHasOwnProperty,
  212. getter,
  213. getBlockNodes,
  214. hasOwnProperty,
  215. createMap,
  216. stringify,
  217. UNSAFE_restoreLegacyJqLiteXHTMLReplacement,
  218. NODE_TYPE_ELEMENT,
  219. NODE_TYPE_ATTRIBUTE,
  220. NODE_TYPE_TEXT,
  221. NODE_TYPE_COMMENT,
  222. NODE_TYPE_DOCUMENT,
  223. NODE_TYPE_DOCUMENT_FRAGMENT
  224. */
  225. ////////////////////////////////////
  226. /**
  227. * @ngdoc module
  228. * @name ng
  229. * @module ng
  230. * @installation
  231. * @description
  232. *
  233. * The ng module is loaded by default when an AngularJS application is started. The module itself
  234. * contains the essential components for an AngularJS application to function. The table below
  235. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  236. * components available within this core module.
  237. *
  238. */
  239. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  240. // The name of a form control's ValidityState property.
  241. // This is used so that it's possible for internal tests to create mock ValidityStates.
  242. var VALIDITY_STATE_PROPERTY = 'validity';
  243. var hasOwnProperty = Object.prototype.hasOwnProperty;
  244. /**
  245. * @private
  246. *
  247. * @description Converts the specified string to lowercase.
  248. * @param {string} string String to be converted to lowercase.
  249. * @returns {string} Lowercased string.
  250. */
  251. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  252. /**
  253. * @private
  254. *
  255. * @description Converts the specified string to uppercase.
  256. * @param {string} string String to be converted to uppercase.
  257. * @returns {string} Uppercased string.
  258. */
  259. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  260. var
  261. msie, // holds major version number for IE, or NaN if UA is not IE.
  262. jqLite, // delay binding since jQuery could be loaded after us.
  263. jQuery, // delay binding
  264. slice = [].slice,
  265. splice = [].splice,
  266. push = [].push,
  267. toString = Object.prototype.toString,
  268. getPrototypeOf = Object.getPrototypeOf,
  269. ngMinErr = minErr('ng'),
  270. /** @name angular */
  271. angular = window.angular || (window.angular = {}),
  272. angularModule,
  273. uid = 0;
  274. // Support: IE 9-11 only
  275. /**
  276. * documentMode is an IE-only property
  277. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  278. */
  279. msie = window.document.documentMode;
  280. /**
  281. * @private
  282. * @param {*} obj
  283. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  284. * String ...)
  285. */
  286. function isArrayLike(obj) {
  287. // `null`, `undefined` and `window` are not array-like
  288. if (obj == null || isWindow(obj)) return false;
  289. // arrays, strings and jQuery/jqLite objects are array like
  290. // * jqLite is either the jQuery or jqLite constructor function
  291. // * we have to check the existence of jqLite first as this method is called
  292. // via the forEach method when constructing the jqLite object in the first place
  293. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  294. // Support: iOS 8.2 (not reproducible in simulator)
  295. // "length" in obj used to prevent JIT error (gh-11508)
  296. var length = 'length' in Object(obj) && obj.length;
  297. // NodeList objects (with `item` method) and
  298. // other objects with suitable length characteristics are array-like
  299. return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function');
  300. }
  301. /**
  302. * @ngdoc function
  303. * @name angular.forEach
  304. * @module ng
  305. * @kind function
  306. *
  307. * @description
  308. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  309. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  310. * is the value of an object property or an array element, `key` is the object property key or
  311. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  312. *
  313. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  314. * using the `hasOwnProperty` method.
  315. *
  316. * Unlike ES262's
  317. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  318. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  319. * return the value provided.
  320. *
  321. ```js
  322. var values = {name: 'misko', gender: 'male'};
  323. var log = [];
  324. angular.forEach(values, function(value, key) {
  325. this.push(key + ': ' + value);
  326. }, log);
  327. expect(log).toEqual(['name: misko', 'gender: male']);
  328. ```
  329. *
  330. * @param {Object|Array} obj Object to iterate over.
  331. * @param {Function} iterator Iterator function.
  332. * @param {Object=} context Object to become context (`this`) for the iterator function.
  333. * @returns {Object|Array} Reference to `obj`.
  334. */
  335. function forEach(obj, iterator, context) {
  336. var key, length;
  337. if (obj) {
  338. if (isFunction(obj)) {
  339. for (key in obj) {
  340. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  341. iterator.call(context, obj[key], key, obj);
  342. }
  343. }
  344. } else if (isArray(obj) || isArrayLike(obj)) {
  345. var isPrimitive = typeof obj !== 'object';
  346. for (key = 0, length = obj.length; key < length; key++) {
  347. if (isPrimitive || key in obj) {
  348. iterator.call(context, obj[key], key, obj);
  349. }
  350. }
  351. } else if (obj.forEach && obj.forEach !== forEach) {
  352. obj.forEach(iterator, context, obj);
  353. } else if (isBlankObject(obj)) {
  354. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  355. for (key in obj) {
  356. iterator.call(context, obj[key], key, obj);
  357. }
  358. } else if (typeof obj.hasOwnProperty === 'function') {
  359. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  360. for (key in obj) {
  361. if (obj.hasOwnProperty(key)) {
  362. iterator.call(context, obj[key], key, obj);
  363. }
  364. }
  365. } else {
  366. // Slow path for objects which do not have a method `hasOwnProperty`
  367. for (key in obj) {
  368. if (hasOwnProperty.call(obj, key)) {
  369. iterator.call(context, obj[key], key, obj);
  370. }
  371. }
  372. }
  373. }
  374. return obj;
  375. }
  376. function forEachSorted(obj, iterator, context) {
  377. var keys = Object.keys(obj).sort();
  378. for (var i = 0; i < keys.length; i++) {
  379. iterator.call(context, obj[keys[i]], keys[i]);
  380. }
  381. return keys;
  382. }
  383. /**
  384. * when using forEach the params are value, key, but it is often useful to have key, value.
  385. * @param {function(string, *)} iteratorFn
  386. * @returns {function(*, string)}
  387. */
  388. function reverseParams(iteratorFn) {
  389. return function(value, key) {iteratorFn(key, value);};
  390. }
  391. /**
  392. * A consistent way of creating unique IDs in angular.
  393. *
  394. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  395. * we hit number precision issues in JavaScript.
  396. *
  397. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  398. *
  399. * @returns {number} an unique alpha-numeric string
  400. */
  401. function nextUid() {
  402. return ++uid;
  403. }
  404. /**
  405. * Set or clear the hashkey for an object.
  406. * @param obj object
  407. * @param h the hashkey (!truthy to delete the hashkey)
  408. */
  409. function setHashKey(obj, h) {
  410. if (h) {
  411. obj.$$hashKey = h;
  412. } else {
  413. delete obj.$$hashKey;
  414. }
  415. }
  416. function baseExtend(dst, objs, deep) {
  417. var h = dst.$$hashKey;
  418. for (var i = 0, ii = objs.length; i < ii; ++i) {
  419. var obj = objs[i];
  420. if (!isObject(obj) && !isFunction(obj)) continue;
  421. var keys = Object.keys(obj);
  422. for (var j = 0, jj = keys.length; j < jj; j++) {
  423. var key = keys[j];
  424. var src = obj[key];
  425. if (deep && isObject(src)) {
  426. if (isDate(src)) {
  427. dst[key] = new Date(src.valueOf());
  428. } else if (isRegExp(src)) {
  429. dst[key] = new RegExp(src);
  430. } else if (src.nodeName) {
  431. dst[key] = src.cloneNode(true);
  432. } else if (isElement(src)) {
  433. dst[key] = src.clone();
  434. } else {
  435. if (key !== '__proto__') {
  436. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  437. baseExtend(dst[key], [src], true);
  438. }
  439. }
  440. } else {
  441. dst[key] = src;
  442. }
  443. }
  444. }
  445. setHashKey(dst, h);
  446. return dst;
  447. }
  448. /**
  449. * @ngdoc function
  450. * @name angular.extend
  451. * @module ng
  452. * @kind function
  453. *
  454. * @description
  455. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  456. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  457. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  458. *
  459. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  460. * {@link angular.merge} for this.
  461. *
  462. * @param {Object} dst Destination object.
  463. * @param {...Object} src Source object(s).
  464. * @returns {Object} Reference to `dst`.
  465. */
  466. function extend(dst) {
  467. return baseExtend(dst, slice.call(arguments, 1), false);
  468. }
  469. /**
  470. * @ngdoc function
  471. * @name angular.merge
  472. * @module ng
  473. * @kind function
  474. *
  475. * @description
  476. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  477. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  478. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  479. *
  480. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  481. * objects, performing a deep copy.
  482. *
  483. * @deprecated
  484. * sinceVersion="1.6.5"
  485. * This function is deprecated, but will not be removed in the 1.x lifecycle.
  486. * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
  487. * supported by this function. We suggest using another, similar library for all-purpose merging,
  488. * such as [lodash's merge()](https://lodash.com/docs/4.17.4#merge).
  489. *
  490. * @knownIssue
  491. * This is a list of (known) object types that are not handled correctly by this function:
  492. * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
  493. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  494. * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
  495. * - AngularJS {@link $rootScope.Scope scopes};
  496. *
  497. * `angular.merge` also does not support merging objects with circular references.
  498. *
  499. * @param {Object} dst Destination object.
  500. * @param {...Object} src Source object(s).
  501. * @returns {Object} Reference to `dst`.
  502. */
  503. function merge(dst) {
  504. return baseExtend(dst, slice.call(arguments, 1), true);
  505. }
  506. function toInt(str) {
  507. return parseInt(str, 10);
  508. }
  509. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  510. // eslint-disable-next-line no-self-compare
  511. return num !== num;
  512. };
  513. function inherit(parent, extra) {
  514. return extend(Object.create(parent), extra);
  515. }
  516. /**
  517. * @ngdoc function
  518. * @name angular.noop
  519. * @module ng
  520. * @kind function
  521. *
  522. * @description
  523. * A function that performs no operations. This function can be useful when writing code in the
  524. * functional style.
  525. ```js
  526. function foo(callback) {
  527. var result = calculateResult();
  528. (callback || angular.noop)(result);
  529. }
  530. ```
  531. */
  532. function noop() {}
  533. noop.$inject = [];
  534. /**
  535. * @ngdoc function
  536. * @name angular.identity
  537. * @module ng
  538. * @kind function
  539. *
  540. * @description
  541. * A function that returns its first argument. This function is useful when writing code in the
  542. * functional style.
  543. *
  544. ```js
  545. function transformer(transformationFn, value) {
  546. return (transformationFn || angular.identity)(value);
  547. };
  548. // E.g.
  549. function getResult(fn, input) {
  550. return (fn || angular.identity)(input);
  551. };
  552. getResult(function(n) { return n * 2; }, 21); // returns 42
  553. getResult(null, 21); // returns 21
  554. getResult(undefined, 21); // returns 21
  555. ```
  556. *
  557. * @param {*} value to be returned.
  558. * @returns {*} the value passed in.
  559. */
  560. function identity($) {return $;}
  561. identity.$inject = [];
  562. function valueFn(value) {return function valueRef() {return value;};}
  563. function hasCustomToString(obj) {
  564. return isFunction(obj.toString) && obj.toString !== toString;
  565. }
  566. /**
  567. * @ngdoc function
  568. * @name angular.isUndefined
  569. * @module ng
  570. * @kind function
  571. *
  572. * @description
  573. * Determines if a reference is undefined.
  574. *
  575. * @param {*} value Reference to check.
  576. * @returns {boolean} True if `value` is undefined.
  577. */
  578. function isUndefined(value) {return typeof value === 'undefined';}
  579. /**
  580. * @ngdoc function
  581. * @name angular.isDefined
  582. * @module ng
  583. * @kind function
  584. *
  585. * @description
  586. * Determines if a reference is defined.
  587. *
  588. * @param {*} value Reference to check.
  589. * @returns {boolean} True if `value` is defined.
  590. */
  591. function isDefined(value) {return typeof value !== 'undefined';}
  592. /**
  593. * @ngdoc function
  594. * @name angular.isObject
  595. * @module ng
  596. * @kind function
  597. *
  598. * @description
  599. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  600. * considered to be objects. Note that JavaScript arrays are objects.
  601. *
  602. * @param {*} value Reference to check.
  603. * @returns {boolean} True if `value` is an `Object` but not `null`.
  604. */
  605. function isObject(value) {
  606. // http://jsperf.com/isobject4
  607. return value !== null && typeof value === 'object';
  608. }
  609. /**
  610. * Determine if a value is an object with a null prototype
  611. *
  612. * @returns {boolean} True if `value` is an `Object` with a null prototype
  613. */
  614. function isBlankObject(value) {
  615. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  616. }
  617. /**
  618. * @ngdoc function
  619. * @name angular.isString
  620. * @module ng
  621. * @kind function
  622. *
  623. * @description
  624. * Determines if a reference is a `String`.
  625. *
  626. * @param {*} value Reference to check.
  627. * @returns {boolean} True if `value` is a `String`.
  628. */
  629. function isString(value) {return typeof value === 'string';}
  630. /**
  631. * @ngdoc function
  632. * @name angular.isNumber
  633. * @module ng
  634. * @kind function
  635. *
  636. * @description
  637. * Determines if a reference is a `Number`.
  638. *
  639. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  640. *
  641. * If you wish to exclude these then you can use the native
  642. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  643. * method.
  644. *
  645. * @param {*} value Reference to check.
  646. * @returns {boolean} True if `value` is a `Number`.
  647. */
  648. function isNumber(value) {return typeof value === 'number';}
  649. /**
  650. * @ngdoc function
  651. * @name angular.isDate
  652. * @module ng
  653. * @kind function
  654. *
  655. * @description
  656. * Determines if a value is a date.
  657. *
  658. * @param {*} value Reference to check.
  659. * @returns {boolean} True if `value` is a `Date`.
  660. */
  661. function isDate(value) {
  662. return toString.call(value) === '[object Date]';
  663. }
  664. /**
  665. * @ngdoc function
  666. * @name angular.isArray
  667. * @module ng
  668. * @kind function
  669. *
  670. * @description
  671. * Determines if a reference is an `Array`.
  672. *
  673. * @param {*} value Reference to check.
  674. * @returns {boolean} True if `value` is an `Array`.
  675. */
  676. function isArray(arr) {
  677. return Array.isArray(arr) || arr instanceof Array;
  678. }
  679. /**
  680. * @description
  681. * Determines if a reference is an `Error`.
  682. * Loosely based on https://www.npmjs.com/package/iserror
  683. *
  684. * @param {*} value Reference to check.
  685. * @returns {boolean} True if `value` is an `Error`.
  686. */
  687. function isError(value) {
  688. var tag = toString.call(value);
  689. switch (tag) {
  690. case '[object Error]': return true;
  691. case '[object Exception]': return true;
  692. case '[object DOMException]': return true;
  693. default: return value instanceof Error;
  694. }
  695. }
  696. /**
  697. * @ngdoc function
  698. * @name angular.isFunction
  699. * @module ng
  700. * @kind function
  701. *
  702. * @description
  703. * Determines if a reference is a `Function`.
  704. *
  705. * @param {*} value Reference to check.
  706. * @returns {boolean} True if `value` is a `Function`.
  707. */
  708. function isFunction(value) {return typeof value === 'function';}
  709. /**
  710. * Determines if a value is a regular expression object.
  711. *
  712. * @private
  713. * @param {*} value Reference to check.
  714. * @returns {boolean} True if `value` is a `RegExp`.
  715. */
  716. function isRegExp(value) {
  717. return toString.call(value) === '[object RegExp]';
  718. }
  719. /**
  720. * Checks if `obj` is a window object.
  721. *
  722. * @private
  723. * @param {*} obj Object to check
  724. * @returns {boolean} True if `obj` is a window obj.
  725. */
  726. function isWindow(obj) {
  727. return obj && obj.window === obj;
  728. }
  729. function isScope(obj) {
  730. return obj && obj.$evalAsync && obj.$watch;
  731. }
  732. function isFile(obj) {
  733. return toString.call(obj) === '[object File]';
  734. }
  735. function isFormData(obj) {
  736. return toString.call(obj) === '[object FormData]';
  737. }
  738. function isBlob(obj) {
  739. return toString.call(obj) === '[object Blob]';
  740. }
  741. function isBoolean(value) {
  742. return typeof value === 'boolean';
  743. }
  744. function isPromiseLike(obj) {
  745. return obj && isFunction(obj.then);
  746. }
  747. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  748. function isTypedArray(value) {
  749. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  750. }
  751. function isArrayBuffer(obj) {
  752. return toString.call(obj) === '[object ArrayBuffer]';
  753. }
  754. var trim = function(value) {
  755. return isString(value) ? value.trim() : value;
  756. };
  757. // Copied from:
  758. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  759. // Prereq: s is a string.
  760. var escapeForRegexp = function(s) {
  761. return s
  762. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  763. // eslint-disable-next-line no-control-regex
  764. .replace(/\x08/g, '\\x08');
  765. };
  766. /**
  767. * @ngdoc function
  768. * @name angular.isElement
  769. * @module ng
  770. * @kind function
  771. *
  772. * @description
  773. * Determines if a reference is a DOM element (or wrapped jQuery element).
  774. *
  775. * @param {*} value Reference to check.
  776. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  777. */
  778. function isElement(node) {
  779. return !!(node &&
  780. (node.nodeName // We are a direct element.
  781. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  782. }
  783. /**
  784. * @param str 'key1,key2,...'
  785. * @returns {object} in the form of {key1:true, key2:true, ...}
  786. */
  787. function makeMap(str) {
  788. var obj = {}, items = str.split(','), i;
  789. for (i = 0; i < items.length; i++) {
  790. obj[items[i]] = true;
  791. }
  792. return obj;
  793. }
  794. function nodeName_(element) {
  795. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  796. }
  797. function includes(array, obj) {
  798. return Array.prototype.indexOf.call(array, obj) !== -1;
  799. }
  800. function arrayRemove(array, value) {
  801. var index = array.indexOf(value);
  802. if (index >= 0) {
  803. array.splice(index, 1);
  804. }
  805. return index;
  806. }
  807. /**
  808. * @ngdoc function
  809. * @name angular.copy
  810. * @module ng
  811. * @kind function
  812. *
  813. * @description
  814. * Creates a deep copy of `source`, which should be an object or an array. This functions is used
  815. * internally, mostly in the change-detection code. It is not intended as an all-purpose copy
  816. * function, and has several limitations (see below).
  817. *
  818. * * If no destination is supplied, a copy of the object or array is created.
  819. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  820. * are deleted and then all elements/properties from the source are copied to it.
  821. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  822. * * If `source` is identical to `destination` an exception will be thrown.
  823. *
  824. * <br />
  825. *
  826. * <div class="alert alert-warning">
  827. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  828. * and on `destination`) will be ignored.
  829. * </div>
  830. *
  831. * <div class="alert alert-warning">
  832. * `angular.copy` does not check if destination and source are of the same type. It's the
  833. * developer's responsibility to make sure they are compatible.
  834. * </div>
  835. *
  836. * @knownIssue
  837. * This is a non-exhaustive list of object types / features that are not handled correctly by
  838. * `angular.copy`. Note that since this functions is used by the change detection code, this
  839. * means binding or watching objects of these types (or that include these types) might not work
  840. * correctly.
  841. * - [`File`](https://developer.mozilla.org/docs/Web/API/File)
  842. * - [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)
  843. * - [`ImageData`](https://developer.mozilla.org/docs/Web/API/ImageData)
  844. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  845. * - [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)
  846. * - [`WeakMap`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)
  847. * - [`getter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/
  848. * [`setter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)
  849. *
  850. * @param {*} source The source that will be used to make a copy. Can be any type, including
  851. * primitives, `null`, and `undefined`.
  852. * @param {(Object|Array)=} destination Destination into which the source is copied. If provided,
  853. * must be of the same type as `source`.
  854. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  855. *
  856. * @example
  857. <example module="copyExample" name="angular-copy">
  858. <file name="index.html">
  859. <div ng-controller="ExampleController">
  860. <form novalidate class="simple-form">
  861. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  862. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  863. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  864. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  865. <button ng-click="reset()">RESET</button>
  866. <button ng-click="update(user)">SAVE</button>
  867. </form>
  868. <pre>form = {{user | json}}</pre>
  869. <pre>leader = {{leader | json}}</pre>
  870. </div>
  871. </file>
  872. <file name="script.js">
  873. // Module: copyExample
  874. angular.
  875. module('copyExample', []).
  876. controller('ExampleController', ['$scope', function($scope) {
  877. $scope.leader = {};
  878. $scope.reset = function() {
  879. // Example with 1 argument
  880. $scope.user = angular.copy($scope.leader);
  881. };
  882. $scope.update = function(user) {
  883. // Example with 2 arguments
  884. angular.copy(user, $scope.leader);
  885. };
  886. $scope.reset();
  887. }]);
  888. </file>
  889. </example>
  890. */
  891. function copy(source, destination, maxDepth) {
  892. var stackSource = [];
  893. var stackDest = [];
  894. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  895. if (destination) {
  896. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  897. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  898. }
  899. if (source === destination) {
  900. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  901. }
  902. // Empty the destination object
  903. if (isArray(destination)) {
  904. destination.length = 0;
  905. } else {
  906. forEach(destination, function(value, key) {
  907. if (key !== '$$hashKey') {
  908. delete destination[key];
  909. }
  910. });
  911. }
  912. stackSource.push(source);
  913. stackDest.push(destination);
  914. return copyRecurse(source, destination, maxDepth);
  915. }
  916. return copyElement(source, maxDepth);
  917. function copyRecurse(source, destination, maxDepth) {
  918. maxDepth--;
  919. if (maxDepth < 0) {
  920. return '...';
  921. }
  922. var h = destination.$$hashKey;
  923. var key;
  924. if (isArray(source)) {
  925. for (var i = 0, ii = source.length; i < ii; i++) {
  926. destination.push(copyElement(source[i], maxDepth));
  927. }
  928. } else if (isBlankObject(source)) {
  929. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  930. for (key in source) {
  931. destination[key] = copyElement(source[key], maxDepth);
  932. }
  933. } else if (source && typeof source.hasOwnProperty === 'function') {
  934. // Slow path, which must rely on hasOwnProperty
  935. for (key in source) {
  936. if (source.hasOwnProperty(key)) {
  937. destination[key] = copyElement(source[key], maxDepth);
  938. }
  939. }
  940. } else {
  941. // Slowest path --- hasOwnProperty can't be called as a method
  942. for (key in source) {
  943. if (hasOwnProperty.call(source, key)) {
  944. destination[key] = copyElement(source[key], maxDepth);
  945. }
  946. }
  947. }
  948. setHashKey(destination, h);
  949. return destination;
  950. }
  951. function copyElement(source, maxDepth) {
  952. // Simple values
  953. if (!isObject(source)) {
  954. return source;
  955. }
  956. // Already copied values
  957. var index = stackSource.indexOf(source);
  958. if (index !== -1) {
  959. return stackDest[index];
  960. }
  961. if (isWindow(source) || isScope(source)) {
  962. throw ngMinErr('cpws',
  963. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  964. }
  965. var needsRecurse = false;
  966. var destination = copyType(source);
  967. if (destination === undefined) {
  968. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  969. needsRecurse = true;
  970. }
  971. stackSource.push(source);
  972. stackDest.push(destination);
  973. return needsRecurse
  974. ? copyRecurse(source, destination, maxDepth)
  975. : destination;
  976. }
  977. function copyType(source) {
  978. switch (toString.call(source)) {
  979. case '[object Int8Array]':
  980. case '[object Int16Array]':
  981. case '[object Int32Array]':
  982. case '[object Float32Array]':
  983. case '[object Float64Array]':
  984. case '[object Uint8Array]':
  985. case '[object Uint8ClampedArray]':
  986. case '[object Uint16Array]':
  987. case '[object Uint32Array]':
  988. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  989. case '[object ArrayBuffer]':
  990. // Support: IE10
  991. if (!source.slice) {
  992. // If we're in this case we know the environment supports ArrayBuffer
  993. /* eslint-disable no-undef */
  994. var copied = new ArrayBuffer(source.byteLength);
  995. new Uint8Array(copied).set(new Uint8Array(source));
  996. /* eslint-enable */
  997. return copied;
  998. }
  999. return source.slice(0);
  1000. case '[object Boolean]':
  1001. case '[object Number]':
  1002. case '[object String]':
  1003. case '[object Date]':
  1004. return new source.constructor(source.valueOf());
  1005. case '[object RegExp]':
  1006. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  1007. re.lastIndex = source.lastIndex;
  1008. return re;
  1009. case '[object Blob]':
  1010. return new source.constructor([source], {type: source.type});
  1011. }
  1012. if (isFunction(source.cloneNode)) {
  1013. return source.cloneNode(true);
  1014. }
  1015. }
  1016. }
  1017. // eslint-disable-next-line no-self-compare
  1018. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  1019. /**
  1020. * @ngdoc function
  1021. * @name angular.equals
  1022. * @module ng
  1023. * @kind function
  1024. *
  1025. * @description
  1026. * Determines if two objects or two values are equivalent. Supports value types, regular
  1027. * expressions, arrays and objects.
  1028. *
  1029. * Two objects or values are considered equivalent if at least one of the following is true:
  1030. *
  1031. * * Both objects or values pass `===` comparison.
  1032. * * Both objects or values are of the same type and all of their properties are equal by
  1033. * comparing them with `angular.equals`.
  1034. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  1035. * * Both values represent the same regular expression (In JavaScript,
  1036. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  1037. * representation matches).
  1038. *
  1039. * During a property comparison, properties of `function` type and properties with names
  1040. * that begin with `$` are ignored.
  1041. *
  1042. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1043. *
  1044. * @param {*} o1 Object or value to compare.
  1045. * @param {*} o2 Object or value to compare.
  1046. * @returns {boolean} True if arguments are equal.
  1047. *
  1048. * @example
  1049. <example module="equalsExample" name="equalsExample">
  1050. <file name="index.html">
  1051. <div ng-controller="ExampleController">
  1052. <form novalidate>
  1053. <h3>User 1</h3>
  1054. Name: <input type="text" ng-model="user1.name">
  1055. Age: <input type="number" ng-model="user1.age">
  1056. <h3>User 2</h3>
  1057. Name: <input type="text" ng-model="user2.name">
  1058. Age: <input type="number" ng-model="user2.age">
  1059. <div>
  1060. <br/>
  1061. <input type="button" value="Compare" ng-click="compare()">
  1062. </div>
  1063. User 1: <pre>{{user1 | json}}</pre>
  1064. User 2: <pre>{{user2 | json}}</pre>
  1065. Equal: <pre>{{result}}</pre>
  1066. </form>
  1067. </div>
  1068. </file>
  1069. <file name="script.js">
  1070. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1071. $scope.user1 = {};
  1072. $scope.user2 = {};
  1073. $scope.compare = function() {
  1074. $scope.result = angular.equals($scope.user1, $scope.user2);
  1075. };
  1076. }]);
  1077. </file>
  1078. </example>
  1079. */
  1080. function equals(o1, o2) {
  1081. if (o1 === o2) return true;
  1082. if (o1 === null || o2 === null) return false;
  1083. // eslint-disable-next-line no-self-compare
  1084. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1085. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1086. if (t1 === t2 && t1 === 'object') {
  1087. if (isArray(o1)) {
  1088. if (!isArray(o2)) return false;
  1089. if ((length = o1.length) === o2.length) {
  1090. for (key = 0; key < length; key++) {
  1091. if (!equals(o1[key], o2[key])) return false;
  1092. }
  1093. return true;
  1094. }
  1095. } else if (isDate(o1)) {
  1096. if (!isDate(o2)) return false;
  1097. return simpleCompare(o1.getTime(), o2.getTime());
  1098. } else if (isRegExp(o1)) {
  1099. if (!isRegExp(o2)) return false;
  1100. return o1.toString() === o2.toString();
  1101. } else {
  1102. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1103. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1104. keySet = createMap();
  1105. for (key in o1) {
  1106. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1107. if (!equals(o1[key], o2[key])) return false;
  1108. keySet[key] = true;
  1109. }
  1110. for (key in o2) {
  1111. if (!(key in keySet) &&
  1112. key.charAt(0) !== '$' &&
  1113. isDefined(o2[key]) &&
  1114. !isFunction(o2[key])) return false;
  1115. }
  1116. return true;
  1117. }
  1118. }
  1119. return false;
  1120. }
  1121. var csp = function() {
  1122. if (!isDefined(csp.rules)) {
  1123. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1124. window.document.querySelector('[data-ng-csp]'));
  1125. if (ngCspElement) {
  1126. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1127. ngCspElement.getAttribute('data-ng-csp');
  1128. csp.rules = {
  1129. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1130. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1131. };
  1132. } else {
  1133. csp.rules = {
  1134. noUnsafeEval: noUnsafeEval(),
  1135. noInlineStyle: false
  1136. };
  1137. }
  1138. }
  1139. return csp.rules;
  1140. function noUnsafeEval() {
  1141. try {
  1142. // eslint-disable-next-line no-new, no-new-func
  1143. new Function('');
  1144. return false;
  1145. } catch (e) {
  1146. return true;
  1147. }
  1148. }
  1149. };
  1150. /**
  1151. * @ngdoc directive
  1152. * @module ng
  1153. * @name ngJq
  1154. *
  1155. * @element ANY
  1156. * @param {string=} ngJq the name of the library available under `window`
  1157. * to be used for angular.element
  1158. * @description
  1159. * Use this directive to force the angular.element library. This should be
  1160. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1161. * the jquery variable under window (eg. jQuery).
  1162. *
  1163. * Since AngularJS looks for this directive when it is loaded (doesn't wait for the
  1164. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1165. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1166. * others ignored.
  1167. *
  1168. * @example
  1169. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1170. ```html
  1171. <!doctype html>
  1172. <html ng-app ng-jq>
  1173. ...
  1174. ...
  1175. </html>
  1176. ```
  1177. * @example
  1178. * This example shows how to use a jQuery based library of a different name.
  1179. * The library name must be available at the top most 'window'.
  1180. ```html
  1181. <!doctype html>
  1182. <html ng-app ng-jq="jQueryLib">
  1183. ...
  1184. ...
  1185. </html>
  1186. ```
  1187. */
  1188. var jq = function() {
  1189. if (isDefined(jq.name_)) return jq.name_;
  1190. var el;
  1191. var i, ii = ngAttrPrefixes.length, prefix, name;
  1192. for (i = 0; i < ii; ++i) {
  1193. prefix = ngAttrPrefixes[i];
  1194. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1195. if (el) {
  1196. name = el.getAttribute(prefix + 'jq');
  1197. break;
  1198. }
  1199. }
  1200. return (jq.name_ = name);
  1201. };
  1202. function concat(array1, array2, index) {
  1203. return array1.concat(slice.call(array2, index));
  1204. }
  1205. function sliceArgs(args, startIndex) {
  1206. return slice.call(args, startIndex || 0);
  1207. }
  1208. /**
  1209. * @ngdoc function
  1210. * @name angular.bind
  1211. * @module ng
  1212. * @kind function
  1213. *
  1214. * @description
  1215. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1216. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1217. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1218. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1219. *
  1220. * @param {Object} self Context which `fn` should be evaluated in.
  1221. * @param {function()} fn Function to be bound.
  1222. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1223. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1224. */
  1225. function bind(self, fn) {
  1226. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1227. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1228. return curryArgs.length
  1229. ? function() {
  1230. return arguments.length
  1231. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1232. : fn.apply(self, curryArgs);
  1233. }
  1234. : function() {
  1235. return arguments.length
  1236. ? fn.apply(self, arguments)
  1237. : fn.call(self);
  1238. };
  1239. } else {
  1240. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1241. return fn;
  1242. }
  1243. }
  1244. function toJsonReplacer(key, value) {
  1245. var val = value;
  1246. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1247. val = undefined;
  1248. } else if (isWindow(value)) {
  1249. val = '$WINDOW';
  1250. } else if (value && window.document === value) {
  1251. val = '$DOCUMENT';
  1252. } else if (isScope(value)) {
  1253. val = '$SCOPE';
  1254. }
  1255. return val;
  1256. }
  1257. /**
  1258. * @ngdoc function
  1259. * @name angular.toJson
  1260. * @module ng
  1261. * @kind function
  1262. *
  1263. * @description
  1264. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1265. * stripped since AngularJS uses this notation internally.
  1266. *
  1267. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1268. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1269. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1270. * @returns {string|undefined} JSON-ified string representing `obj`.
  1271. * @knownIssue
  1272. *
  1273. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1274. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1275. * `Date.prototype.toJSON` method as follows:
  1276. *
  1277. * ```
  1278. * var _DatetoJSON = Date.prototype.toJSON;
  1279. * Date.prototype.toJSON = function() {
  1280. * try {
  1281. * return _DatetoJSON.call(this);
  1282. * } catch(e) {
  1283. * if (e instanceof RangeError) {
  1284. * return null;
  1285. * }
  1286. * throw e;
  1287. * }
  1288. * };
  1289. * ```
  1290. *
  1291. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1292. */
  1293. function toJson(obj, pretty) {
  1294. if (isUndefined(obj)) return undefined;
  1295. if (!isNumber(pretty)) {
  1296. pretty = pretty ? 2 : null;
  1297. }
  1298. return JSON.stringify(obj, toJsonReplacer, pretty);
  1299. }
  1300. /**
  1301. * @ngdoc function
  1302. * @name angular.fromJson
  1303. * @module ng
  1304. * @kind function
  1305. *
  1306. * @description
  1307. * Deserializes a JSON string.
  1308. *
  1309. * @param {string} json JSON string to deserialize.
  1310. * @returns {Object|Array|string|number} Deserialized JSON string.
  1311. */
  1312. function fromJson(json) {
  1313. return isString(json)
  1314. ? JSON.parse(json)
  1315. : json;
  1316. }
  1317. var ALL_COLONS = /:/g;
  1318. function timezoneToOffset(timezone, fallback) {
  1319. // Support: IE 9-11 only, Edge 13-15+
  1320. // IE/Edge do not "understand" colon (`:`) in timezone
  1321. timezone = timezone.replace(ALL_COLONS, '');
  1322. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1323. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1324. }
  1325. function addDateMinutes(date, minutes) {
  1326. date = new Date(date.getTime());
  1327. date.setMinutes(date.getMinutes() + minutes);
  1328. return date;
  1329. }
  1330. function convertTimezoneToLocal(date, timezone, reverse) {
  1331. reverse = reverse ? -1 : 1;
  1332. var dateTimezoneOffset = date.getTimezoneOffset();
  1333. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1334. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1335. }
  1336. /**
  1337. * @returns {string} Returns the string representation of the element.
  1338. */
  1339. function startingTag(element) {
  1340. element = jqLite(element).clone().empty();
  1341. var elemHtml = jqLite('<div></div>').append(element).html();
  1342. try {
  1343. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1344. elemHtml.
  1345. match(/^(<[^>]+>)/)[1].
  1346. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1347. } catch (e) {
  1348. return lowercase(elemHtml);
  1349. }
  1350. }
  1351. /////////////////////////////////////////////////
  1352. /**
  1353. * Tries to decode the URI component without throwing an exception.
  1354. *
  1355. * @private
  1356. * @param str value potential URI component to check.
  1357. * @returns {boolean} True if `value` can be decoded
  1358. * with the decodeURIComponent function.
  1359. */
  1360. function tryDecodeURIComponent(value) {
  1361. try {
  1362. return decodeURIComponent(value);
  1363. } catch (e) {
  1364. // Ignore any invalid uri component.
  1365. }
  1366. }
  1367. /**
  1368. * Parses an escaped url query string into key-value pairs.
  1369. * @returns {Object.<string,boolean|Array>}
  1370. */
  1371. function parseKeyValue(/**string*/keyValue) {
  1372. var obj = {};
  1373. forEach((keyValue || '').split('&'), function(keyValue) {
  1374. var splitPoint, key, val;
  1375. if (keyValue) {
  1376. key = keyValue = keyValue.replace(/\+/g,'%20');
  1377. splitPoint = keyValue.indexOf('=');
  1378. if (splitPoint !== -1) {
  1379. key = keyValue.substring(0, splitPoint);
  1380. val = keyValue.substring(splitPoint + 1);
  1381. }
  1382. key = tryDecodeURIComponent(key);
  1383. if (isDefined(key)) {
  1384. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1385. if (!hasOwnProperty.call(obj, key)) {
  1386. obj[key] = val;
  1387. } else if (isArray(obj[key])) {
  1388. obj[key].push(val);
  1389. } else {
  1390. obj[key] = [obj[key],val];
  1391. }
  1392. }
  1393. }
  1394. });
  1395. return obj;
  1396. }
  1397. function toKeyValue(obj) {
  1398. var parts = [];
  1399. forEach(obj, function(value, key) {
  1400. if (isArray(value)) {
  1401. forEach(value, function(arrayValue) {
  1402. parts.push(encodeUriQuery(key, true) +
  1403. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1404. });
  1405. } else {
  1406. parts.push(encodeUriQuery(key, true) +
  1407. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1408. }
  1409. });
  1410. return parts.length ? parts.join('&') : '';
  1411. }
  1412. /**
  1413. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1414. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1415. * segments:
  1416. * segment = *pchar
  1417. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1418. * pct-encoded = "%" HEXDIG HEXDIG
  1419. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1420. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1421. * / "*" / "+" / "," / ";" / "="
  1422. */
  1423. function encodeUriSegment(val) {
  1424. return encodeUriQuery(val, true).
  1425. replace(/%26/gi, '&').
  1426. replace(/%3D/gi, '=').
  1427. replace(/%2B/gi, '+');
  1428. }
  1429. /**
  1430. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1431. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1432. * encoded per http://tools.ietf.org/html/rfc3986:
  1433. * query = *( pchar / "/" / "?" )
  1434. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1435. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1436. * pct-encoded = "%" HEXDIG HEXDIG
  1437. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1438. * / "*" / "+" / "," / ";" / "="
  1439. */
  1440. function encodeUriQuery(val, pctEncodeSpaces) {
  1441. return encodeURIComponent(val).
  1442. replace(/%40/gi, '@').
  1443. replace(/%3A/gi, ':').
  1444. replace(/%24/g, '$').
  1445. replace(/%2C/gi, ',').
  1446. replace(/%3B/gi, ';').
  1447. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1448. }
  1449. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1450. function getNgAttribute(element, ngAttr) {
  1451. var attr, i, ii = ngAttrPrefixes.length;
  1452. for (i = 0; i < ii; ++i) {
  1453. attr = ngAttrPrefixes[i] + ngAttr;
  1454. if (isString(attr = element.getAttribute(attr))) {
  1455. return attr;
  1456. }
  1457. }
  1458. return null;
  1459. }
  1460. function allowAutoBootstrap(document) {
  1461. var script = document.currentScript;
  1462. if (!script) {
  1463. // Support: IE 9-11 only
  1464. // IE does not have `document.currentScript`
  1465. return true;
  1466. }
  1467. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1468. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1469. return false;
  1470. }
  1471. var attributes = script.attributes;
  1472. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1473. return srcs.every(function(src) {
  1474. if (!src) {
  1475. return true;
  1476. }
  1477. if (!src.value) {
  1478. return false;
  1479. }
  1480. var link = document.createElement('a');
  1481. link.href = src.value;
  1482. if (document.location.origin === link.origin) {
  1483. // Same-origin resources are always allowed, even for banned URL schemes.
  1484. return true;
  1485. }
  1486. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1487. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1488. // content security policy in web pages and other browser extensions.
  1489. switch (link.protocol) {
  1490. case 'http:':
  1491. case 'https:':
  1492. case 'ftp:':
  1493. case 'blob:':
  1494. case 'file:':
  1495. case 'data:':
  1496. return true;
  1497. default:
  1498. return false;
  1499. }
  1500. });
  1501. }
  1502. // Cached as it has to run during loading so that document.currentScript is available.
  1503. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1504. /**
  1505. * @ngdoc directive
  1506. * @name ngApp
  1507. * @module ng
  1508. *
  1509. * @element ANY
  1510. * @param {angular.Module} ngApp an optional application
  1511. * {@link angular.module module} name to load.
  1512. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1513. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1514. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1515. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1516. * tracking down the root of these bugs.
  1517. *
  1518. * @description
  1519. *
  1520. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1521. * designates the **root element** of the application and is typically placed near the root element
  1522. * of the page - e.g. on the `<body>` or `<html>` tags.
  1523. *
  1524. * There are a few things to keep in mind when using `ngApp`:
  1525. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1526. * found in the document will be used to define the root element to auto-bootstrap as an
  1527. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1528. * {@link angular.bootstrap} instead.
  1529. * - AngularJS applications cannot be nested within each other.
  1530. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1531. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1532. * {@link ngRoute.ngView `ngView`}.
  1533. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1534. * causing animations to stop working and making the injector inaccessible from outside the app.
  1535. *
  1536. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1537. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1538. * should contain the application code needed or have dependencies on other modules that will
  1539. * contain the code. See {@link angular.module} for more information.
  1540. *
  1541. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1542. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1543. * would not be resolved to `3`.
  1544. *
  1545. * @example
  1546. *
  1547. * ### Simple Usage
  1548. *
  1549. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1550. *
  1551. <example module="ngAppDemo" name="ng-app">
  1552. <file name="index.html">
  1553. <div ng-controller="ngAppDemoController">
  1554. I can add: {{a}} + {{b}} = {{ a+b }}
  1555. </div>
  1556. </file>
  1557. <file name="script.js">
  1558. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1559. $scope.a = 1;
  1560. $scope.b = 2;
  1561. });
  1562. </file>
  1563. </example>
  1564. *
  1565. * @example
  1566. *
  1567. * ### With `ngStrictDi`
  1568. *
  1569. * Using `ngStrictDi`, you would see something like this:
  1570. *
  1571. <example ng-app-included="true" name="strict-di">
  1572. <file name="index.html">
  1573. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1574. <div ng-controller="GoodController1">
  1575. I can add: {{a}} + {{b}} = {{ a+b }}
  1576. <p>This renders because the controller does not fail to
  1577. instantiate, by using explicit annotation style (see
  1578. script.js for details)
  1579. </p>
  1580. </div>
  1581. <div ng-controller="GoodController2">
  1582. Name: <input ng-model="name"><br />
  1583. Hello, {{name}}!
  1584. <p>This renders because the controller does not fail to
  1585. instantiate, by using explicit annotation style
  1586. (see script.js for details)
  1587. </p>
  1588. </div>
  1589. <div ng-controller="BadController">
  1590. I can add: {{a}} + {{b}} = {{ a+b }}
  1591. <p>The controller could not be instantiated, due to relying
  1592. on automatic function annotations (which are disabled in
  1593. strict mode). As such, the content of this section is not
  1594. interpolated, and there should be an error in your web console.
  1595. </p>
  1596. </div>
  1597. </div>
  1598. </file>
  1599. <file name="script.js">
  1600. angular.module('ngAppStrictDemo', [])
  1601. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1602. // rather than an explicit annotation
  1603. .controller('BadController', function($scope) {
  1604. $scope.a = 1;
  1605. $scope.b = 2;
  1606. })
  1607. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1608. // due to using explicit annotations using the array style and $inject property, respectively.
  1609. .controller('GoodController1', ['$scope', function($scope) {
  1610. $scope.a = 1;
  1611. $scope.b = 2;
  1612. }])
  1613. .controller('GoodController2', GoodController2);
  1614. function GoodController2($scope) {
  1615. $scope.name = 'World';
  1616. }
  1617. GoodController2.$inject = ['$scope'];
  1618. </file>
  1619. <file name="style.css">
  1620. div[ng-controller] {
  1621. margin-bottom: 1em;
  1622. -webkit-border-radius: 4px;
  1623. border-radius: 4px;
  1624. border: 1px solid;
  1625. padding: .5em;
  1626. }
  1627. div[ng-controller^=Good] {
  1628. border-color: #d6e9c6;
  1629. background-color: #dff0d8;
  1630. color: #3c763d;
  1631. }
  1632. div[ng-controller^=Bad] {
  1633. border-color: #ebccd1;
  1634. background-color: #f2dede;
  1635. color: #a94442;
  1636. margin-bottom: 0;
  1637. }
  1638. </file>
  1639. </example>
  1640. */
  1641. function angularInit(element, bootstrap) {
  1642. var appElement,
  1643. module,
  1644. config = {};
  1645. // The element `element` has priority over any other element.
  1646. forEach(ngAttrPrefixes, function(prefix) {
  1647. var name = prefix + 'app';
  1648. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1649. appElement = element;
  1650. module = element.getAttribute(name);
  1651. }
  1652. });
  1653. forEach(ngAttrPrefixes, function(prefix) {
  1654. var name = prefix + 'app';
  1655. var candidate;
  1656. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1657. appElement = candidate;
  1658. module = candidate.getAttribute(name);
  1659. }
  1660. });
  1661. if (appElement) {
  1662. if (!isAutoBootstrapAllowed) {
  1663. window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' +
  1664. 'an extension, document.location.href does not match.');
  1665. return;
  1666. }
  1667. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1668. bootstrap(appElement, module ? [module] : [], config);
  1669. }
  1670. }
  1671. /**
  1672. * @ngdoc function
  1673. * @name angular.bootstrap
  1674. * @module ng
  1675. * @description
  1676. * Use this function to manually start up AngularJS application.
  1677. *
  1678. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1679. *
  1680. * AngularJS will detect if it has been loaded into the browser more than once and only allow the
  1681. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1682. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1683. * multiple instances of AngularJS try to work on the DOM.
  1684. *
  1685. * <div class="alert alert-warning">
  1686. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1687. * They must use {@link ng.directive:ngApp ngApp}.
  1688. * </div>
  1689. *
  1690. * <div class="alert alert-warning">
  1691. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1692. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1693. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1694. * causing animations to stop working and making the injector inaccessible from outside the app.
  1695. * </div>
  1696. *
  1697. * ```html
  1698. * <!doctype html>
  1699. * <html>
  1700. * <body>
  1701. * <div ng-controller="WelcomeController">
  1702. * {{greeting}}
  1703. * </div>
  1704. *
  1705. * <script src="angular.js"></script>
  1706. * <script>
  1707. * var app = angular.module('demo', [])
  1708. * .controller('WelcomeController', function($scope) {
  1709. * $scope.greeting = 'Welcome!';
  1710. * });
  1711. * angular.bootstrap(document, ['demo']);
  1712. * </script>
  1713. * </body>
  1714. * </html>
  1715. * ```
  1716. *
  1717. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1718. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1719. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1720. * function that will be invoked by the injector as a `config` block.
  1721. * See: {@link angular.module modules}
  1722. * @param {Object=} config an object for defining configuration options for the application. The
  1723. * following keys are supported:
  1724. *
  1725. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1726. * assist in finding bugs which break minified code. Defaults to `false`.
  1727. *
  1728. * @returns {auto.$injector} Returns the newly created injector for this app.
  1729. */
  1730. function bootstrap(element, modules, config) {
  1731. if (!isObject(config)) config = {};
  1732. var defaultConfig = {
  1733. strictDi: false
  1734. };
  1735. config = extend(defaultConfig, config);
  1736. var doBootstrap = function() {
  1737. element = jqLite(element);
  1738. if (element.injector()) {
  1739. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1740. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1741. throw ngMinErr(
  1742. 'btstrpd',
  1743. 'App already bootstrapped with this element \'{0}\'',
  1744. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1745. }
  1746. modules = modules || [];
  1747. modules.unshift(['$provide', function($provide) {
  1748. $provide.value('$rootElement', element);
  1749. }]);
  1750. if (config.debugInfoEnabled) {
  1751. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1752. modules.push(['$compileProvider', function($compileProvider) {
  1753. $compileProvider.debugInfoEnabled(true);
  1754. }]);
  1755. }
  1756. modules.unshift('ng');
  1757. var injector = createInjector(modules, config.strictDi);
  1758. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1759. function bootstrapApply(scope, element, compile, injector) {
  1760. scope.$apply(function() {
  1761. element.data('$injector', injector);
  1762. compile(element)(scope);
  1763. });
  1764. }]
  1765. );
  1766. return injector;
  1767. };
  1768. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1769. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1770. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1771. config.debugInfoEnabled = true;
  1772. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1773. }
  1774. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1775. return doBootstrap();
  1776. }
  1777. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1778. angular.resumeBootstrap = function(extraModules) {
  1779. forEach(extraModules, function(module) {
  1780. modules.push(module);
  1781. });
  1782. return doBootstrap();
  1783. };
  1784. if (isFunction(angular.resumeDeferredBootstrap)) {
  1785. angular.resumeDeferredBootstrap();
  1786. }
  1787. }
  1788. /**
  1789. * @ngdoc function
  1790. * @name angular.reloadWithDebugInfo
  1791. * @module ng
  1792. * @description
  1793. * Use this function to reload the current application with debug information turned on.
  1794. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1795. *
  1796. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1797. */
  1798. function reloadWithDebugInfo() {
  1799. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1800. window.location.reload();
  1801. }
  1802. /**
  1803. * @name angular.getTestability
  1804. * @module ng
  1805. * @description
  1806. * Get the testability service for the instance of AngularJS on the given
  1807. * element.
  1808. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1809. */
  1810. function getTestability(rootElement) {
  1811. var injector = angular.element(rootElement).injector();
  1812. if (!injector) {
  1813. throw ngMinErr('test',
  1814. 'no injector found for element argument to getTestability');
  1815. }
  1816. return injector.get('$$testability');
  1817. }
  1818. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1819. function snake_case(name, separator) {
  1820. separator = separator || '_';
  1821. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1822. return (pos ? separator : '') + letter.toLowerCase();
  1823. });
  1824. }
  1825. var bindJQueryFired = false;
  1826. function bindJQuery() {
  1827. var originalCleanData;
  1828. if (bindJQueryFired) {
  1829. return;
  1830. }
  1831. // bind to jQuery if present;
  1832. var jqName = jq();
  1833. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1834. !jqName ? undefined : // use jqLite
  1835. window[jqName]; // use jQuery specified by `ngJq`
  1836. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1837. // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.
  1838. // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1839. // versions. It will not work for sure with jQuery <1.7, though.
  1840. if (jQuery && jQuery.fn.on) {
  1841. jqLite = jQuery;
  1842. extend(jQuery.fn, {
  1843. scope: JQLitePrototype.scope,
  1844. isolateScope: JQLitePrototype.isolateScope,
  1845. controller: /** @type {?} */ (JQLitePrototype).controller,
  1846. injector: JQLitePrototype.injector,
  1847. inheritedData: JQLitePrototype.inheritedData
  1848. });
  1849. } else {
  1850. jqLite = JQLite;
  1851. }
  1852. // All nodes removed from the DOM via various jqLite/jQuery APIs like .remove()
  1853. // are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire
  1854. // the $destroy event on all removed nodes.
  1855. originalCleanData = jqLite.cleanData;
  1856. jqLite.cleanData = function(elems) {
  1857. var events;
  1858. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1859. events = (jqLite._data(elem) || {}).events;
  1860. if (events && events.$destroy) {
  1861. jqLite(elem).triggerHandler('$destroy');
  1862. }
  1863. }
  1864. originalCleanData(elems);
  1865. };
  1866. angular.element = jqLite;
  1867. // Prevent double-proxying.
  1868. bindJQueryFired = true;
  1869. }
  1870. /**
  1871. * @ngdoc function
  1872. * @name angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement
  1873. * @module ng
  1874. * @kind function
  1875. *
  1876. * @description
  1877. * Restores the pre-1.8 behavior of jqLite that turns XHTML-like strings like
  1878. * `<div /><span />` to `<div></div><span></span>` instead of `<div><span></span></div>`.
  1879. * The new behavior is a security fix. Thus, if you need to call this function, please try to adjust
  1880. * your code for this change and remove your use of this function as soon as possible.
  1881. * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the
  1882. * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details
  1883. * about the workarounds.
  1884. */
  1885. function UNSAFE_restoreLegacyJqLiteXHTMLReplacement() {
  1886. JQLite.legacyXHTMLReplacement = true;
  1887. }
  1888. /**
  1889. * throw error if the argument is falsy.
  1890. */
  1891. function assertArg(arg, name, reason) {
  1892. if (!arg) {
  1893. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1894. }
  1895. return arg;
  1896. }
  1897. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1898. if (acceptArrayAnnotation && isArray(arg)) {
  1899. arg = arg[arg.length - 1];
  1900. }
  1901. assertArg(isFunction(arg), name, 'not a function, got ' +
  1902. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1903. return arg;
  1904. }
  1905. /**
  1906. * throw error if the name given is hasOwnProperty
  1907. * @param {String} name the name to test
  1908. * @param {String} context the context in which the name is used, such as module or directive
  1909. */
  1910. function assertNotHasOwnProperty(name, context) {
  1911. if (name === 'hasOwnProperty') {
  1912. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1913. }
  1914. }
  1915. /**
  1916. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1917. * @param {Object} obj starting object
  1918. * @param {String} path path to traverse
  1919. * @param {boolean} [bindFnToScope=true]
  1920. * @returns {Object} value as accessible by path
  1921. */
  1922. //TODO(misko): this function needs to be removed
  1923. function getter(obj, path, bindFnToScope) {
  1924. if (!path) return obj;
  1925. var keys = path.split('.');
  1926. var key;
  1927. var lastInstance = obj;
  1928. var len = keys.length;
  1929. for (var i = 0; i < len; i++) {
  1930. key = keys[i];
  1931. if (obj) {
  1932. obj = (lastInstance = obj)[key];
  1933. }
  1934. }
  1935. if (!bindFnToScope && isFunction(obj)) {
  1936. return bind(lastInstance, obj);
  1937. }
  1938. return obj;
  1939. }
  1940. /**
  1941. * Return the DOM siblings between the first and last node in the given array.
  1942. * @param {Array} array like object
  1943. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1944. */
  1945. function getBlockNodes(nodes) {
  1946. // TODO(perf): update `nodes` instead of creating a new object?
  1947. var node = nodes[0];
  1948. var endNode = nodes[nodes.length - 1];
  1949. var blockNodes;
  1950. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1951. if (blockNodes || nodes[i] !== node) {
  1952. if (!blockNodes) {
  1953. blockNodes = jqLite(slice.call(nodes, 0, i));
  1954. }
  1955. blockNodes.push(node);
  1956. }
  1957. }
  1958. return blockNodes || nodes;
  1959. }
  1960. /**
  1961. * Creates a new object without a prototype. This object is useful for lookup without having to
  1962. * guard against prototypically inherited properties via hasOwnProperty.
  1963. *
  1964. * Related micro-benchmarks:
  1965. * - http://jsperf.com/object-create2
  1966. * - http://jsperf.com/proto-map-lookup/2
  1967. * - http://jsperf.com/for-in-vs-object-keys2
  1968. *
  1969. * @returns {Object}
  1970. */
  1971. function createMap() {
  1972. return Object.create(null);
  1973. }
  1974. function stringify(value) {
  1975. if (value == null) { // null || undefined
  1976. return '';
  1977. }
  1978. switch (typeof value) {
  1979. case 'string':
  1980. break;
  1981. case 'number':
  1982. value = '' + value;
  1983. break;
  1984. default:
  1985. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1986. value = value.toString();
  1987. } else {
  1988. value = toJson(value);
  1989. }
  1990. }
  1991. return value;
  1992. }
  1993. var NODE_TYPE_ELEMENT = 1;
  1994. var NODE_TYPE_ATTRIBUTE = 2;
  1995. var NODE_TYPE_TEXT = 3;
  1996. var NODE_TYPE_COMMENT = 8;
  1997. var NODE_TYPE_DOCUMENT = 9;
  1998. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1999. /**
  2000. * @ngdoc type
  2001. * @name angular.Module
  2002. * @module ng
  2003. * @description
  2004. *
  2005. * Interface for configuring AngularJS {@link angular.module modules}.
  2006. */
  2007. function setupModuleLoader(window) {
  2008. var $injectorMinErr = minErr('$injector');
  2009. var ngMinErr = minErr('ng');
  2010. function ensure(obj, name, factory) {
  2011. return obj[name] || (obj[name] = factory());
  2012. }
  2013. var angular = ensure(window, 'angular', Object);
  2014. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  2015. angular.$$minErr = angular.$$minErr || minErr;
  2016. return ensure(angular, 'module', function() {
  2017. /** @type {Object.<string, angular.Module>} */
  2018. var modules = {};
  2019. /**
  2020. * @ngdoc function
  2021. * @name angular.module
  2022. * @module ng
  2023. * @description
  2024. *
  2025. * The `angular.module` is a global place for creating, registering and retrieving AngularJS
  2026. * modules.
  2027. * All modules (AngularJS core or 3rd party) that should be available to an application must be
  2028. * registered using this mechanism.
  2029. *
  2030. * Passing one argument retrieves an existing {@link angular.Module},
  2031. * whereas passing more than one argument creates a new {@link angular.Module}
  2032. *
  2033. *
  2034. * # Module
  2035. *
  2036. * A module is a collection of services, directives, controllers, filters, and configuration information.
  2037. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  2038. *
  2039. * ```js
  2040. * // Create a new module
  2041. * var myModule = angular.module('myModule', []);
  2042. *
  2043. * // register a new service
  2044. * myModule.value('appName', 'MyCoolApp');
  2045. *
  2046. * // configure existing services inside initialization blocks.
  2047. * myModule.config(['$locationProvider', function($locationProvider) {
  2048. * // Configure existing providers
  2049. * $locationProvider.hashPrefix('!');
  2050. * }]);
  2051. * ```
  2052. *
  2053. * Then you can create an injector and load your modules like this:
  2054. *
  2055. * ```js
  2056. * var injector = angular.injector(['ng', 'myModule'])
  2057. * ```
  2058. *
  2059. * However it's more likely that you'll just use
  2060. * {@link ng.directive:ngApp ngApp} or
  2061. * {@link angular.bootstrap} to simplify this process for you.
  2062. *
  2063. * @param {!string} name The name of the module to create or retrieve.
  2064. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2065. * unspecified then the module is being retrieved for further configuration.
  2066. * @param {Function=} configFn Optional configuration function for the module. Same as
  2067. * {@link angular.Module#config Module#config()}.
  2068. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2069. */
  2070. return function module(name, requires, configFn) {
  2071. var info = {};
  2072. var assertNotHasOwnProperty = function(name, context) {
  2073. if (name === 'hasOwnProperty') {
  2074. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2075. }
  2076. };
  2077. assertNotHasOwnProperty(name, 'module');
  2078. if (requires && modules.hasOwnProperty(name)) {
  2079. modules[name] = null;
  2080. }
  2081. return ensure(modules, name, function() {
  2082. if (!requires) {
  2083. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2084. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2085. 'specify the dependencies as the second argument.', name);
  2086. }
  2087. /** @type {!Array.<Array.<*>>} */
  2088. var invokeQueue = [];
  2089. /** @type {!Array.<Function>} */
  2090. var configBlocks = [];
  2091. /** @type {!Array.<Function>} */
  2092. var runBlocks = [];
  2093. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2094. /** @type {angular.Module} */
  2095. var moduleInstance = {
  2096. // Private state
  2097. _invokeQueue: invokeQueue,
  2098. _configBlocks: configBlocks,
  2099. _runBlocks: runBlocks,
  2100. /**
  2101. * @ngdoc method
  2102. * @name angular.Module#info
  2103. * @module ng
  2104. *
  2105. * @param {Object=} info Information about the module
  2106. * @returns {Object|Module} The current info object for this module if called as a getter,
  2107. * or `this` if called as a setter.
  2108. *
  2109. * @description
  2110. * Read and write custom information about this module.
  2111. * For example you could put the version of the module in here.
  2112. *
  2113. * ```js
  2114. * angular.module('myModule', []).info({ version: '1.0.0' });
  2115. * ```
  2116. *
  2117. * The version could then be read back out by accessing the module elsewhere:
  2118. *
  2119. * ```
  2120. * var version = angular.module('myModule').info().version;
  2121. * ```
  2122. *
  2123. * You can also retrieve this information during runtime via the
  2124. * {@link $injector#modules `$injector.modules`} property:
  2125. *
  2126. * ```js
  2127. * var version = $injector.modules['myModule'].info().version;
  2128. * ```
  2129. */
  2130. info: function(value) {
  2131. if (isDefined(value)) {
  2132. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2133. info = value;
  2134. return this;
  2135. }
  2136. return info;
  2137. },
  2138. /**
  2139. * @ngdoc property
  2140. * @name angular.Module#requires
  2141. * @module ng
  2142. *
  2143. * @description
  2144. * Holds the list of modules which the injector will load before the current module is
  2145. * loaded.
  2146. */
  2147. requires: requires,
  2148. /**
  2149. * @ngdoc property
  2150. * @name angular.Module#name
  2151. * @module ng
  2152. *
  2153. * @description
  2154. * Name of the module.
  2155. */
  2156. name: name,
  2157. /**
  2158. * @ngdoc method
  2159. * @name angular.Module#provider
  2160. * @module ng
  2161. * @param {string} name service name
  2162. * @param {Function} providerType Construction function for creating new instance of the
  2163. * service.
  2164. * @description
  2165. * See {@link auto.$provide#provider $provide.provider()}.
  2166. */
  2167. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2168. /**
  2169. * @ngdoc method
  2170. * @name angular.Module#factory
  2171. * @module ng
  2172. * @param {string} name service name
  2173. * @param {Function} providerFunction Function for creating new instance of the service.
  2174. * @description
  2175. * See {@link auto.$provide#factory $provide.factory()}.
  2176. */
  2177. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2178. /**
  2179. * @ngdoc method
  2180. * @name angular.Module#service
  2181. * @module ng
  2182. * @param {string} name service name
  2183. * @param {Function} constructor A constructor function that will be instantiated.
  2184. * @description
  2185. * See {@link auto.$provide#service $provide.service()}.
  2186. */
  2187. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2188. /**
  2189. * @ngdoc method
  2190. * @name angular.Module#value
  2191. * @module ng
  2192. * @param {string} name service name
  2193. * @param {*} object Service instance object.
  2194. * @description
  2195. * See {@link auto.$provide#value $provide.value()}.
  2196. */
  2197. value: invokeLater('$provide', 'value'),
  2198. /**
  2199. * @ngdoc method
  2200. * @name angular.Module#constant
  2201. * @module ng
  2202. * @param {string} name constant name
  2203. * @param {*} object Constant value.
  2204. * @description
  2205. * Because the constants are fixed, they get applied before other provide methods.
  2206. * See {@link auto.$provide#constant $provide.constant()}.
  2207. */
  2208. constant: invokeLater('$provide', 'constant', 'unshift'),
  2209. /**
  2210. * @ngdoc method
  2211. * @name angular.Module#decorator
  2212. * @module ng
  2213. * @param {string} name The name of the service to decorate.
  2214. * @param {Function} decorFn This function will be invoked when the service needs to be
  2215. * instantiated and should return the decorated service instance.
  2216. * @description
  2217. * See {@link auto.$provide#decorator $provide.decorator()}.
  2218. */
  2219. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2220. /**
  2221. * @ngdoc method
  2222. * @name angular.Module#animation
  2223. * @module ng
  2224. * @param {string} name animation name
  2225. * @param {Function} animationFactory Factory function for creating new instance of an
  2226. * animation.
  2227. * @description
  2228. *
  2229. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2230. *
  2231. *
  2232. * Defines an animation hook that can be later used with
  2233. * {@link $animate $animate} service and directives that use this service.
  2234. *
  2235. * ```js
  2236. * module.animation('.animation-name', function($inject1, $inject2) {
  2237. * return {
  2238. * eventName : function(element, done) {
  2239. * //code to run the animation
  2240. * //once complete, then run done()
  2241. * return function cancellationFunction(element) {
  2242. * //code to cancel the animation
  2243. * }
  2244. * }
  2245. * }
  2246. * })
  2247. * ```
  2248. *
  2249. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2250. * {@link ngAnimate ngAnimate module} for more information.
  2251. */
  2252. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2253. /**
  2254. * @ngdoc method
  2255. * @name angular.Module#filter
  2256. * @module ng
  2257. * @param {string} name Filter name - this must be a valid AngularJS expression identifier
  2258. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2259. * @description
  2260. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2261. *
  2262. * <div class="alert alert-warning">
  2263. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2264. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2265. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2266. * (`myapp_subsection_filterx`).
  2267. * </div>
  2268. */
  2269. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2270. /**
  2271. * @ngdoc method
  2272. * @name angular.Module#controller
  2273. * @module ng
  2274. * @param {string|Object} name Controller name, or an object map of controllers where the
  2275. * keys are the names and the values are the constructors.
  2276. * @param {Function} constructor Controller constructor function.
  2277. * @description
  2278. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2279. */
  2280. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2281. /**
  2282. * @ngdoc method
  2283. * @name angular.Module#directive
  2284. * @module ng
  2285. * @param {string|Object} name Directive name, or an object map of directives where the
  2286. * keys are the names and the values are the factories.
  2287. * @param {Function} directiveFactory Factory function for creating new instance of
  2288. * directives.
  2289. * @description
  2290. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2291. */
  2292. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2293. /**
  2294. * @ngdoc method
  2295. * @name angular.Module#component
  2296. * @module ng
  2297. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  2298. * or an object map of components where the keys are the names and the values are the component definition objects.
  2299. * @param {Object} options Component definition object (a simplified
  2300. * {@link ng.$compile#directive-definition-object directive definition object})
  2301. *
  2302. * @description
  2303. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2304. */
  2305. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2306. /**
  2307. * @ngdoc method
  2308. * @name angular.Module#config
  2309. * @module ng
  2310. * @param {Function} configFn Execute this function on module load. Useful for service
  2311. * configuration.
  2312. * @description
  2313. * Use this method to configure services by injecting their
  2314. * {@link angular.Module#provider `providers`}, e.g. for adding routes to the
  2315. * {@link ngRoute.$routeProvider $routeProvider}.
  2316. *
  2317. * Note that you can only inject {@link angular.Module#provider `providers`} and
  2318. * {@link angular.Module#constant `constants`} into this function.
  2319. *
  2320. * For more about how to configure services, see
  2321. * {@link providers#provider-recipe Provider Recipe}.
  2322. */
  2323. config: config,
  2324. /**
  2325. * @ngdoc method
  2326. * @name angular.Module#run
  2327. * @module ng
  2328. * @param {Function} initializationFn Execute this function after injector creation.
  2329. * Useful for application initialization.
  2330. * @description
  2331. * Use this method to register work which should be performed when the injector is done
  2332. * loading all modules.
  2333. */
  2334. run: function(block) {
  2335. runBlocks.push(block);
  2336. return this;
  2337. }
  2338. };
  2339. if (configFn) {
  2340. config(configFn);
  2341. }
  2342. return moduleInstance;
  2343. /**
  2344. * @param {string} provider
  2345. * @param {string} method
  2346. * @param {String=} insertMethod
  2347. * @returns {angular.Module}
  2348. */
  2349. function invokeLater(provider, method, insertMethod, queue) {
  2350. if (!queue) queue = invokeQueue;
  2351. return function() {
  2352. queue[insertMethod || 'push']([provider, method, arguments]);
  2353. return moduleInstance;
  2354. };
  2355. }
  2356. /**
  2357. * @param {string} provider
  2358. * @param {string} method
  2359. * @returns {angular.Module}
  2360. */
  2361. function invokeLaterAndSetModuleName(provider, method, queue) {
  2362. if (!queue) queue = invokeQueue;
  2363. return function(recipeName, factoryFunction) {
  2364. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2365. queue.push([provider, method, arguments]);
  2366. return moduleInstance;
  2367. };
  2368. }
  2369. });
  2370. };
  2371. });
  2372. }
  2373. /* global shallowCopy: true */
  2374. /**
  2375. * Creates a shallow copy of an object, an array or a primitive.
  2376. *
  2377. * Assumes that there are no proto properties for objects.
  2378. */
  2379. function shallowCopy(src, dst) {
  2380. if (isArray(src)) {
  2381. dst = dst || [];
  2382. for (var i = 0, ii = src.length; i < ii; i++) {
  2383. dst[i] = src[i];
  2384. }
  2385. } else if (isObject(src)) {
  2386. dst = dst || {};
  2387. for (var key in src) {
  2388. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2389. dst[key] = src[key];
  2390. }
  2391. }
  2392. }
  2393. return dst || src;
  2394. }
  2395. /* exported toDebugString */
  2396. function serializeObject(obj, maxDepth) {
  2397. var seen = [];
  2398. // There is no direct way to stringify object until reaching a specific depth
  2399. // and a very deep object can cause a performance issue, so we copy the object
  2400. // based on this specific depth and then stringify it.
  2401. if (isValidObjectMaxDepth(maxDepth)) {
  2402. // This file is also included in `angular-loader`, so `copy()` might not always be available in
  2403. // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
  2404. obj = angular.copy(obj, null, maxDepth);
  2405. }
  2406. return JSON.stringify(obj, function(key, val) {
  2407. val = toJsonReplacer(key, val);
  2408. if (isObject(val)) {
  2409. if (seen.indexOf(val) >= 0) return '...';
  2410. seen.push(val);
  2411. }
  2412. return val;
  2413. });
  2414. }
  2415. function toDebugString(obj, maxDepth) {
  2416. if (typeof obj === 'function') {
  2417. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2418. } else if (isUndefined(obj)) {
  2419. return 'undefined';
  2420. } else if (typeof obj !== 'string') {
  2421. return serializeObject(obj, maxDepth);
  2422. }
  2423. return obj;
  2424. }
  2425. /* global angularModule: true,
  2426. version: true,
  2427. $CompileProvider,
  2428. htmlAnchorDirective,
  2429. inputDirective,
  2430. hiddenInputBrowserCacheDirective,
  2431. formDirective,
  2432. scriptDirective,
  2433. selectDirective,
  2434. optionDirective,
  2435. ngBindDirective,
  2436. ngBindHtmlDirective,
  2437. ngBindTemplateDirective,
  2438. ngClassDirective,
  2439. ngClassEvenDirective,
  2440. ngClassOddDirective,
  2441. ngCloakDirective,
  2442. ngControllerDirective,
  2443. ngFormDirective,
  2444. ngHideDirective,
  2445. ngIfDirective,
  2446. ngIncludeDirective,
  2447. ngIncludeFillContentDirective,
  2448. ngInitDirective,
  2449. ngNonBindableDirective,
  2450. ngPluralizeDirective,
  2451. ngRefDirective,
  2452. ngRepeatDirective,
  2453. ngShowDirective,
  2454. ngStyleDirective,
  2455. ngSwitchDirective,
  2456. ngSwitchWhenDirective,
  2457. ngSwitchDefaultDirective,
  2458. ngOptionsDirective,
  2459. ngTranscludeDirective,
  2460. ngModelDirective,
  2461. ngListDirective,
  2462. ngChangeDirective,
  2463. patternDirective,
  2464. patternDirective,
  2465. requiredDirective,
  2466. requiredDirective,
  2467. minlengthDirective,
  2468. minlengthDirective,
  2469. maxlengthDirective,
  2470. maxlengthDirective,
  2471. ngValueDirective,
  2472. ngModelOptionsDirective,
  2473. ngAttributeAliasDirectives,
  2474. ngEventDirectives,
  2475. $AnchorScrollProvider,
  2476. $AnimateProvider,
  2477. $CoreAnimateCssProvider,
  2478. $$CoreAnimateJsProvider,
  2479. $$CoreAnimateQueueProvider,
  2480. $$AnimateRunnerFactoryProvider,
  2481. $$AnimateAsyncRunFactoryProvider,
  2482. $BrowserProvider,
  2483. $CacheFactoryProvider,
  2484. $ControllerProvider,
  2485. $DateProvider,
  2486. $DocumentProvider,
  2487. $$IsDocumentHiddenProvider,
  2488. $ExceptionHandlerProvider,
  2489. $FilterProvider,
  2490. $$ForceReflowProvider,
  2491. $InterpolateProvider,
  2492. $$IntervalFactoryProvider,
  2493. $IntervalProvider,
  2494. $HttpProvider,
  2495. $HttpParamSerializerProvider,
  2496. $HttpParamSerializerJQLikeProvider,
  2497. $HttpBackendProvider,
  2498. $xhrFactoryProvider,
  2499. $jsonpCallbacksProvider,
  2500. $LocationProvider,
  2501. $LogProvider,
  2502. $$MapProvider,
  2503. $ParseProvider,
  2504. $RootScopeProvider,
  2505. $QProvider,
  2506. $$QProvider,
  2507. $$SanitizeUriProvider,
  2508. $SceProvider,
  2509. $SceDelegateProvider,
  2510. $SnifferProvider,
  2511. $$TaskTrackerFactoryProvider,
  2512. $TemplateCacheProvider,
  2513. $TemplateRequestProvider,
  2514. $$TestabilityProvider,
  2515. $TimeoutProvider,
  2516. $$RAFProvider,
  2517. $WindowProvider,
  2518. $$jqLiteProvider,
  2519. $$CookieReaderProvider
  2520. */
  2521. /**
  2522. * @ngdoc object
  2523. * @name angular.version
  2524. * @module ng
  2525. * @description
  2526. * An object that contains information about the current AngularJS version.
  2527. *
  2528. * This object has the following properties:
  2529. *
  2530. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2531. * - `major` – `{number}` – Major version number, such as "0".
  2532. * - `minor` – `{number}` – Minor version number, such as "9".
  2533. * - `dot` – `{number}` – Dot version number, such as "18".
  2534. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2535. */
  2536. var version = {
  2537. // These placeholder strings will be replaced by grunt's `build` task.
  2538. // They need to be double- or single-quoted.
  2539. full: '1.8.2',
  2540. major: 1,
  2541. minor: 8,
  2542. dot: 2,
  2543. codeName: 'meteoric-mining'
  2544. };
  2545. function publishExternalAPI(angular) {
  2546. extend(angular, {
  2547. 'errorHandlingConfig': errorHandlingConfig,
  2548. 'bootstrap': bootstrap,
  2549. 'copy': copy,
  2550. 'extend': extend,
  2551. 'merge': merge,
  2552. 'equals': equals,
  2553. 'element': jqLite,
  2554. 'forEach': forEach,
  2555. 'injector': createInjector,
  2556. 'noop': noop,
  2557. 'bind': bind,
  2558. 'toJson': toJson,
  2559. 'fromJson': fromJson,
  2560. 'identity': identity,
  2561. 'isUndefined': isUndefined,
  2562. 'isDefined': isDefined,
  2563. 'isString': isString,
  2564. 'isFunction': isFunction,
  2565. 'isObject': isObject,
  2566. 'isNumber': isNumber,
  2567. 'isElement': isElement,
  2568. 'isArray': isArray,
  2569. 'version': version,
  2570. 'isDate': isDate,
  2571. 'callbacks': {$$counter: 0},
  2572. 'getTestability': getTestability,
  2573. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2574. 'UNSAFE_restoreLegacyJqLiteXHTMLReplacement': UNSAFE_restoreLegacyJqLiteXHTMLReplacement,
  2575. '$$minErr': minErr,
  2576. '$$csp': csp,
  2577. '$$encodeUriSegment': encodeUriSegment,
  2578. '$$encodeUriQuery': encodeUriQuery,
  2579. '$$lowercase': lowercase,
  2580. '$$stringify': stringify,
  2581. '$$uppercase': uppercase
  2582. });
  2583. angularModule = setupModuleLoader(window);
  2584. angularModule('ng', ['ngLocale'], ['$provide',
  2585. function ngModule($provide) {
  2586. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2587. $provide.provider({
  2588. $$sanitizeUri: $$SanitizeUriProvider
  2589. });
  2590. $provide.provider('$compile', $CompileProvider).
  2591. directive({
  2592. a: htmlAnchorDirective,
  2593. input: inputDirective,
  2594. textarea: inputDirective,
  2595. form: formDirective,
  2596. script: scriptDirective,
  2597. select: selectDirective,
  2598. option: optionDirective,
  2599. ngBind: ngBindDirective,
  2600. ngBindHtml: ngBindHtmlDirective,
  2601. ngBindTemplate: ngBindTemplateDirective,
  2602. ngClass: ngClassDirective,
  2603. ngClassEven: ngClassEvenDirective,
  2604. ngClassOdd: ngClassOddDirective,
  2605. ngCloak: ngCloakDirective,
  2606. ngController: ngControllerDirective,
  2607. ngForm: ngFormDirective,
  2608. ngHide: ngHideDirective,
  2609. ngIf: ngIfDirective,
  2610. ngInclude: ngIncludeDirective,
  2611. ngInit: ngInitDirective,
  2612. ngNonBindable: ngNonBindableDirective,
  2613. ngPluralize: ngPluralizeDirective,
  2614. ngRef: ngRefDirective,
  2615. ngRepeat: ngRepeatDirective,
  2616. ngShow: ngShowDirective,
  2617. ngStyle: ngStyleDirective,
  2618. ngSwitch: ngSwitchDirective,
  2619. ngSwitchWhen: ngSwitchWhenDirective,
  2620. ngSwitchDefault: ngSwitchDefaultDirective,
  2621. ngOptions: ngOptionsDirective,
  2622. ngTransclude: ngTranscludeDirective,
  2623. ngModel: ngModelDirective,
  2624. ngList: ngListDirective,
  2625. ngChange: ngChangeDirective,
  2626. pattern: patternDirective,
  2627. ngPattern: patternDirective,
  2628. required: requiredDirective,
  2629. ngRequired: requiredDirective,
  2630. minlength: minlengthDirective,
  2631. ngMinlength: minlengthDirective,
  2632. maxlength: maxlengthDirective,
  2633. ngMaxlength: maxlengthDirective,
  2634. ngValue: ngValueDirective,
  2635. ngModelOptions: ngModelOptionsDirective
  2636. }).
  2637. directive({
  2638. ngInclude: ngIncludeFillContentDirective,
  2639. input: hiddenInputBrowserCacheDirective
  2640. }).
  2641. directive(ngAttributeAliasDirectives).
  2642. directive(ngEventDirectives);
  2643. $provide.provider({
  2644. $anchorScroll: $AnchorScrollProvider,
  2645. $animate: $AnimateProvider,
  2646. $animateCss: $CoreAnimateCssProvider,
  2647. $$animateJs: $$CoreAnimateJsProvider,
  2648. $$animateQueue: $$CoreAnimateQueueProvider,
  2649. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2650. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2651. $browser: $BrowserProvider,
  2652. $cacheFactory: $CacheFactoryProvider,
  2653. $controller: $ControllerProvider,
  2654. $document: $DocumentProvider,
  2655. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2656. $exceptionHandler: $ExceptionHandlerProvider,
  2657. $filter: $FilterProvider,
  2658. $$forceReflow: $$ForceReflowProvider,
  2659. $interpolate: $InterpolateProvider,
  2660. $interval: $IntervalProvider,
  2661. $$intervalFactory: $$IntervalFactoryProvider,
  2662. $http: $HttpProvider,
  2663. $httpParamSerializer: $HttpParamSerializerProvider,
  2664. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2665. $httpBackend: $HttpBackendProvider,
  2666. $xhrFactory: $xhrFactoryProvider,
  2667. $jsonpCallbacks: $jsonpCallbacksProvider,
  2668. $location: $LocationProvider,
  2669. $log: $LogProvider,
  2670. $parse: $ParseProvider,
  2671. $rootScope: $RootScopeProvider,
  2672. $q: $QProvider,
  2673. $$q: $$QProvider,
  2674. $sce: $SceProvider,
  2675. $sceDelegate: $SceDelegateProvider,
  2676. $sniffer: $SnifferProvider,
  2677. $$taskTrackerFactory: $$TaskTrackerFactoryProvider,
  2678. $templateCache: $TemplateCacheProvider,
  2679. $templateRequest: $TemplateRequestProvider,
  2680. $$testability: $$TestabilityProvider,
  2681. $timeout: $TimeoutProvider,
  2682. $window: $WindowProvider,
  2683. $$rAF: $$RAFProvider,
  2684. $$jqLite: $$jqLiteProvider,
  2685. $$Map: $$MapProvider,
  2686. $$cookieReader: $$CookieReaderProvider
  2687. });
  2688. }
  2689. ])
  2690. .info({ angularVersion: '1.8.2' });
  2691. }
  2692. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2693. * Any commits to this file should be reviewed with security in mind. *
  2694. * Changes to this file can potentially create security vulnerabilities. *
  2695. * An approval from 2 Core members with history of modifying *
  2696. * this file is required. *
  2697. * *
  2698. * Does the change somehow allow for arbitrary javascript to be executed? *
  2699. * Or allows for someone to change the prototype of built-in objects? *
  2700. * Or gives undesired access to variables likes document or window? *
  2701. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2702. /* global
  2703. JQLitePrototype: true,
  2704. BOOLEAN_ATTR: true,
  2705. ALIASED_ATTR: true
  2706. */
  2707. //////////////////////////////////
  2708. //JQLite
  2709. //////////////////////////////////
  2710. /**
  2711. * @ngdoc function
  2712. * @name angular.element
  2713. * @module ng
  2714. * @kind function
  2715. *
  2716. * @description
  2717. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2718. *
  2719. * If jQuery is available, `angular.element` is an alias for the
  2720. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2721. * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2722. *
  2723. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2724. * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2725. * commonly needed functionality with the goal of having a very small footprint.
  2726. *
  2727. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2728. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2729. * specific version of jQuery if multiple versions exist on the page.
  2730. *
  2731. * <div class="alert alert-info">**Note:** All element references in AngularJS are always wrapped with jQuery or
  2732. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2733. *
  2734. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2735. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2736. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2737. *
  2738. * ## AngularJS's jqLite
  2739. * jqLite provides only the following jQuery methods:
  2740. *
  2741. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2742. * - [`after()`](http://api.jquery.com/after/)
  2743. * - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements
  2744. * so will not work correctly when invoked on a jqLite object containing more than one DOM node
  2745. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2746. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2747. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2748. * - [`clone()`](http://api.jquery.com/clone/)
  2749. * - [`contents()`](http://api.jquery.com/contents/)
  2750. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2751. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2752. * - [`data()`](http://api.jquery.com/data/)
  2753. * - [`detach()`](http://api.jquery.com/detach/)
  2754. * - [`empty()`](http://api.jquery.com/empty/)
  2755. * - [`eq()`](http://api.jquery.com/eq/)
  2756. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2757. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2758. * - [`html()`](http://api.jquery.com/html/)
  2759. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2760. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2761. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2762. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2763. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2764. * - [`prepend()`](http://api.jquery.com/prepend/)
  2765. * - [`prop()`](http://api.jquery.com/prop/)
  2766. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2767. * - [`remove()`](http://api.jquery.com/remove/)
  2768. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2769. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2770. * - [`removeData()`](http://api.jquery.com/removeData/)
  2771. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2772. * - [`text()`](http://api.jquery.com/text/)
  2773. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2774. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2775. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2776. * - [`val()`](http://api.jquery.com/val/)
  2777. * - [`wrap()`](http://api.jquery.com/wrap/)
  2778. *
  2779. * jqLite also provides a method restoring pre-1.8 insecure treatment of XHTML-like tags.
  2780. * This legacy behavior turns input like `<div /><span />` to `<div></div><span></span>`
  2781. * instead of `<div><span></span></div>` like version 1.8 & newer do. To restore it, invoke:
  2782. * ```js
  2783. * angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement();
  2784. * ```
  2785. * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the
  2786. * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details
  2787. * about the workarounds.
  2788. *
  2789. * ## jQuery/jqLite Extras
  2790. * AngularJS also provides the following additional methods and events to both jQuery and jqLite:
  2791. *
  2792. * ### Events
  2793. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2794. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2795. * element before it is removed.
  2796. *
  2797. * ### Methods
  2798. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2799. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2800. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2801. * `'ngModel'`).
  2802. * - `injector()` - retrieves the injector of the current element or its parent.
  2803. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2804. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2805. * be enabled.
  2806. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2807. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2808. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2809. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2810. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2811. * parent element is reached.
  2812. *
  2813. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2814. * https://github.com/angular/angular.js/issues/14251 for more information.
  2815. *
  2816. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2817. * @returns {Object} jQuery object.
  2818. */
  2819. JQLite.expando = 'ng339';
  2820. var jqCache = JQLite.cache = {},
  2821. jqId = 1;
  2822. /*
  2823. * !!! This is an undocumented "private" function !!!
  2824. */
  2825. JQLite._data = function(node) {
  2826. //jQuery always returns an object on cache miss
  2827. return this.cache[node[this.expando]] || {};
  2828. };
  2829. function jqNextId() { return ++jqId; }
  2830. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2831. var MS_HACK_REGEXP = /^-ms-/;
  2832. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2833. var jqLiteMinErr = minErr('jqLite');
  2834. /**
  2835. * Converts kebab-case to camelCase.
  2836. * There is also a special case for the ms prefix starting with a lowercase letter.
  2837. * @param name Name to normalize
  2838. */
  2839. function cssKebabToCamel(name) {
  2840. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2841. }
  2842. function fnCamelCaseReplace(all, letter) {
  2843. return letter.toUpperCase();
  2844. }
  2845. /**
  2846. * Converts kebab-case to camelCase.
  2847. * @param name Name to normalize
  2848. */
  2849. function kebabToCamel(name) {
  2850. return name
  2851. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2852. }
  2853. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2854. var HTML_REGEXP = /<|&#?\w+;/;
  2855. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2856. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2857. // Table parts need to be wrapped with `<table>` or they're
  2858. // stripped to their contents when put in a div.
  2859. // XHTML parsers do not magically insert elements in the
  2860. // same way that tag soup parsers do, so we cannot shorten
  2861. // this by omitting <tbody> or other required elements.
  2862. var wrapMap = {
  2863. thead: ['table'],
  2864. col: ['colgroup', 'table'],
  2865. tr: ['tbody', 'table'],
  2866. td: ['tr', 'tbody', 'table']
  2867. };
  2868. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2869. wrapMap.th = wrapMap.td;
  2870. // Support: IE <10 only
  2871. // IE 9 requires an option wrapper & it needs to have the whole table structure
  2872. // set up in advance; assigning `"<td></td>"` to `tr.innerHTML` doesn't work, etc.
  2873. var wrapMapIE9 = {
  2874. option: [1, '<select multiple="multiple">', '</select>'],
  2875. _default: [0, '', '']
  2876. };
  2877. for (var key in wrapMap) {
  2878. var wrapMapValueClosing = wrapMap[key];
  2879. var wrapMapValue = wrapMapValueClosing.slice().reverse();
  2880. wrapMapIE9[key] = [wrapMapValue.length, '<' + wrapMapValue.join('><') + '>', '</' + wrapMapValueClosing.join('></') + '>'];
  2881. }
  2882. wrapMapIE9.optgroup = wrapMapIE9.option;
  2883. function jqLiteIsTextNode(html) {
  2884. return !HTML_REGEXP.test(html);
  2885. }
  2886. function jqLiteAcceptsData(node) {
  2887. // The window object can accept data but has no nodeType
  2888. // Otherwise we are only interested in elements (1) and documents (9)
  2889. var nodeType = node.nodeType;
  2890. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2891. }
  2892. function jqLiteHasData(node) {
  2893. for (var key in jqCache[node.ng339]) {
  2894. return true;
  2895. }
  2896. return false;
  2897. }
  2898. function jqLiteBuildFragment(html, context) {
  2899. var tmp, tag, wrap, finalHtml,
  2900. fragment = context.createDocumentFragment(),
  2901. nodes = [], i;
  2902. if (jqLiteIsTextNode(html)) {
  2903. // Convert non-html into a text node
  2904. nodes.push(context.createTextNode(html));
  2905. } else {
  2906. // Convert html into DOM nodes
  2907. tmp = fragment.appendChild(context.createElement('div'));
  2908. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2909. finalHtml = JQLite.legacyXHTMLReplacement ?
  2910. html.replace(XHTML_TAG_REGEXP, '<$1></$2>') :
  2911. html;
  2912. if (msie < 10) {
  2913. wrap = wrapMapIE9[tag] || wrapMapIE9._default;
  2914. tmp.innerHTML = wrap[1] + finalHtml + wrap[2];
  2915. // Descend through wrappers to the right content
  2916. i = wrap[0];
  2917. while (i--) {
  2918. tmp = tmp.firstChild;
  2919. }
  2920. } else {
  2921. wrap = wrapMap[tag] || [];
  2922. // Create wrappers & descend into them
  2923. i = wrap.length;
  2924. while (--i > -1) {
  2925. tmp.appendChild(window.document.createElement(wrap[i]));
  2926. tmp = tmp.firstChild;
  2927. }
  2928. tmp.innerHTML = finalHtml;
  2929. }
  2930. nodes = concat(nodes, tmp.childNodes);
  2931. tmp = fragment.firstChild;
  2932. tmp.textContent = '';
  2933. }
  2934. // Remove wrapper from fragment
  2935. fragment.textContent = '';
  2936. fragment.innerHTML = ''; // Clear inner HTML
  2937. forEach(nodes, function(node) {
  2938. fragment.appendChild(node);
  2939. });
  2940. return fragment;
  2941. }
  2942. function jqLiteParseHTML(html, context) {
  2943. context = context || window.document;
  2944. var parsed;
  2945. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2946. return [context.createElement(parsed[1])];
  2947. }
  2948. if ((parsed = jqLiteBuildFragment(html, context))) {
  2949. return parsed.childNodes;
  2950. }
  2951. return [];
  2952. }
  2953. function jqLiteWrapNode(node, wrapper) {
  2954. var parent = node.parentNode;
  2955. if (parent) {
  2956. parent.replaceChild(wrapper, node);
  2957. }
  2958. wrapper.appendChild(node);
  2959. }
  2960. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2961. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2962. // eslint-disable-next-line no-bitwise
  2963. return !!(this.compareDocumentPosition(arg) & 16);
  2964. };
  2965. /////////////////////////////////////////////
  2966. function JQLite(element) {
  2967. if (element instanceof JQLite) {
  2968. return element;
  2969. }
  2970. var argIsString;
  2971. if (isString(element)) {
  2972. element = trim(element);
  2973. argIsString = true;
  2974. }
  2975. if (!(this instanceof JQLite)) {
  2976. if (argIsString && element.charAt(0) !== '<') {
  2977. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2978. }
  2979. return new JQLite(element);
  2980. }
  2981. if (argIsString) {
  2982. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2983. } else if (isFunction(element)) {
  2984. jqLiteReady(element);
  2985. } else {
  2986. jqLiteAddNodes(this, element);
  2987. }
  2988. }
  2989. function jqLiteClone(element) {
  2990. return element.cloneNode(true);
  2991. }
  2992. function jqLiteDealoc(element, onlyDescendants) {
  2993. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2994. if (element.querySelectorAll) {
  2995. jqLite.cleanData(element.querySelectorAll('*'));
  2996. }
  2997. }
  2998. function isEmptyObject(obj) {
  2999. var name;
  3000. for (name in obj) {
  3001. return false;
  3002. }
  3003. return true;
  3004. }
  3005. function removeIfEmptyData(element) {
  3006. var expandoId = element.ng339;
  3007. var expandoStore = expandoId && jqCache[expandoId];
  3008. var events = expandoStore && expandoStore.events;
  3009. var data = expandoStore && expandoStore.data;
  3010. if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) {
  3011. delete jqCache[expandoId];
  3012. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  3013. }
  3014. }
  3015. function jqLiteOff(element, type, fn, unsupported) {
  3016. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  3017. var expandoStore = jqLiteExpandoStore(element);
  3018. var events = expandoStore && expandoStore.events;
  3019. var handle = expandoStore && expandoStore.handle;
  3020. if (!handle) return; //no listeners registered
  3021. if (!type) {
  3022. for (type in events) {
  3023. if (type !== '$destroy') {
  3024. element.removeEventListener(type, handle);
  3025. }
  3026. delete events[type];
  3027. }
  3028. } else {
  3029. var removeHandler = function(type) {
  3030. var listenerFns = events[type];
  3031. if (isDefined(fn)) {
  3032. arrayRemove(listenerFns || [], fn);
  3033. }
  3034. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  3035. element.removeEventListener(type, handle);
  3036. delete events[type];
  3037. }
  3038. };
  3039. forEach(type.split(' '), function(type) {
  3040. removeHandler(type);
  3041. if (MOUSE_EVENT_MAP[type]) {
  3042. removeHandler(MOUSE_EVENT_MAP[type]);
  3043. }
  3044. });
  3045. }
  3046. removeIfEmptyData(element);
  3047. }
  3048. function jqLiteRemoveData(element, name) {
  3049. var expandoId = element.ng339;
  3050. var expandoStore = expandoId && jqCache[expandoId];
  3051. if (expandoStore) {
  3052. if (name) {
  3053. delete expandoStore.data[name];
  3054. } else {
  3055. expandoStore.data = {};
  3056. }
  3057. removeIfEmptyData(element);
  3058. }
  3059. }
  3060. function jqLiteExpandoStore(element, createIfNecessary) {
  3061. var expandoId = element.ng339,
  3062. expandoStore = expandoId && jqCache[expandoId];
  3063. if (createIfNecessary && !expandoStore) {
  3064. element.ng339 = expandoId = jqNextId();
  3065. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  3066. }
  3067. return expandoStore;
  3068. }
  3069. function jqLiteData(element, key, value) {
  3070. if (jqLiteAcceptsData(element)) {
  3071. var prop;
  3072. var isSimpleSetter = isDefined(value);
  3073. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  3074. var massGetter = !key;
  3075. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  3076. var data = expandoStore && expandoStore.data;
  3077. if (isSimpleSetter) { // data('key', value)
  3078. data[kebabToCamel(key)] = value;
  3079. } else {
  3080. if (massGetter) { // data()
  3081. return data;
  3082. } else {
  3083. if (isSimpleGetter) { // data('key')
  3084. // don't force creation of expandoStore if it doesn't exist yet
  3085. return data && data[kebabToCamel(key)];
  3086. } else { // mass-setter: data({key1: val1, key2: val2})
  3087. for (prop in key) {
  3088. data[kebabToCamel(prop)] = key[prop];
  3089. }
  3090. }
  3091. }
  3092. }
  3093. }
  3094. }
  3095. function jqLiteHasClass(element, selector) {
  3096. if (!element.getAttribute) return false;
  3097. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  3098. indexOf(' ' + selector + ' ') > -1);
  3099. }
  3100. function jqLiteRemoveClass(element, cssClasses) {
  3101. if (cssClasses && element.setAttribute) {
  3102. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3103. .replace(/[\n\t]/g, ' ');
  3104. var newClasses = existingClasses;
  3105. forEach(cssClasses.split(' '), function(cssClass) {
  3106. cssClass = trim(cssClass);
  3107. newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
  3108. });
  3109. if (newClasses !== existingClasses) {
  3110. element.setAttribute('class', trim(newClasses));
  3111. }
  3112. }
  3113. }
  3114. function jqLiteAddClass(element, cssClasses) {
  3115. if (cssClasses && element.setAttribute) {
  3116. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3117. .replace(/[\n\t]/g, ' ');
  3118. var newClasses = existingClasses;
  3119. forEach(cssClasses.split(' '), function(cssClass) {
  3120. cssClass = trim(cssClass);
  3121. if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
  3122. newClasses += cssClass + ' ';
  3123. }
  3124. });
  3125. if (newClasses !== existingClasses) {
  3126. element.setAttribute('class', trim(newClasses));
  3127. }
  3128. }
  3129. }
  3130. function jqLiteAddNodes(root, elements) {
  3131. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  3132. if (elements) {
  3133. // if a Node (the most common case)
  3134. if (elements.nodeType) {
  3135. root[root.length++] = elements;
  3136. } else {
  3137. var length = elements.length;
  3138. // if an Array or NodeList and not a Window
  3139. if (typeof length === 'number' && elements.window !== elements) {
  3140. if (length) {
  3141. for (var i = 0; i < length; i++) {
  3142. root[root.length++] = elements[i];
  3143. }
  3144. }
  3145. } else {
  3146. root[root.length++] = elements;
  3147. }
  3148. }
  3149. }
  3150. }
  3151. function jqLiteController(element, name) {
  3152. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3153. }
  3154. function jqLiteInheritedData(element, name, value) {
  3155. // if element is the document object work with the html element instead
  3156. // this makes $(document).scope() possible
  3157. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3158. element = element.documentElement;
  3159. }
  3160. var names = isArray(name) ? name : [name];
  3161. while (element) {
  3162. for (var i = 0, ii = names.length; i < ii; i++) {
  3163. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3164. }
  3165. // If dealing with a document fragment node with a host element, and no parent, use the host
  3166. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3167. // to lookup parent controllers.
  3168. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3169. }
  3170. }
  3171. function jqLiteEmpty(element) {
  3172. jqLiteDealoc(element, true);
  3173. while (element.firstChild) {
  3174. element.removeChild(element.firstChild);
  3175. }
  3176. }
  3177. function jqLiteRemove(element, keepData) {
  3178. if (!keepData) jqLiteDealoc(element);
  3179. var parent = element.parentNode;
  3180. if (parent) parent.removeChild(element);
  3181. }
  3182. function jqLiteDocumentLoaded(action, win) {
  3183. win = win || window;
  3184. if (win.document.readyState === 'complete') {
  3185. // Force the action to be run async for consistent behavior
  3186. // from the action's point of view
  3187. // i.e. it will definitely not be in a $apply
  3188. win.setTimeout(action);
  3189. } else {
  3190. // No need to unbind this handler as load is only ever called once
  3191. jqLite(win).on('load', action);
  3192. }
  3193. }
  3194. function jqLiteReady(fn) {
  3195. function trigger() {
  3196. window.document.removeEventListener('DOMContentLoaded', trigger);
  3197. window.removeEventListener('load', trigger);
  3198. fn();
  3199. }
  3200. // check if document is already loaded
  3201. if (window.document.readyState === 'complete') {
  3202. window.setTimeout(fn);
  3203. } else {
  3204. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3205. // Works for modern browsers and IE9
  3206. window.document.addEventListener('DOMContentLoaded', trigger);
  3207. // Fallback to window.onload for others
  3208. window.addEventListener('load', trigger);
  3209. }
  3210. }
  3211. //////////////////////////////////////////
  3212. // Functions which are declared directly.
  3213. //////////////////////////////////////////
  3214. var JQLitePrototype = JQLite.prototype = {
  3215. ready: jqLiteReady,
  3216. toString: function() {
  3217. var value = [];
  3218. forEach(this, function(e) { value.push('' + e);});
  3219. return '[' + value.join(', ') + ']';
  3220. },
  3221. eq: function(index) {
  3222. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3223. },
  3224. length: 0,
  3225. push: push,
  3226. sort: [].sort,
  3227. splice: [].splice
  3228. };
  3229. //////////////////////////////////////////
  3230. // Functions iterating getter/setters.
  3231. // these functions return self on setter and
  3232. // value on get.
  3233. //////////////////////////////////////////
  3234. var BOOLEAN_ATTR = {};
  3235. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3236. BOOLEAN_ATTR[lowercase(value)] = value;
  3237. });
  3238. var BOOLEAN_ELEMENTS = {};
  3239. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3240. BOOLEAN_ELEMENTS[value] = true;
  3241. });
  3242. var ALIASED_ATTR = {
  3243. 'ngMinlength': 'minlength',
  3244. 'ngMaxlength': 'maxlength',
  3245. 'ngMin': 'min',
  3246. 'ngMax': 'max',
  3247. 'ngPattern': 'pattern',
  3248. 'ngStep': 'step'
  3249. };
  3250. function getBooleanAttrName(element, name) {
  3251. // check dom last since we will most likely fail on name
  3252. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3253. // booleanAttr is here twice to minimize DOM access
  3254. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3255. }
  3256. function getAliasedAttrName(name) {
  3257. return ALIASED_ATTR[name];
  3258. }
  3259. forEach({
  3260. data: jqLiteData,
  3261. removeData: jqLiteRemoveData,
  3262. hasData: jqLiteHasData,
  3263. cleanData: function jqLiteCleanData(nodes) {
  3264. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3265. jqLiteRemoveData(nodes[i]);
  3266. jqLiteOff(nodes[i]);
  3267. }
  3268. }
  3269. }, function(fn, name) {
  3270. JQLite[name] = fn;
  3271. });
  3272. forEach({
  3273. data: jqLiteData,
  3274. inheritedData: jqLiteInheritedData,
  3275. scope: function(element) {
  3276. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3277. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3278. },
  3279. isolateScope: function(element) {
  3280. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3281. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3282. },
  3283. controller: jqLiteController,
  3284. injector: function(element) {
  3285. return jqLiteInheritedData(element, '$injector');
  3286. },
  3287. removeAttr: function(element, name) {
  3288. element.removeAttribute(name);
  3289. },
  3290. hasClass: jqLiteHasClass,
  3291. css: function(element, name, value) {
  3292. name = cssKebabToCamel(name);
  3293. if (isDefined(value)) {
  3294. element.style[name] = value;
  3295. } else {
  3296. return element.style[name];
  3297. }
  3298. },
  3299. attr: function(element, name, value) {
  3300. var ret;
  3301. var nodeType = element.nodeType;
  3302. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3303. !element.getAttribute) {
  3304. return;
  3305. }
  3306. var lowercasedName = lowercase(name);
  3307. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3308. if (isDefined(value)) {
  3309. // setter
  3310. if (value === null || (value === false && isBooleanAttr)) {
  3311. element.removeAttribute(name);
  3312. } else {
  3313. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3314. }
  3315. } else {
  3316. // getter
  3317. ret = element.getAttribute(name);
  3318. if (isBooleanAttr && ret !== null) {
  3319. ret = lowercasedName;
  3320. }
  3321. // Normalize non-existing attributes to undefined (as jQuery).
  3322. return ret === null ? undefined : ret;
  3323. }
  3324. },
  3325. prop: function(element, name, value) {
  3326. if (isDefined(value)) {
  3327. element[name] = value;
  3328. } else {
  3329. return element[name];
  3330. }
  3331. },
  3332. text: (function() {
  3333. getText.$dv = '';
  3334. return getText;
  3335. function getText(element, value) {
  3336. if (isUndefined(value)) {
  3337. var nodeType = element.nodeType;
  3338. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3339. }
  3340. element.textContent = value;
  3341. }
  3342. })(),
  3343. val: function(element, value) {
  3344. if (isUndefined(value)) {
  3345. if (element.multiple && nodeName_(element) === 'select') {
  3346. var result = [];
  3347. forEach(element.options, function(option) {
  3348. if (option.selected) {
  3349. result.push(option.value || option.text);
  3350. }
  3351. });
  3352. return result;
  3353. }
  3354. return element.value;
  3355. }
  3356. element.value = value;
  3357. },
  3358. html: function(element, value) {
  3359. if (isUndefined(value)) {
  3360. return element.innerHTML;
  3361. }
  3362. jqLiteDealoc(element, true);
  3363. element.innerHTML = value;
  3364. },
  3365. empty: jqLiteEmpty
  3366. }, function(fn, name) {
  3367. /**
  3368. * Properties: writes return selection, reads return first value
  3369. */
  3370. JQLite.prototype[name] = function(arg1, arg2) {
  3371. var i, key;
  3372. var nodeCount = this.length;
  3373. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3374. // in a way that survives minification.
  3375. // jqLiteEmpty takes no arguments but is a setter.
  3376. if (fn !== jqLiteEmpty &&
  3377. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3378. if (isObject(arg1)) {
  3379. // we are a write, but the object properties are the key/values
  3380. for (i = 0; i < nodeCount; i++) {
  3381. if (fn === jqLiteData) {
  3382. // data() takes the whole object in jQuery
  3383. fn(this[i], arg1);
  3384. } else {
  3385. for (key in arg1) {
  3386. fn(this[i], key, arg1[key]);
  3387. }
  3388. }
  3389. }
  3390. // return self for chaining
  3391. return this;
  3392. } else {
  3393. // we are a read, so read the first child.
  3394. // TODO: do we still need this?
  3395. var value = fn.$dv;
  3396. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3397. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3398. for (var j = 0; j < jj; j++) {
  3399. var nodeValue = fn(this[j], arg1, arg2);
  3400. value = value ? value + nodeValue : nodeValue;
  3401. }
  3402. return value;
  3403. }
  3404. } else {
  3405. // we are a write, so apply to all children
  3406. for (i = 0; i < nodeCount; i++) {
  3407. fn(this[i], arg1, arg2);
  3408. }
  3409. // return self for chaining
  3410. return this;
  3411. }
  3412. };
  3413. });
  3414. function createEventHandler(element, events) {
  3415. var eventHandler = function(event, type) {
  3416. // jQuery specific api
  3417. event.isDefaultPrevented = function() {
  3418. return event.defaultPrevented;
  3419. };
  3420. var eventFns = events[type || event.type];
  3421. var eventFnsLength = eventFns ? eventFns.length : 0;
  3422. if (!eventFnsLength) return;
  3423. if (isUndefined(event.immediatePropagationStopped)) {
  3424. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3425. event.stopImmediatePropagation = function() {
  3426. event.immediatePropagationStopped = true;
  3427. if (event.stopPropagation) {
  3428. event.stopPropagation();
  3429. }
  3430. if (originalStopImmediatePropagation) {
  3431. originalStopImmediatePropagation.call(event);
  3432. }
  3433. };
  3434. }
  3435. event.isImmediatePropagationStopped = function() {
  3436. return event.immediatePropagationStopped === true;
  3437. };
  3438. // Some events have special handlers that wrap the real handler
  3439. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3440. // Copy event handlers in case event handlers array is modified during execution.
  3441. if ((eventFnsLength > 1)) {
  3442. eventFns = shallowCopy(eventFns);
  3443. }
  3444. for (var i = 0; i < eventFnsLength; i++) {
  3445. if (!event.isImmediatePropagationStopped()) {
  3446. handlerWrapper(element, event, eventFns[i]);
  3447. }
  3448. }
  3449. };
  3450. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3451. // events on `element`
  3452. eventHandler.elem = element;
  3453. return eventHandler;
  3454. }
  3455. function defaultHandlerWrapper(element, event, handler) {
  3456. handler.call(element, event);
  3457. }
  3458. function specialMouseHandlerWrapper(target, event, handler) {
  3459. // Refer to jQuery's implementation of mouseenter & mouseleave
  3460. // Read about mouseenter and mouseleave:
  3461. // http://www.quirksmode.org/js/events_mouse.html#link8
  3462. var related = event.relatedTarget;
  3463. // For mousenter/leave call the handler if related is outside the target.
  3464. // NB: No relatedTarget if the mouse left/entered the browser window
  3465. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3466. handler.call(target, event);
  3467. }
  3468. }
  3469. //////////////////////////////////////////
  3470. // Functions iterating traversal.
  3471. // These functions chain results into a single
  3472. // selector.
  3473. //////////////////////////////////////////
  3474. forEach({
  3475. removeData: jqLiteRemoveData,
  3476. on: function jqLiteOn(element, type, fn, unsupported) {
  3477. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3478. // Do not add event handlers to non-elements because they will not be cleaned up.
  3479. if (!jqLiteAcceptsData(element)) {
  3480. return;
  3481. }
  3482. var expandoStore = jqLiteExpandoStore(element, true);
  3483. var events = expandoStore.events;
  3484. var handle = expandoStore.handle;
  3485. if (!handle) {
  3486. handle = expandoStore.handle = createEventHandler(element, events);
  3487. }
  3488. // http://jsperf.com/string-indexof-vs-split
  3489. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3490. var i = types.length;
  3491. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3492. var eventFns = events[type];
  3493. if (!eventFns) {
  3494. eventFns = events[type] = [];
  3495. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3496. if (type !== '$destroy' && !noEventListener) {
  3497. element.addEventListener(type, handle);
  3498. }
  3499. }
  3500. eventFns.push(fn);
  3501. };
  3502. while (i--) {
  3503. type = types[i];
  3504. if (MOUSE_EVENT_MAP[type]) {
  3505. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3506. addHandler(type, undefined, true);
  3507. } else {
  3508. addHandler(type);
  3509. }
  3510. }
  3511. },
  3512. off: jqLiteOff,
  3513. one: function(element, type, fn) {
  3514. element = jqLite(element);
  3515. //add the listener twice so that when it is called
  3516. //you can remove the original function and still be
  3517. //able to call element.off(ev, fn) normally
  3518. element.on(type, function onFn() {
  3519. element.off(type, fn);
  3520. element.off(type, onFn);
  3521. });
  3522. element.on(type, fn);
  3523. },
  3524. replaceWith: function(element, replaceNode) {
  3525. var index, parent = element.parentNode;
  3526. jqLiteDealoc(element);
  3527. forEach(new JQLite(replaceNode), function(node) {
  3528. if (index) {
  3529. parent.insertBefore(node, index.nextSibling);
  3530. } else {
  3531. parent.replaceChild(node, element);
  3532. }
  3533. index = node;
  3534. });
  3535. },
  3536. children: function(element) {
  3537. var children = [];
  3538. forEach(element.childNodes, function(element) {
  3539. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3540. children.push(element);
  3541. }
  3542. });
  3543. return children;
  3544. },
  3545. contents: function(element) {
  3546. return element.contentDocument || element.childNodes || [];
  3547. },
  3548. append: function(element, node) {
  3549. var nodeType = element.nodeType;
  3550. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3551. node = new JQLite(node);
  3552. for (var i = 0, ii = node.length; i < ii; i++) {
  3553. var child = node[i];
  3554. element.appendChild(child);
  3555. }
  3556. },
  3557. prepend: function(element, node) {
  3558. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3559. var index = element.firstChild;
  3560. forEach(new JQLite(node), function(child) {
  3561. element.insertBefore(child, index);
  3562. });
  3563. }
  3564. },
  3565. wrap: function(element, wrapNode) {
  3566. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3567. },
  3568. remove: jqLiteRemove,
  3569. detach: function(element) {
  3570. jqLiteRemove(element, true);
  3571. },
  3572. after: function(element, newElement) {
  3573. var index = element, parent = element.parentNode;
  3574. if (parent) {
  3575. newElement = new JQLite(newElement);
  3576. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3577. var node = newElement[i];
  3578. parent.insertBefore(node, index.nextSibling);
  3579. index = node;
  3580. }
  3581. }
  3582. },
  3583. addClass: jqLiteAddClass,
  3584. removeClass: jqLiteRemoveClass,
  3585. toggleClass: function(element, selector, condition) {
  3586. if (selector) {
  3587. forEach(selector.split(' '), function(className) {
  3588. var classCondition = condition;
  3589. if (isUndefined(classCondition)) {
  3590. classCondition = !jqLiteHasClass(element, className);
  3591. }
  3592. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3593. });
  3594. }
  3595. },
  3596. parent: function(element) {
  3597. var parent = element.parentNode;
  3598. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3599. },
  3600. next: function(element) {
  3601. return element.nextElementSibling;
  3602. },
  3603. find: function(element, selector) {
  3604. if (element.getElementsByTagName) {
  3605. return element.getElementsByTagName(selector);
  3606. } else {
  3607. return [];
  3608. }
  3609. },
  3610. clone: jqLiteClone,
  3611. triggerHandler: function(element, event, extraParameters) {
  3612. var dummyEvent, eventFnsCopy, handlerArgs;
  3613. var eventName = event.type || event;
  3614. var expandoStore = jqLiteExpandoStore(element);
  3615. var events = expandoStore && expandoStore.events;
  3616. var eventFns = events && events[eventName];
  3617. if (eventFns) {
  3618. // Create a dummy event to pass to the handlers
  3619. dummyEvent = {
  3620. preventDefault: function() { this.defaultPrevented = true; },
  3621. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3622. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3623. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3624. stopPropagation: noop,
  3625. type: eventName,
  3626. target: element
  3627. };
  3628. // If a custom event was provided then extend our dummy event with it
  3629. if (event.type) {
  3630. dummyEvent = extend(dummyEvent, event);
  3631. }
  3632. // Copy event handlers in case event handlers array is modified during execution.
  3633. eventFnsCopy = shallowCopy(eventFns);
  3634. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3635. forEach(eventFnsCopy, function(fn) {
  3636. if (!dummyEvent.isImmediatePropagationStopped()) {
  3637. fn.apply(element, handlerArgs);
  3638. }
  3639. });
  3640. }
  3641. }
  3642. }, function(fn, name) {
  3643. /**
  3644. * chaining functions
  3645. */
  3646. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3647. var value;
  3648. for (var i = 0, ii = this.length; i < ii; i++) {
  3649. if (isUndefined(value)) {
  3650. value = fn(this[i], arg1, arg2, arg3);
  3651. if (isDefined(value)) {
  3652. // any function which returns a value needs to be wrapped
  3653. value = jqLite(value);
  3654. }
  3655. } else {
  3656. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3657. }
  3658. }
  3659. return isDefined(value) ? value : this;
  3660. };
  3661. });
  3662. // bind legacy bind/unbind to on/off
  3663. JQLite.prototype.bind = JQLite.prototype.on;
  3664. JQLite.prototype.unbind = JQLite.prototype.off;
  3665. // Provider for private $$jqLite service
  3666. /** @this */
  3667. function $$jqLiteProvider() {
  3668. this.$get = function $$jqLite() {
  3669. return extend(JQLite, {
  3670. hasClass: function(node, classes) {
  3671. if (node.attr) node = node[0];
  3672. return jqLiteHasClass(node, classes);
  3673. },
  3674. addClass: function(node, classes) {
  3675. if (node.attr) node = node[0];
  3676. return jqLiteAddClass(node, classes);
  3677. },
  3678. removeClass: function(node, classes) {
  3679. if (node.attr) node = node[0];
  3680. return jqLiteRemoveClass(node, classes);
  3681. }
  3682. });
  3683. };
  3684. }
  3685. /**
  3686. * Computes a hash of an 'obj'.
  3687. * Hash of a:
  3688. * string is string
  3689. * number is number as string
  3690. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3691. * that is also assigned to the $$hashKey property of the object.
  3692. *
  3693. * @param obj
  3694. * @returns {string} hash string such that the same input will have the same hash string.
  3695. * The resulting string key is in 'type:hashKey' format.
  3696. */
  3697. function hashKey(obj, nextUidFn) {
  3698. var key = obj && obj.$$hashKey;
  3699. if (key) {
  3700. if (typeof key === 'function') {
  3701. key = obj.$$hashKey();
  3702. }
  3703. return key;
  3704. }
  3705. var objType = typeof obj;
  3706. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3707. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3708. } else {
  3709. key = objType + ':' + obj;
  3710. }
  3711. return key;
  3712. }
  3713. // A minimal ES2015 Map implementation.
  3714. // Should be bug/feature equivalent to the native implementations of supported browsers
  3715. // (for the features required in Angular).
  3716. // See https://kangax.github.io/compat-table/es6/#test-Map
  3717. var nanKey = Object.create(null);
  3718. function NgMapShim() {
  3719. this._keys = [];
  3720. this._values = [];
  3721. this._lastKey = NaN;
  3722. this._lastIndex = -1;
  3723. }
  3724. NgMapShim.prototype = {
  3725. _idx: function(key) {
  3726. if (key !== this._lastKey) {
  3727. this._lastKey = key;
  3728. this._lastIndex = this._keys.indexOf(key);
  3729. }
  3730. return this._lastIndex;
  3731. },
  3732. _transformKey: function(key) {
  3733. return isNumberNaN(key) ? nanKey : key;
  3734. },
  3735. get: function(key) {
  3736. key = this._transformKey(key);
  3737. var idx = this._idx(key);
  3738. if (idx !== -1) {
  3739. return this._values[idx];
  3740. }
  3741. },
  3742. has: function(key) {
  3743. key = this._transformKey(key);
  3744. var idx = this._idx(key);
  3745. return idx !== -1;
  3746. },
  3747. set: function(key, value) {
  3748. key = this._transformKey(key);
  3749. var idx = this._idx(key);
  3750. if (idx === -1) {
  3751. idx = this._lastIndex = this._keys.length;
  3752. }
  3753. this._keys[idx] = key;
  3754. this._values[idx] = value;
  3755. // Support: IE11
  3756. // Do not `return this` to simulate the partial IE11 implementation
  3757. },
  3758. delete: function(key) {
  3759. key = this._transformKey(key);
  3760. var idx = this._idx(key);
  3761. if (idx === -1) {
  3762. return false;
  3763. }
  3764. this._keys.splice(idx, 1);
  3765. this._values.splice(idx, 1);
  3766. this._lastKey = NaN;
  3767. this._lastIndex = -1;
  3768. return true;
  3769. }
  3770. };
  3771. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3772. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3773. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3774. var NgMap = NgMapShim;
  3775. var $$MapProvider = [/** @this */function() {
  3776. this.$get = [function() {
  3777. return NgMap;
  3778. }];
  3779. }];
  3780. /**
  3781. * @ngdoc function
  3782. * @module ng
  3783. * @name angular.injector
  3784. * @kind function
  3785. *
  3786. * @description
  3787. * Creates an injector object that can be used for retrieving services as well as for
  3788. * dependency injection (see {@link guide/di dependency injection}).
  3789. *
  3790. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3791. * {@link angular.module}. The `ng` module must be explicitly added.
  3792. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3793. * disallows argument name annotation inference.
  3794. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3795. *
  3796. * @example
  3797. * Typical usage
  3798. * ```js
  3799. * // create an injector
  3800. * var $injector = angular.injector(['ng']);
  3801. *
  3802. * // use the injector to kick off your application
  3803. * // use the type inference to auto inject arguments, or use implicit injection
  3804. * $injector.invoke(function($rootScope, $compile, $document) {
  3805. * $compile($document)($rootScope);
  3806. * $rootScope.$digest();
  3807. * });
  3808. * ```
  3809. *
  3810. * Sometimes you want to get access to the injector of a currently running AngularJS app
  3811. * from outside AngularJS. Perhaps, you want to inject and compile some markup after the
  3812. * application has been bootstrapped. You can do this using the extra `injector()` added
  3813. * to JQuery/jqLite elements. See {@link angular.element}.
  3814. *
  3815. * *This is fairly rare but could be the case if a third party library is injecting the
  3816. * markup.*
  3817. *
  3818. * In the following example a new block of HTML containing a `ng-controller`
  3819. * directive is added to the end of the document body by JQuery. We then compile and link
  3820. * it into the current AngularJS scope.
  3821. *
  3822. * ```js
  3823. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3824. * $(document.body).append($div);
  3825. *
  3826. * angular.element(document).injector().invoke(function($compile) {
  3827. * var scope = angular.element($div).scope();
  3828. * $compile($div)(scope);
  3829. * });
  3830. * ```
  3831. */
  3832. /**
  3833. * @ngdoc module
  3834. * @name auto
  3835. * @installation
  3836. * @description
  3837. *
  3838. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3839. */
  3840. var ARROW_ARG = /^([^(]+?)=>/;
  3841. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3842. var FN_ARG_SPLIT = /,/;
  3843. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3844. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3845. var $injectorMinErr = minErr('$injector');
  3846. function stringifyFn(fn) {
  3847. return Function.prototype.toString.call(fn);
  3848. }
  3849. function extractArgs(fn) {
  3850. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3851. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3852. return args;
  3853. }
  3854. function anonFn(fn) {
  3855. // For anonymous functions, showing at the very least the function signature can help in
  3856. // debugging.
  3857. var args = extractArgs(fn);
  3858. if (args) {
  3859. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3860. }
  3861. return 'fn';
  3862. }
  3863. function annotate(fn, strictDi, name) {
  3864. var $inject,
  3865. argDecl,
  3866. last;
  3867. if (typeof fn === 'function') {
  3868. if (!($inject = fn.$inject)) {
  3869. $inject = [];
  3870. if (fn.length) {
  3871. if (strictDi) {
  3872. if (!isString(name) || !name) {
  3873. name = fn.name || anonFn(fn);
  3874. }
  3875. throw $injectorMinErr('strictdi',
  3876. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3877. }
  3878. argDecl = extractArgs(fn);
  3879. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3880. arg.replace(FN_ARG, function(all, underscore, name) {
  3881. $inject.push(name);
  3882. });
  3883. });
  3884. }
  3885. fn.$inject = $inject;
  3886. }
  3887. } else if (isArray(fn)) {
  3888. last = fn.length - 1;
  3889. assertArgFn(fn[last], 'fn');
  3890. $inject = fn.slice(0, last);
  3891. } else {
  3892. assertArgFn(fn, 'fn', true);
  3893. }
  3894. return $inject;
  3895. }
  3896. ///////////////////////////////////////
  3897. /**
  3898. * @ngdoc service
  3899. * @name $injector
  3900. *
  3901. * @description
  3902. *
  3903. * `$injector` is used to retrieve object instances as defined by
  3904. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3905. * and load modules.
  3906. *
  3907. * The following always holds true:
  3908. *
  3909. * ```js
  3910. * var $injector = angular.injector();
  3911. * expect($injector.get('$injector')).toBe($injector);
  3912. * expect($injector.invoke(function($injector) {
  3913. * return $injector;
  3914. * })).toBe($injector);
  3915. * ```
  3916. *
  3917. * ## Injection Function Annotation
  3918. *
  3919. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3920. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3921. *
  3922. * ```js
  3923. * // inferred (only works if code not minified/obfuscated)
  3924. * $injector.invoke(function(serviceA){});
  3925. *
  3926. * // annotated
  3927. * function explicit(serviceA) {};
  3928. * explicit.$inject = ['serviceA'];
  3929. * $injector.invoke(explicit);
  3930. *
  3931. * // inline
  3932. * $injector.invoke(['serviceA', function(serviceA){}]);
  3933. * ```
  3934. *
  3935. * ### Inference
  3936. *
  3937. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3938. * can then be parsed and the function arguments can be extracted. This method of discovering
  3939. * annotations is disallowed when the injector is in strict mode.
  3940. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3941. * argument names.
  3942. *
  3943. * ### `$inject` Annotation
  3944. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3945. *
  3946. * ### Inline
  3947. * As an array of injection names, where the last item in the array is the function to call.
  3948. */
  3949. /**
  3950. * @ngdoc property
  3951. * @name $injector#modules
  3952. * @type {Object}
  3953. * @description
  3954. * A hash containing all the modules that have been loaded into the
  3955. * $injector.
  3956. *
  3957. * You can use this property to find out information about a module via the
  3958. * {@link angular.Module#info `myModule.info(...)`} method.
  3959. *
  3960. * For example:
  3961. *
  3962. * ```
  3963. * var info = $injector.modules['ngAnimate'].info();
  3964. * ```
  3965. *
  3966. * **Do not use this property to attempt to modify the modules after the application
  3967. * has been bootstrapped.**
  3968. */
  3969. /**
  3970. * @ngdoc method
  3971. * @name $injector#get
  3972. *
  3973. * @description
  3974. * Return an instance of the service.
  3975. *
  3976. * @param {string} name The name of the instance to retrieve.
  3977. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3978. * @return {*} The instance.
  3979. */
  3980. /**
  3981. * @ngdoc method
  3982. * @name $injector#invoke
  3983. *
  3984. * @description
  3985. * Invoke the method and supply the method arguments from the `$injector`.
  3986. *
  3987. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3988. * injected according to the {@link guide/di $inject Annotation} rules.
  3989. * @param {Object=} self The `this` for the invoked method.
  3990. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3991. * object first, before the `$injector` is consulted.
  3992. * @returns {*} the value returned by the invoked `fn` function.
  3993. */
  3994. /**
  3995. * @ngdoc method
  3996. * @name $injector#has
  3997. *
  3998. * @description
  3999. * Allows the user to query if the particular service exists.
  4000. *
  4001. * @param {string} name Name of the service to query.
  4002. * @returns {boolean} `true` if injector has given service.
  4003. */
  4004. /**
  4005. * @ngdoc method
  4006. * @name $injector#instantiate
  4007. * @description
  4008. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  4009. * operator, and supplies all of the arguments to the constructor function as specified by the
  4010. * constructor annotation.
  4011. *
  4012. * @param {Function} Type Annotated constructor function.
  4013. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  4014. * object first, before the `$injector` is consulted.
  4015. * @returns {Object} new instance of `Type`.
  4016. */
  4017. /**
  4018. * @ngdoc method
  4019. * @name $injector#annotate
  4020. *
  4021. * @description
  4022. * Returns an array of service names which the function is requesting for injection. This API is
  4023. * used by the injector to determine which services need to be injected into the function when the
  4024. * function is invoked. There are three ways in which the function can be annotated with the needed
  4025. * dependencies.
  4026. *
  4027. * #### Argument names
  4028. *
  4029. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  4030. * by converting the function into a string using `toString()` method and extracting the argument
  4031. * names.
  4032. * ```js
  4033. * // Given
  4034. * function MyController($scope, $route) {
  4035. * // ...
  4036. * }
  4037. *
  4038. * // Then
  4039. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  4040. * ```
  4041. *
  4042. * You can disallow this method by using strict injection mode.
  4043. *
  4044. * This method does not work with code minification / obfuscation. For this reason the following
  4045. * annotation strategies are supported.
  4046. *
  4047. * #### The `$inject` property
  4048. *
  4049. * If a function has an `$inject` property and its value is an array of strings, then the strings
  4050. * represent names of services to be injected into the function.
  4051. * ```js
  4052. * // Given
  4053. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  4054. * // ...
  4055. * }
  4056. * // Define function dependencies
  4057. * MyController['$inject'] = ['$scope', '$route'];
  4058. *
  4059. * // Then
  4060. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  4061. * ```
  4062. *
  4063. * #### The array notation
  4064. *
  4065. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  4066. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  4067. * a way that survives minification is a better choice:
  4068. *
  4069. * ```js
  4070. * // We wish to write this (not minification / obfuscation safe)
  4071. * injector.invoke(function($compile, $rootScope) {
  4072. * // ...
  4073. * });
  4074. *
  4075. * // We are forced to write break inlining
  4076. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  4077. * // ...
  4078. * };
  4079. * tmpFn.$inject = ['$compile', '$rootScope'];
  4080. * injector.invoke(tmpFn);
  4081. *
  4082. * // To better support inline function the inline annotation is supported
  4083. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  4084. * // ...
  4085. * }]);
  4086. *
  4087. * // Therefore
  4088. * expect(injector.annotate(
  4089. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  4090. * ).toEqual(['$compile', '$rootScope']);
  4091. * ```
  4092. *
  4093. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  4094. * be retrieved as described above.
  4095. *
  4096. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  4097. *
  4098. * @returns {Array.<string>} The names of the services which the function requires.
  4099. */
  4100. /**
  4101. * @ngdoc method
  4102. * @name $injector#loadNewModules
  4103. *
  4104. * @description
  4105. *
  4106. * **This is a dangerous API, which you use at your own risk!**
  4107. *
  4108. * Add the specified modules to the current injector.
  4109. *
  4110. * This method will add each of the injectables to the injector and execute all of the config and run
  4111. * blocks for each module passed to the method.
  4112. *
  4113. * If a module has already been loaded into the injector then it will not be loaded again.
  4114. *
  4115. * * The application developer is responsible for loading the code containing the modules; and for
  4116. * ensuring that lazy scripts are not downloaded and executed more often that desired.
  4117. * * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
  4118. * * Modules cannot be unloaded.
  4119. *
  4120. * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
  4121. * into the injector, which may indicate whether the script has been executed already.
  4122. *
  4123. * @example
  4124. * Here is an example of loading a bundle of modules, with a utility method called `getScript`:
  4125. *
  4126. * ```javascript
  4127. * app.factory('loadModule', function($injector) {
  4128. * return function loadModule(moduleName, bundleUrl) {
  4129. * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
  4130. * };
  4131. * })
  4132. * ```
  4133. *
  4134. * @param {Array<String|Function|Array>=} mods an array of modules to load into the application.
  4135. * Each item in the array should be the name of a predefined module or a (DI annotated)
  4136. * function that will be invoked by the injector as a `config` block.
  4137. * See: {@link angular.module modules}
  4138. */
  4139. /**
  4140. * @ngdoc service
  4141. * @name $provide
  4142. *
  4143. * @description
  4144. *
  4145. * The {@link auto.$provide $provide} service has a number of methods for registering components
  4146. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  4147. * {@link angular.Module}.
  4148. *
  4149. * An AngularJS **service** is a singleton object created by a **service factory**. These **service
  4150. * factories** are functions which, in turn, are created by a **service provider**.
  4151. * The **service providers** are constructor functions. When instantiated they must contain a
  4152. * property called `$get`, which holds the **service factory** function.
  4153. *
  4154. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  4155. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  4156. * function to get the instance of the **service**.
  4157. *
  4158. * Often services have no configuration options and there is no need to add methods to the service
  4159. * provider. The provider will be no more than a constructor function with a `$get` property. For
  4160. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  4161. * services without specifying a provider.
  4162. *
  4163. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  4164. * {@link auto.$injector $injector}
  4165. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  4166. * providers and services.
  4167. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  4168. * services, not providers.
  4169. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  4170. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  4171. * given factory function.
  4172. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  4173. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  4174. * a new object using the given constructor function.
  4175. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  4176. * will be able to modify or replace the implementation of another service.
  4177. *
  4178. * See the individual methods for more information and examples.
  4179. */
  4180. /**
  4181. * @ngdoc method
  4182. * @name $provide#provider
  4183. * @description
  4184. *
  4185. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4186. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4187. * service.
  4188. *
  4189. * Service provider names start with the name of the service they provide followed by `Provider`.
  4190. * For example, the {@link ng.$log $log} service has a provider called
  4191. * {@link ng.$logProvider $logProvider}.
  4192. *
  4193. * Service provider objects can have additional methods which allow configuration of the provider
  4194. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4195. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4196. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4197. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4198. * console or not.
  4199. *
  4200. * It is possible to inject other providers into the provider function,
  4201. * but the injected provider must have been defined before the one that requires it.
  4202. *
  4203. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4204. 'Provider'` key.
  4205. * @param {(Object|function())} provider If the provider is:
  4206. *
  4207. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4208. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4209. * - `Constructor`: a new instance of the provider will be created using
  4210. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4211. *
  4212. * @returns {Object} registered provider instance
  4213. * @example
  4214. *
  4215. * The following example shows how to create a simple event tracking service and register it using
  4216. * {@link auto.$provide#provider $provide.provider()}.
  4217. *
  4218. * ```js
  4219. * // Define the eventTracker provider
  4220. * function EventTrackerProvider() {
  4221. * var trackingUrl = '/track';
  4222. *
  4223. * // A provider method for configuring where the tracked events should been saved
  4224. * this.setTrackingUrl = function(url) {
  4225. * trackingUrl = url;
  4226. * };
  4227. *
  4228. * // The service factory function
  4229. * this.$get = ['$http', function($http) {
  4230. * var trackedEvents = {};
  4231. * return {
  4232. * // Call this to track an event
  4233. * event: function(event) {
  4234. * var count = trackedEvents[event] || 0;
  4235. * count += 1;
  4236. * trackedEvents[event] = count;
  4237. * return count;
  4238. * },
  4239. * // Call this to save the tracked events to the trackingUrl
  4240. * save: function() {
  4241. * $http.post(trackingUrl, trackedEvents);
  4242. * }
  4243. * };
  4244. * }];
  4245. * }
  4246. *
  4247. * describe('eventTracker', function() {
  4248. * var postSpy;
  4249. *
  4250. * beforeEach(module(function($provide) {
  4251. * // Register the eventTracker provider
  4252. * $provide.provider('eventTracker', EventTrackerProvider);
  4253. * }));
  4254. *
  4255. * beforeEach(module(function(eventTrackerProvider) {
  4256. * // Configure eventTracker provider
  4257. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4258. * }));
  4259. *
  4260. * it('tracks events', inject(function(eventTracker) {
  4261. * expect(eventTracker.event('login')).toEqual(1);
  4262. * expect(eventTracker.event('login')).toEqual(2);
  4263. * }));
  4264. *
  4265. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4266. * postSpy = spyOn($http, 'post');
  4267. * eventTracker.event('login');
  4268. * eventTracker.save();
  4269. * expect(postSpy).toHaveBeenCalled();
  4270. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4271. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4272. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4273. * }));
  4274. * });
  4275. * ```
  4276. */
  4277. /**
  4278. * @ngdoc method
  4279. * @name $provide#factory
  4280. * @description
  4281. *
  4282. * Register a **service factory**, which will be called to return the service instance.
  4283. * This is short for registering a service where its provider consists of only a `$get` property,
  4284. * which is the given service factory function.
  4285. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4286. * configure your service in a provider.
  4287. *
  4288. * @param {string} name The name of the instance.
  4289. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4290. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4291. * @returns {Object} registered provider instance
  4292. *
  4293. * @example
  4294. * Here is an example of registering a service
  4295. * ```js
  4296. * $provide.factory('ping', ['$http', function($http) {
  4297. * return function ping() {
  4298. * return $http.send('/ping');
  4299. * };
  4300. * }]);
  4301. * ```
  4302. * You would then inject and use this service like this:
  4303. * ```js
  4304. * someModule.controller('Ctrl', ['ping', function(ping) {
  4305. * ping();
  4306. * }]);
  4307. * ```
  4308. */
  4309. /**
  4310. * @ngdoc method
  4311. * @name $provide#service
  4312. * @description
  4313. *
  4314. * Register a **service constructor**, which will be invoked with `new` to create the service
  4315. * instance.
  4316. * This is short for registering a service where its provider's `$get` property is a factory
  4317. * function that returns an instance instantiated by the injector from the service constructor
  4318. * function.
  4319. *
  4320. * Internally it looks a bit like this:
  4321. *
  4322. * ```
  4323. * {
  4324. * $get: function() {
  4325. * return $injector.instantiate(constructor);
  4326. * }
  4327. * }
  4328. * ```
  4329. *
  4330. *
  4331. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4332. * as a type/class.
  4333. *
  4334. * @param {string} name The name of the instance.
  4335. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4336. * that will be instantiated.
  4337. * @returns {Object} registered provider instance
  4338. *
  4339. * @example
  4340. * Here is an example of registering a service using
  4341. * {@link auto.$provide#service $provide.service(class)}.
  4342. * ```js
  4343. * var Ping = function($http) {
  4344. * this.$http = $http;
  4345. * };
  4346. *
  4347. * Ping.$inject = ['$http'];
  4348. *
  4349. * Ping.prototype.send = function() {
  4350. * return this.$http.get('/ping');
  4351. * };
  4352. * $provide.service('ping', Ping);
  4353. * ```
  4354. * You would then inject and use this service like this:
  4355. * ```js
  4356. * someModule.controller('Ctrl', ['ping', function(ping) {
  4357. * ping.send();
  4358. * }]);
  4359. * ```
  4360. */
  4361. /**
  4362. * @ngdoc method
  4363. * @name $provide#value
  4364. * @description
  4365. *
  4366. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4367. * number, an array, an object or a function. This is short for registering a service where its
  4368. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4369. * service**. That also means it is not possible to inject other services into a value service.
  4370. *
  4371. * Value services are similar to constant services, except that they cannot be injected into a
  4372. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4373. * an AngularJS {@link auto.$provide#decorator decorator}.
  4374. *
  4375. * @param {string} name The name of the instance.
  4376. * @param {*} value The value.
  4377. * @returns {Object} registered provider instance
  4378. *
  4379. * @example
  4380. * Here are some examples of creating value services.
  4381. * ```js
  4382. * $provide.value('ADMIN_USER', 'admin');
  4383. *
  4384. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4385. *
  4386. * $provide.value('halfOf', function(value) {
  4387. * return value / 2;
  4388. * });
  4389. * ```
  4390. */
  4391. /**
  4392. * @ngdoc method
  4393. * @name $provide#constant
  4394. * @description
  4395. *
  4396. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4397. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4398. * possible to inject other services into a constant.
  4399. *
  4400. * But unlike {@link auto.$provide#value value}, a constant can be
  4401. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4402. * be overridden by an AngularJS {@link auto.$provide#decorator decorator}.
  4403. *
  4404. * @param {string} name The name of the constant.
  4405. * @param {*} value The constant value.
  4406. * @returns {Object} registered instance
  4407. *
  4408. * @example
  4409. * Here a some examples of creating constants:
  4410. * ```js
  4411. * $provide.constant('SHARD_HEIGHT', 306);
  4412. *
  4413. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4414. *
  4415. * $provide.constant('double', function(value) {
  4416. * return value * 2;
  4417. * });
  4418. * ```
  4419. */
  4420. /**
  4421. * @ngdoc method
  4422. * @name $provide#decorator
  4423. * @description
  4424. *
  4425. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4426. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4427. * service. The return value of the decorator function may be the original service, or a new service
  4428. * that replaces (or wraps and delegates to) the original service.
  4429. *
  4430. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4431. *
  4432. * @param {string} name The name of the service to decorate.
  4433. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4434. * provided and should return the decorated service instance. The function is called using
  4435. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4436. * Local injection arguments:
  4437. *
  4438. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4439. * decorated or delegated to.
  4440. *
  4441. * @example
  4442. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4443. * calls to {@link ng.$log#error $log.warn()}.
  4444. * ```js
  4445. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4446. * $delegate.warn = $delegate.error;
  4447. * return $delegate;
  4448. * }]);
  4449. * ```
  4450. */
  4451. function createInjector(modulesToLoad, strictDi) {
  4452. strictDi = (strictDi === true);
  4453. var INSTANTIATING = {},
  4454. providerSuffix = 'Provider',
  4455. path = [],
  4456. loadedModules = new NgMap(),
  4457. providerCache = {
  4458. $provide: {
  4459. provider: supportObject(provider),
  4460. factory: supportObject(factory),
  4461. service: supportObject(service),
  4462. value: supportObject(value),
  4463. constant: supportObject(constant),
  4464. decorator: decorator
  4465. }
  4466. },
  4467. providerInjector = (providerCache.$injector =
  4468. createInternalInjector(providerCache, function(serviceName, caller) {
  4469. if (angular.isString(caller)) {
  4470. path.push(caller);
  4471. }
  4472. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4473. })),
  4474. instanceCache = {},
  4475. protoInstanceInjector =
  4476. createInternalInjector(instanceCache, function(serviceName, caller) {
  4477. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4478. return instanceInjector.invoke(
  4479. provider.$get, provider, undefined, serviceName);
  4480. }),
  4481. instanceInjector = protoInstanceInjector;
  4482. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4483. instanceInjector.modules = providerInjector.modules = createMap();
  4484. var runBlocks = loadModules(modulesToLoad);
  4485. instanceInjector = protoInstanceInjector.get('$injector');
  4486. instanceInjector.strictDi = strictDi;
  4487. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4488. instanceInjector.loadNewModules = function(mods) {
  4489. forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
  4490. };
  4491. return instanceInjector;
  4492. ////////////////////////////////////
  4493. // $provider
  4494. ////////////////////////////////////
  4495. function supportObject(delegate) {
  4496. return function(key, value) {
  4497. if (isObject(key)) {
  4498. forEach(key, reverseParams(delegate));
  4499. } else {
  4500. return delegate(key, value);
  4501. }
  4502. };
  4503. }
  4504. function provider(name, provider_) {
  4505. assertNotHasOwnProperty(name, 'service');
  4506. if (isFunction(provider_) || isArray(provider_)) {
  4507. provider_ = providerInjector.instantiate(provider_);
  4508. }
  4509. if (!provider_.$get) {
  4510. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4511. }
  4512. return (providerCache[name + providerSuffix] = provider_);
  4513. }
  4514. function enforceReturnValue(name, factory) {
  4515. return /** @this */ function enforcedReturnValue() {
  4516. var result = instanceInjector.invoke(factory, this);
  4517. if (isUndefined(result)) {
  4518. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4519. }
  4520. return result;
  4521. };
  4522. }
  4523. function factory(name, factoryFn, enforce) {
  4524. return provider(name, {
  4525. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4526. });
  4527. }
  4528. function service(name, constructor) {
  4529. return factory(name, ['$injector', function($injector) {
  4530. return $injector.instantiate(constructor);
  4531. }]);
  4532. }
  4533. function value(name, val) { return factory(name, valueFn(val), false); }
  4534. function constant(name, value) {
  4535. assertNotHasOwnProperty(name, 'constant');
  4536. providerCache[name] = value;
  4537. instanceCache[name] = value;
  4538. }
  4539. function decorator(serviceName, decorFn) {
  4540. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4541. orig$get = origProvider.$get;
  4542. origProvider.$get = function() {
  4543. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4544. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4545. };
  4546. }
  4547. ////////////////////////////////////
  4548. // Module Loading
  4549. ////////////////////////////////////
  4550. function loadModules(modulesToLoad) {
  4551. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4552. var runBlocks = [], moduleFn;
  4553. forEach(modulesToLoad, function(module) {
  4554. if (loadedModules.get(module)) return;
  4555. loadedModules.set(module, true);
  4556. function runInvokeQueue(queue) {
  4557. var i, ii;
  4558. for (i = 0, ii = queue.length; i < ii; i++) {
  4559. var invokeArgs = queue[i],
  4560. provider = providerInjector.get(invokeArgs[0]);
  4561. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4562. }
  4563. }
  4564. try {
  4565. if (isString(module)) {
  4566. moduleFn = angularModule(module);
  4567. instanceInjector.modules[module] = moduleFn;
  4568. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4569. runInvokeQueue(moduleFn._invokeQueue);
  4570. runInvokeQueue(moduleFn._configBlocks);
  4571. } else if (isFunction(module)) {
  4572. runBlocks.push(providerInjector.invoke(module));
  4573. } else if (isArray(module)) {
  4574. runBlocks.push(providerInjector.invoke(module));
  4575. } else {
  4576. assertArgFn(module, 'module');
  4577. }
  4578. } catch (e) {
  4579. if (isArray(module)) {
  4580. module = module[module.length - 1];
  4581. }
  4582. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4583. // Safari & FF's stack traces don't contain error.message content
  4584. // unlike those of Chrome and IE
  4585. // So if stack doesn't contain message, we create a new string that contains both.
  4586. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4587. // eslint-disable-next-line no-ex-assign
  4588. e = e.message + '\n' + e.stack;
  4589. }
  4590. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4591. module, e.stack || e.message || e);
  4592. }
  4593. });
  4594. return runBlocks;
  4595. }
  4596. ////////////////////////////////////
  4597. // internal Injector
  4598. ////////////////////////////////////
  4599. function createInternalInjector(cache, factory) {
  4600. function getService(serviceName, caller) {
  4601. if (cache.hasOwnProperty(serviceName)) {
  4602. if (cache[serviceName] === INSTANTIATING) {
  4603. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4604. serviceName + ' <- ' + path.join(' <- '));
  4605. }
  4606. return cache[serviceName];
  4607. } else {
  4608. try {
  4609. path.unshift(serviceName);
  4610. cache[serviceName] = INSTANTIATING;
  4611. cache[serviceName] = factory(serviceName, caller);
  4612. return cache[serviceName];
  4613. } catch (err) {
  4614. if (cache[serviceName] === INSTANTIATING) {
  4615. delete cache[serviceName];
  4616. }
  4617. throw err;
  4618. } finally {
  4619. path.shift();
  4620. }
  4621. }
  4622. }
  4623. function injectionArgs(fn, locals, serviceName) {
  4624. var args = [],
  4625. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4626. for (var i = 0, length = $inject.length; i < length; i++) {
  4627. var key = $inject[i];
  4628. if (typeof key !== 'string') {
  4629. throw $injectorMinErr('itkn',
  4630. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4631. }
  4632. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4633. getService(key, serviceName));
  4634. }
  4635. return args;
  4636. }
  4637. function isClass(func) {
  4638. // Support: IE 9-11 only
  4639. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4640. if (msie || typeof func !== 'function') {
  4641. return false;
  4642. }
  4643. var result = func.$$ngIsClass;
  4644. if (!isBoolean(result)) {
  4645. result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func));
  4646. }
  4647. return result;
  4648. }
  4649. function invoke(fn, self, locals, serviceName) {
  4650. if (typeof locals === 'string') {
  4651. serviceName = locals;
  4652. locals = null;
  4653. }
  4654. var args = injectionArgs(fn, locals, serviceName);
  4655. if (isArray(fn)) {
  4656. fn = fn[fn.length - 1];
  4657. }
  4658. if (!isClass(fn)) {
  4659. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4660. // #5388
  4661. return fn.apply(self, args);
  4662. } else {
  4663. args.unshift(null);
  4664. return new (Function.prototype.bind.apply(fn, args))();
  4665. }
  4666. }
  4667. function instantiate(Type, locals, serviceName) {
  4668. // Check if Type is annotated and use just the given function at n-1 as parameter
  4669. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4670. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4671. var args = injectionArgs(Type, locals, serviceName);
  4672. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4673. args.unshift(null);
  4674. return new (Function.prototype.bind.apply(ctor, args))();
  4675. }
  4676. return {
  4677. invoke: invoke,
  4678. instantiate: instantiate,
  4679. get: getService,
  4680. annotate: createInjector.$$annotate,
  4681. has: function(name) {
  4682. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4683. }
  4684. };
  4685. }
  4686. }
  4687. createInjector.$$annotate = annotate;
  4688. /**
  4689. * @ngdoc provider
  4690. * @name $anchorScrollProvider
  4691. * @this
  4692. *
  4693. * @description
  4694. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4695. * {@link ng.$location#hash $location.hash()} changes.
  4696. */
  4697. function $AnchorScrollProvider() {
  4698. var autoScrollingEnabled = true;
  4699. /**
  4700. * @ngdoc method
  4701. * @name $anchorScrollProvider#disableAutoScrolling
  4702. *
  4703. * @description
  4704. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4705. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4706. * Use this method to disable automatic scrolling.
  4707. *
  4708. * If automatic scrolling is disabled, one must explicitly call
  4709. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4710. * current hash.
  4711. */
  4712. this.disableAutoScrolling = function() {
  4713. autoScrollingEnabled = false;
  4714. };
  4715. /**
  4716. * @ngdoc service
  4717. * @name $anchorScroll
  4718. * @kind function
  4719. * @requires $window
  4720. * @requires $location
  4721. * @requires $rootScope
  4722. *
  4723. * @description
  4724. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4725. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4726. * in the
  4727. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4728. *
  4729. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4730. * match any anchor whenever it changes. This can be disabled by calling
  4731. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4732. *
  4733. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4734. * vertical scroll-offset (either fixed or dynamic).
  4735. *
  4736. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4737. * {@link ng.$location#hash $location.hash()} will be used.
  4738. *
  4739. * @property {(number|function|jqLite)} yOffset
  4740. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4741. * positioned elements at the top of the page, such as navbars, headers etc.
  4742. *
  4743. * `yOffset` can be specified in various ways:
  4744. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4745. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4746. * a number representing the offset (in pixels).<br /><br />
  4747. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4748. * the top of the page to the element's bottom will be used as offset.<br />
  4749. * **Note**: The element will be taken into account only as long as its `position` is set to
  4750. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4751. * their height and/or positioning according to the viewport's size.
  4752. *
  4753. * <br />
  4754. * <div class="alert alert-warning">
  4755. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4756. * not some child element.
  4757. * </div>
  4758. *
  4759. * @example
  4760. <example module="anchorScrollExample" name="anchor-scroll">
  4761. <file name="index.html">
  4762. <div id="scrollArea" ng-controller="ScrollController">
  4763. <a ng-click="gotoBottom()">Go to bottom</a>
  4764. <a id="bottom"></a> You're at the bottom!
  4765. </div>
  4766. </file>
  4767. <file name="script.js">
  4768. angular.module('anchorScrollExample', [])
  4769. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4770. function($scope, $location, $anchorScroll) {
  4771. $scope.gotoBottom = function() {
  4772. // set the location.hash to the id of
  4773. // the element you wish to scroll to.
  4774. $location.hash('bottom');
  4775. // call $anchorScroll()
  4776. $anchorScroll();
  4777. };
  4778. }]);
  4779. </file>
  4780. <file name="style.css">
  4781. #scrollArea {
  4782. height: 280px;
  4783. overflow: auto;
  4784. }
  4785. #bottom {
  4786. display: block;
  4787. margin-top: 2000px;
  4788. }
  4789. </file>
  4790. </example>
  4791. *
  4792. * <hr />
  4793. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4794. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4795. *
  4796. * @example
  4797. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4798. <file name="index.html">
  4799. <div class="fixed-header" ng-controller="headerCtrl">
  4800. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4801. Go to anchor {{x}}
  4802. </a>
  4803. </div>
  4804. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4805. Anchor {{x}} of 5
  4806. </div>
  4807. </file>
  4808. <file name="script.js">
  4809. angular.module('anchorScrollOffsetExample', [])
  4810. .run(['$anchorScroll', function($anchorScroll) {
  4811. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4812. }])
  4813. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4814. function($anchorScroll, $location, $scope) {
  4815. $scope.gotoAnchor = function(x) {
  4816. var newHash = 'anchor' + x;
  4817. if ($location.hash() !== newHash) {
  4818. // set the $location.hash to `newHash` and
  4819. // $anchorScroll will automatically scroll to it
  4820. $location.hash('anchor' + x);
  4821. } else {
  4822. // call $anchorScroll() explicitly,
  4823. // since $location.hash hasn't changed
  4824. $anchorScroll();
  4825. }
  4826. };
  4827. }
  4828. ]);
  4829. </file>
  4830. <file name="style.css">
  4831. body {
  4832. padding-top: 50px;
  4833. }
  4834. .anchor {
  4835. border: 2px dashed DarkOrchid;
  4836. padding: 10px 10px 200px 10px;
  4837. }
  4838. .fixed-header {
  4839. background-color: rgba(0, 0, 0, 0.2);
  4840. height: 50px;
  4841. position: fixed;
  4842. top: 0; left: 0; right: 0;
  4843. }
  4844. .fixed-header > a {
  4845. display: inline-block;
  4846. margin: 5px 15px;
  4847. }
  4848. </file>
  4849. </example>
  4850. */
  4851. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4852. var document = $window.document;
  4853. // Helper function to get first anchor from a NodeList
  4854. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4855. // and working in all supported browsers.)
  4856. function getFirstAnchor(list) {
  4857. var result = null;
  4858. Array.prototype.some.call(list, function(element) {
  4859. if (nodeName_(element) === 'a') {
  4860. result = element;
  4861. return true;
  4862. }
  4863. });
  4864. return result;
  4865. }
  4866. function getYOffset() {
  4867. var offset = scroll.yOffset;
  4868. if (isFunction(offset)) {
  4869. offset = offset();
  4870. } else if (isElement(offset)) {
  4871. var elem = offset[0];
  4872. var style = $window.getComputedStyle(elem);
  4873. if (style.position !== 'fixed') {
  4874. offset = 0;
  4875. } else {
  4876. offset = elem.getBoundingClientRect().bottom;
  4877. }
  4878. } else if (!isNumber(offset)) {
  4879. offset = 0;
  4880. }
  4881. return offset;
  4882. }
  4883. function scrollTo(elem) {
  4884. if (elem) {
  4885. elem.scrollIntoView();
  4886. var offset = getYOffset();
  4887. if (offset) {
  4888. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4889. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4890. // top of the viewport.
  4891. //
  4892. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4893. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4894. // way down the page.
  4895. //
  4896. // This is often the case for elements near the bottom of the page.
  4897. //
  4898. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4899. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4900. // desired position.
  4901. var elemTop = elem.getBoundingClientRect().top;
  4902. $window.scrollBy(0, elemTop - offset);
  4903. }
  4904. } else {
  4905. $window.scrollTo(0, 0);
  4906. }
  4907. }
  4908. function scroll(hash) {
  4909. // Allow numeric hashes
  4910. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4911. var elm;
  4912. // empty hash, scroll to the top of the page
  4913. if (!hash) scrollTo(null);
  4914. // element with given id
  4915. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4916. // first anchor with given name :-D
  4917. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4918. // no element and hash === 'top', scroll to the top of the page
  4919. else if (hash === 'top') scrollTo(null);
  4920. }
  4921. // does not scroll when user clicks on anchor link that is currently on
  4922. // (no url change, no $location.hash() change), browser native does scroll
  4923. if (autoScrollingEnabled) {
  4924. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4925. function autoScrollWatchAction(newVal, oldVal) {
  4926. // skip the initial scroll if $location.hash is empty
  4927. if (newVal === oldVal && newVal === '') return;
  4928. jqLiteDocumentLoaded(function() {
  4929. $rootScope.$evalAsync(scroll);
  4930. });
  4931. });
  4932. }
  4933. return scroll;
  4934. }];
  4935. }
  4936. var $animateMinErr = minErr('$animate');
  4937. var ELEMENT_NODE = 1;
  4938. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4939. function mergeClasses(a,b) {
  4940. if (!a && !b) return '';
  4941. if (!a) return b;
  4942. if (!b) return a;
  4943. if (isArray(a)) a = a.join(' ');
  4944. if (isArray(b)) b = b.join(' ');
  4945. return a + ' ' + b;
  4946. }
  4947. function extractElementNode(element) {
  4948. for (var i = 0; i < element.length; i++) {
  4949. var elm = element[i];
  4950. if (elm.nodeType === ELEMENT_NODE) {
  4951. return elm;
  4952. }
  4953. }
  4954. }
  4955. function splitClasses(classes) {
  4956. if (isString(classes)) {
  4957. classes = classes.split(' ');
  4958. }
  4959. // Use createMap() to prevent class assumptions involving property names in
  4960. // Object.prototype
  4961. var obj = createMap();
  4962. forEach(classes, function(klass) {
  4963. // sometimes the split leaves empty string values
  4964. // incase extra spaces were applied to the options
  4965. if (klass.length) {
  4966. obj[klass] = true;
  4967. }
  4968. });
  4969. return obj;
  4970. }
  4971. // if any other type of options value besides an Object value is
  4972. // passed into the $animate.method() animation then this helper code
  4973. // will be run which will ignore it. While this patch is not the
  4974. // greatest solution to this, a lot of existing plugins depend on
  4975. // $animate to either call the callback (< 1.2) or return a promise
  4976. // that can be changed. This helper function ensures that the options
  4977. // are wiped clean incase a callback function is provided.
  4978. function prepareAnimateOptions(options) {
  4979. return isObject(options)
  4980. ? options
  4981. : {};
  4982. }
  4983. var $$CoreAnimateJsProvider = /** @this */ function() {
  4984. this.$get = noop;
  4985. };
  4986. // this is prefixed with Core since it conflicts with
  4987. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4988. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4989. var postDigestQueue = new NgMap();
  4990. var postDigestElements = [];
  4991. this.$get = ['$$AnimateRunner', '$rootScope',
  4992. function($$AnimateRunner, $rootScope) {
  4993. return {
  4994. enabled: noop,
  4995. on: noop,
  4996. off: noop,
  4997. pin: noop,
  4998. push: function(element, event, options, domOperation) {
  4999. if (domOperation) {
  5000. domOperation();
  5001. }
  5002. options = options || {};
  5003. if (options.from) {
  5004. element.css(options.from);
  5005. }
  5006. if (options.to) {
  5007. element.css(options.to);
  5008. }
  5009. if (options.addClass || options.removeClass) {
  5010. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  5011. }
  5012. var runner = new $$AnimateRunner();
  5013. // since there are no animations to run the runner needs to be
  5014. // notified that the animation call is complete.
  5015. runner.complete();
  5016. return runner;
  5017. }
  5018. };
  5019. function updateData(data, classes, value) {
  5020. var changed = false;
  5021. if (classes) {
  5022. classes = isString(classes) ? classes.split(' ') :
  5023. isArray(classes) ? classes : [];
  5024. forEach(classes, function(className) {
  5025. if (className) {
  5026. changed = true;
  5027. data[className] = value;
  5028. }
  5029. });
  5030. }
  5031. return changed;
  5032. }
  5033. function handleCSSClassChanges() {
  5034. forEach(postDigestElements, function(element) {
  5035. var data = postDigestQueue.get(element);
  5036. if (data) {
  5037. var existing = splitClasses(element.attr('class'));
  5038. var toAdd = '';
  5039. var toRemove = '';
  5040. forEach(data, function(status, className) {
  5041. var hasClass = !!existing[className];
  5042. if (status !== hasClass) {
  5043. if (status) {
  5044. toAdd += (toAdd.length ? ' ' : '') + className;
  5045. } else {
  5046. toRemove += (toRemove.length ? ' ' : '') + className;
  5047. }
  5048. }
  5049. });
  5050. forEach(element, function(elm) {
  5051. if (toAdd) {
  5052. jqLiteAddClass(elm, toAdd);
  5053. }
  5054. if (toRemove) {
  5055. jqLiteRemoveClass(elm, toRemove);
  5056. }
  5057. });
  5058. postDigestQueue.delete(element);
  5059. }
  5060. });
  5061. postDigestElements.length = 0;
  5062. }
  5063. function addRemoveClassesPostDigest(element, add, remove) {
  5064. var data = postDigestQueue.get(element) || {};
  5065. var classesAdded = updateData(data, add, true);
  5066. var classesRemoved = updateData(data, remove, false);
  5067. if (classesAdded || classesRemoved) {
  5068. postDigestQueue.set(element, data);
  5069. postDigestElements.push(element);
  5070. if (postDigestElements.length === 1) {
  5071. $rootScope.$$postDigest(handleCSSClassChanges);
  5072. }
  5073. }
  5074. }
  5075. }];
  5076. };
  5077. /**
  5078. * @ngdoc provider
  5079. * @name $animateProvider
  5080. *
  5081. * @description
  5082. * Default implementation of $animate that doesn't perform any animations, instead just
  5083. * synchronously performs DOM updates and resolves the returned runner promise.
  5084. *
  5085. * In order to enable animations the `ngAnimate` module has to be loaded.
  5086. *
  5087. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  5088. */
  5089. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  5090. var provider = this;
  5091. var classNameFilter = null;
  5092. var customFilter = null;
  5093. this.$$registeredAnimations = Object.create(null);
  5094. /**
  5095. * @ngdoc method
  5096. * @name $animateProvider#register
  5097. *
  5098. * @description
  5099. * Registers a new injectable animation factory function. The factory function produces the
  5100. * animation object which contains callback functions for each event that is expected to be
  5101. * animated.
  5102. *
  5103. * * `eventFn`: `function(element, ... , doneFunction, options)`
  5104. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  5105. * on the type of animation additional arguments will be injected into the animation function. The
  5106. * list below explains the function signatures for the different animation methods:
  5107. *
  5108. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  5109. * - addClass: function(element, addedClasses, doneFunction, options)
  5110. * - removeClass: function(element, removedClasses, doneFunction, options)
  5111. * - enter, leave, move: function(element, doneFunction, options)
  5112. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  5113. *
  5114. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  5115. *
  5116. * ```js
  5117. * return {
  5118. * //enter, leave, move signature
  5119. * eventFn : function(element, done, options) {
  5120. * //code to run the animation
  5121. * //once complete, then run done()
  5122. * return function endFunction(wasCancelled) {
  5123. * //code to cancel the animation
  5124. * }
  5125. * }
  5126. * }
  5127. * ```
  5128. *
  5129. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  5130. * @param {Function} factory The factory function that will be executed to return the animation
  5131. * object.
  5132. */
  5133. this.register = function(name, factory) {
  5134. if (name && name.charAt(0) !== '.') {
  5135. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  5136. }
  5137. var key = name + '-animation';
  5138. provider.$$registeredAnimations[name.substr(1)] = key;
  5139. $provide.factory(key, factory);
  5140. };
  5141. /**
  5142. * @ngdoc method
  5143. * @name $animateProvider#customFilter
  5144. *
  5145. * @description
  5146. * Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
  5147. * determine if an animation is allowed or not. When no filter is specified (the default), no
  5148. * animation will be blocked. Setting the `customFilter` value will only allow animations for
  5149. * which the filter function's return value is truthy.
  5150. *
  5151. * This allows to easily create arbitrarily complex rules for filtering animations, such as
  5152. * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
  5153. * Filtering animations can also boost performance for low-powered devices, as well as
  5154. * applications containing a lot of structural operations.
  5155. *
  5156. * <div class="alert alert-success">
  5157. * **Best Practice:**
  5158. * Keep the filtering function as lean as possible, because it will be called for each DOM
  5159. * action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
  5160. * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
  5161. * directives that support animations.
  5162. * Performing computationally expensive or time-consuming operations on each call of the
  5163. * filtering function can make your animations sluggish.
  5164. * </div>
  5165. *
  5166. * **Note:** If present, `customFilter` will be checked before
  5167. * {@link $animateProvider#classNameFilter classNameFilter}.
  5168. *
  5169. * @param {Function=} filterFn - The filter function which will be used to filter all animations.
  5170. * If a falsy value is returned, no animation will be performed. The function will be called
  5171. * with the following arguments:
  5172. * - **node** `{DOMElement}` - The DOM element to be animated.
  5173. * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
  5174. * etc).
  5175. * - **options** `{Object}` - A collection of options/styles used for the animation.
  5176. * @return {Function} The current filter function or `null` if there is none set.
  5177. */
  5178. this.customFilter = function(filterFn) {
  5179. if (arguments.length === 1) {
  5180. customFilter = isFunction(filterFn) ? filterFn : null;
  5181. }
  5182. return customFilter;
  5183. };
  5184. /**
  5185. * @ngdoc method
  5186. * @name $animateProvider#classNameFilter
  5187. *
  5188. * @description
  5189. * Sets and/or returns the CSS class regular expression that is checked when performing
  5190. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  5191. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  5192. * When setting the `classNameFilter` value, animations will only be performed on elements
  5193. * that successfully match the filter expression. This in turn can boost performance
  5194. * for low-powered devices as well as applications containing a lot of structural operations.
  5195. *
  5196. * **Note:** If present, `classNameFilter` will be checked after
  5197. * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
  5198. * false, `classNameFilter` will not be checked.
  5199. *
  5200. * @param {RegExp=} expression The className expression which will be checked against all animations
  5201. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  5202. */
  5203. this.classNameFilter = function(expression) {
  5204. if (arguments.length === 1) {
  5205. classNameFilter = (expression instanceof RegExp) ? expression : null;
  5206. if (classNameFilter) {
  5207. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  5208. if (reservedRegex.test(classNameFilter.toString())) {
  5209. classNameFilter = null;
  5210. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  5211. }
  5212. }
  5213. }
  5214. return classNameFilter;
  5215. };
  5216. this.$get = ['$$animateQueue', function($$animateQueue) {
  5217. function domInsert(element, parentElement, afterElement) {
  5218. // if for some reason the previous element was removed
  5219. // from the dom sometime before this code runs then let's
  5220. // just stick to using the parent element as the anchor
  5221. if (afterElement) {
  5222. var afterNode = extractElementNode(afterElement);
  5223. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  5224. afterElement = null;
  5225. }
  5226. }
  5227. if (afterElement) {
  5228. afterElement.after(element);
  5229. } else {
  5230. parentElement.prepend(element);
  5231. }
  5232. }
  5233. /**
  5234. * @ngdoc service
  5235. * @name $animate
  5236. * @description The $animate service exposes a series of DOM utility methods that provide support
  5237. * for animation hooks. The default behavior is the application of DOM operations, however,
  5238. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5239. * to ensure that animation runs with the triggered DOM operation.
  5240. *
  5241. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5242. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5243. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5244. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5245. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5246. *
  5247. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5248. *
  5249. * To learn more about enabling animation support, click here to visit the
  5250. * {@link ngAnimate ngAnimate module page}.
  5251. */
  5252. return {
  5253. // we don't call it directly since non-existant arguments may
  5254. // be interpreted as null within the sub enabled function
  5255. /**
  5256. *
  5257. * @ngdoc method
  5258. * @name $animate#on
  5259. * @kind function
  5260. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5261. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5262. * is fired with the following params:
  5263. *
  5264. * ```js
  5265. * $animate.on('enter', container,
  5266. * function callback(element, phase) {
  5267. * // cool we detected an enter animation within the container
  5268. * }
  5269. * );
  5270. * ```
  5271. *
  5272. * <div class="alert alert-warning">
  5273. * **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names,
  5274. * e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass}
  5275. * will fire `addClass` if classes are added, and `removeClass` if classes are removed.
  5276. * However, there are two exceptions:
  5277. *
  5278. * <ul>
  5279. * <li>if both an {@link ng.$animate#addClass addClass()} and a
  5280. * {@link ng.$animate#removeClass removeClass()} action are performed during the same
  5281. * animation, the event fired will be `setClass`. This is true even for `ngClass`.</li>
  5282. * <li>an {@link ng.$animate#animate animate()} call that adds and removes classes will fire
  5283. * the `setClass` event, but if it either removes or adds classes,
  5284. * it will fire `animate` instead.</li>
  5285. * </ul>
  5286. *
  5287. * </div>
  5288. *
  5289. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5290. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5291. * as well as among its children
  5292. * @param {Function} callback the callback function that will be fired when the listener is triggered.
  5293. *
  5294. * The arguments present in the callback function are:
  5295. * * `element` - The captured DOM element that the animation was fired on.
  5296. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5297. * * `data` - an object with these properties:
  5298. * * addClass - `{string|null}` - space-separated CSS classes to add to the element
  5299. * * removeClass - `{string|null}` - space-separated CSS classes to remove from the element
  5300. * * from - `{Object|null}` - CSS properties & values at the beginning of the animation
  5301. * * to - `{Object|null}` - CSS properties & values at the end of the animation
  5302. *
  5303. * Note that the callback does not trigger a scope digest. Wrap your call into a
  5304. * {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope.
  5305. */
  5306. on: $$animateQueue.on,
  5307. /**
  5308. *
  5309. * @ngdoc method
  5310. * @name $animate#off
  5311. * @kind function
  5312. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5313. * can be used in three different ways depending on the arguments:
  5314. *
  5315. * ```js
  5316. * // remove all the animation event listeners listening for `enter`
  5317. * $animate.off('enter');
  5318. *
  5319. * // remove listeners for all animation events from the container element
  5320. * $animate.off(container);
  5321. *
  5322. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5323. * $animate.off('enter', container);
  5324. *
  5325. * // remove the event listener function provided by `callback` that is set
  5326. * // to listen for `enter` on the given `container` as well as its children
  5327. * $animate.off('enter', container, callback);
  5328. * ```
  5329. *
  5330. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5331. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5332. * arguments are ignored.
  5333. * @param {DOMElement=} container the container element the event listener was placed on
  5334. * @param {Function=} callback the callback function that was registered as the listener
  5335. */
  5336. off: $$animateQueue.off,
  5337. /**
  5338. * @ngdoc method
  5339. * @name $animate#pin
  5340. * @kind function
  5341. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5342. * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the
  5343. * element despite being outside the realm of the application or within another application. Say for example if the application
  5344. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5345. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5346. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5347. *
  5348. * Note that this feature is only active when the `ngAnimate` module is used.
  5349. *
  5350. * @param {DOMElement} element the external element that will be pinned
  5351. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5352. */
  5353. pin: $$animateQueue.pin,
  5354. /**
  5355. *
  5356. * @ngdoc method
  5357. * @name $animate#enabled
  5358. * @kind function
  5359. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5360. * function can be called in four ways:
  5361. *
  5362. * ```js
  5363. * // returns true or false
  5364. * $animate.enabled();
  5365. *
  5366. * // changes the enabled state for all animations
  5367. * $animate.enabled(false);
  5368. * $animate.enabled(true);
  5369. *
  5370. * // returns true or false if animations are enabled for an element
  5371. * $animate.enabled(element);
  5372. *
  5373. * // changes the enabled state for an element and its children
  5374. * $animate.enabled(element, true);
  5375. * $animate.enabled(element, false);
  5376. * ```
  5377. *
  5378. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5379. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5380. *
  5381. * @return {boolean} whether or not animations are enabled
  5382. */
  5383. enabled: $$animateQueue.enabled,
  5384. /**
  5385. * @ngdoc method
  5386. * @name $animate#cancel
  5387. * @kind function
  5388. * @description Cancels the provided animation and applies the end state of the animation.
  5389. * Note that this does not cancel the underlying operation, e.g. the setting of classes or
  5390. * adding the element to the DOM.
  5391. *
  5392. * @param {animationRunner} animationRunner An animation runner returned by an $animate function.
  5393. *
  5394. * @example
  5395. <example module="animationExample" deps="angular-animate.js" animations="true" name="animate-cancel">
  5396. <file name="app.js">
  5397. angular.module('animationExample', ['ngAnimate']).component('cancelExample', {
  5398. templateUrl: 'template.html',
  5399. controller: function($element, $animate) {
  5400. this.runner = null;
  5401. this.addClass = function() {
  5402. this.runner = $animate.addClass($element.find('div'), 'red');
  5403. var ctrl = this;
  5404. this.runner.finally(function() {
  5405. ctrl.runner = null;
  5406. });
  5407. };
  5408. this.removeClass = function() {
  5409. this.runner = $animate.removeClass($element.find('div'), 'red');
  5410. var ctrl = this;
  5411. this.runner.finally(function() {
  5412. ctrl.runner = null;
  5413. });
  5414. };
  5415. this.cancel = function() {
  5416. $animate.cancel(this.runner);
  5417. };
  5418. }
  5419. });
  5420. </file>
  5421. <file name="template.html">
  5422. <p>
  5423. <button id="add" ng-click="$ctrl.addClass()">Add</button>
  5424. <button ng-click="$ctrl.removeClass()">Remove</button>
  5425. <br>
  5426. <button id="cancel" ng-click="$ctrl.cancel()" ng-disabled="!$ctrl.runner">Cancel</button>
  5427. <br>
  5428. <div id="target">CSS-Animated Text</div>
  5429. </p>
  5430. </file>
  5431. <file name="index.html">
  5432. <cancel-example></cancel-example>
  5433. </file>
  5434. <file name="style.css">
  5435. .red-add, .red-remove {
  5436. transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940);
  5437. }
  5438. .red,
  5439. .red-add.red-add-active {
  5440. color: #FF0000;
  5441. font-size: 40px;
  5442. }
  5443. .red-remove.red-remove-active {
  5444. font-size: 10px;
  5445. color: black;
  5446. }
  5447. </file>
  5448. </example>
  5449. */
  5450. cancel: function(runner) {
  5451. if (runner.cancel) {
  5452. runner.cancel();
  5453. }
  5454. },
  5455. /**
  5456. *
  5457. * @ngdoc method
  5458. * @name $animate#enter
  5459. * @kind function
  5460. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5461. * as the first child within the `parent` element and then triggers an animation.
  5462. * A promise is returned that will be resolved during the next digest once the animation
  5463. * has completed.
  5464. *
  5465. * @param {DOMElement} element the element which will be inserted into the DOM
  5466. * @param {DOMElement} parent the parent element which will append the element as
  5467. * a child (so long as the after element is not present)
  5468. * @param {DOMElement=} after the sibling element after which the element will be appended
  5469. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5470. * The object can have the following properties:
  5471. *
  5472. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5473. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5474. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5475. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5476. *
  5477. * @return {Runner} the animation runner
  5478. */
  5479. enter: function(element, parent, after, options) {
  5480. parent = parent && jqLite(parent);
  5481. after = after && jqLite(after);
  5482. parent = parent || after.parent();
  5483. domInsert(element, parent, after);
  5484. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5485. },
  5486. /**
  5487. *
  5488. * @ngdoc method
  5489. * @name $animate#move
  5490. * @kind function
  5491. * @description Inserts (moves) the element into its new position in the DOM either after
  5492. * the `after` element (if provided) or as the first child within the `parent` element
  5493. * and then triggers an animation. A promise is returned that will be resolved
  5494. * during the next digest once the animation has completed.
  5495. *
  5496. * @param {DOMElement} element the element which will be moved into the new DOM position
  5497. * @param {DOMElement} parent the parent element which will append the element as
  5498. * a child (so long as the after element is not present)
  5499. * @param {DOMElement=} after the sibling element after which the element will be appended
  5500. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5501. * The object can have the following properties:
  5502. *
  5503. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5504. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5505. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5506. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5507. *
  5508. * @return {Runner} the animation runner
  5509. */
  5510. move: function(element, parent, after, options) {
  5511. parent = parent && jqLite(parent);
  5512. after = after && jqLite(after);
  5513. parent = parent || after.parent();
  5514. domInsert(element, parent, after);
  5515. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5516. },
  5517. /**
  5518. * @ngdoc method
  5519. * @name $animate#leave
  5520. * @kind function
  5521. * @description Triggers an animation and then removes the element from the DOM.
  5522. * When the function is called a promise is returned that will be resolved during the next
  5523. * digest once the animation has completed.
  5524. *
  5525. * @param {DOMElement} element the element which will be removed from the DOM
  5526. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5527. * The object can have the following properties:
  5528. *
  5529. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5530. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5531. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5532. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5533. *
  5534. * @return {Runner} the animation runner
  5535. */
  5536. leave: function(element, options) {
  5537. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5538. element.remove();
  5539. });
  5540. },
  5541. /**
  5542. * @ngdoc method
  5543. * @name $animate#addClass
  5544. * @kind function
  5545. *
  5546. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5547. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5548. * animation if element already contains the CSS class or if the class is removed at a later step.
  5549. * Note that class-based animations are treated differently compared to structural animations
  5550. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5551. * depending if CSS or JavaScript animations are used.
  5552. *
  5553. * @param {DOMElement} element the element which the CSS classes will be applied to
  5554. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5555. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5556. * The object can have the following properties:
  5557. *
  5558. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5559. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5560. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5561. *
  5562. * @return {Runner} animationRunner the animation runner
  5563. */
  5564. addClass: function(element, className, options) {
  5565. options = prepareAnimateOptions(options);
  5566. options.addClass = mergeClasses(options.addclass, className);
  5567. return $$animateQueue.push(element, 'addClass', options);
  5568. },
  5569. /**
  5570. * @ngdoc method
  5571. * @name $animate#removeClass
  5572. * @kind function
  5573. *
  5574. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5575. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5576. * animation if element does not contain the CSS class or if the class is added at a later step.
  5577. * Note that class-based animations are treated differently compared to structural animations
  5578. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5579. * depending if CSS or JavaScript animations are used.
  5580. *
  5581. * @param {DOMElement} element the element which the CSS classes will be applied to
  5582. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5583. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5584. * The object can have the following properties:
  5585. *
  5586. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5587. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5588. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5589. *
  5590. * @return {Runner} the animation runner
  5591. */
  5592. removeClass: function(element, className, options) {
  5593. options = prepareAnimateOptions(options);
  5594. options.removeClass = mergeClasses(options.removeClass, className);
  5595. return $$animateQueue.push(element, 'removeClass', options);
  5596. },
  5597. /**
  5598. * @ngdoc method
  5599. * @name $animate#setClass
  5600. * @kind function
  5601. *
  5602. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5603. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5604. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5605. * passed. Note that class-based animations are treated differently compared to structural animations
  5606. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5607. * depending if CSS or JavaScript animations are used.
  5608. *
  5609. * @param {DOMElement} element the element which the CSS classes will be applied to
  5610. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5611. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5612. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5613. * The object can have the following properties:
  5614. *
  5615. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5616. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5617. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5618. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5619. *
  5620. * @return {Runner} the animation runner
  5621. */
  5622. setClass: function(element, add, remove, options) {
  5623. options = prepareAnimateOptions(options);
  5624. options.addClass = mergeClasses(options.addClass, add);
  5625. options.removeClass = mergeClasses(options.removeClass, remove);
  5626. return $$animateQueue.push(element, 'setClass', options);
  5627. },
  5628. /**
  5629. * @ngdoc method
  5630. * @name $animate#animate
  5631. * @kind function
  5632. *
  5633. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5634. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5635. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5636. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5637. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5638. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5639. * method (or as part of the `options` parameter):
  5640. *
  5641. * ```js
  5642. * ngModule.animation('.my-inline-animation', function() {
  5643. * return {
  5644. * animate : function(element, from, to, done, options) {
  5645. * //animation
  5646. * done();
  5647. * }
  5648. * }
  5649. * });
  5650. * ```
  5651. *
  5652. * @param {DOMElement} element the element which the CSS styles will be applied to
  5653. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5654. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5655. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5656. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5657. * (Note that if no animation is detected then this value will not be applied to the element.)
  5658. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5659. * The object can have the following properties:
  5660. *
  5661. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5662. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5663. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5664. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5665. *
  5666. * @return {Runner} the animation runner
  5667. */
  5668. animate: function(element, from, to, className, options) {
  5669. options = prepareAnimateOptions(options);
  5670. options.from = options.from ? extend(options.from, from) : from;
  5671. options.to = options.to ? extend(options.to, to) : to;
  5672. className = className || 'ng-inline-animate';
  5673. options.tempClasses = mergeClasses(options.tempClasses, className);
  5674. return $$animateQueue.push(element, 'animate', options);
  5675. }
  5676. };
  5677. }];
  5678. }];
  5679. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5680. this.$get = ['$$rAF', function($$rAF) {
  5681. var waitQueue = [];
  5682. function waitForTick(fn) {
  5683. waitQueue.push(fn);
  5684. if (waitQueue.length > 1) return;
  5685. $$rAF(function() {
  5686. for (var i = 0; i < waitQueue.length; i++) {
  5687. waitQueue[i]();
  5688. }
  5689. waitQueue = [];
  5690. });
  5691. }
  5692. return function() {
  5693. var passed = false;
  5694. waitForTick(function() {
  5695. passed = true;
  5696. });
  5697. return function(callback) {
  5698. if (passed) {
  5699. callback();
  5700. } else {
  5701. waitForTick(callback);
  5702. }
  5703. };
  5704. };
  5705. }];
  5706. };
  5707. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5708. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5709. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5710. var INITIAL_STATE = 0;
  5711. var DONE_PENDING_STATE = 1;
  5712. var DONE_COMPLETE_STATE = 2;
  5713. AnimateRunner.chain = function(chain, callback) {
  5714. var index = 0;
  5715. next();
  5716. function next() {
  5717. if (index === chain.length) {
  5718. callback(true);
  5719. return;
  5720. }
  5721. chain[index](function(response) {
  5722. if (response === false) {
  5723. callback(false);
  5724. return;
  5725. }
  5726. index++;
  5727. next();
  5728. });
  5729. }
  5730. };
  5731. AnimateRunner.all = function(runners, callback) {
  5732. var count = 0;
  5733. var status = true;
  5734. forEach(runners, function(runner) {
  5735. runner.done(onProgress);
  5736. });
  5737. function onProgress(response) {
  5738. status = status && response;
  5739. if (++count === runners.length) {
  5740. callback(status);
  5741. }
  5742. }
  5743. };
  5744. function AnimateRunner(host) {
  5745. this.setHost(host);
  5746. var rafTick = $$animateAsyncRun();
  5747. var timeoutTick = function(fn) {
  5748. $timeout(fn, 0, false);
  5749. };
  5750. this._doneCallbacks = [];
  5751. this._tick = function(fn) {
  5752. if ($$isDocumentHidden()) {
  5753. timeoutTick(fn);
  5754. } else {
  5755. rafTick(fn);
  5756. }
  5757. };
  5758. this._state = 0;
  5759. }
  5760. AnimateRunner.prototype = {
  5761. setHost: function(host) {
  5762. this.host = host || {};
  5763. },
  5764. done: function(fn) {
  5765. if (this._state === DONE_COMPLETE_STATE) {
  5766. fn();
  5767. } else {
  5768. this._doneCallbacks.push(fn);
  5769. }
  5770. },
  5771. progress: noop,
  5772. getPromise: function() {
  5773. if (!this.promise) {
  5774. var self = this;
  5775. this.promise = $q(function(resolve, reject) {
  5776. self.done(function(status) {
  5777. if (status === false) {
  5778. reject();
  5779. } else {
  5780. resolve();
  5781. }
  5782. });
  5783. });
  5784. }
  5785. return this.promise;
  5786. },
  5787. then: function(resolveHandler, rejectHandler) {
  5788. return this.getPromise().then(resolveHandler, rejectHandler);
  5789. },
  5790. 'catch': function(handler) {
  5791. return this.getPromise()['catch'](handler);
  5792. },
  5793. 'finally': function(handler) {
  5794. return this.getPromise()['finally'](handler);
  5795. },
  5796. pause: function() {
  5797. if (this.host.pause) {
  5798. this.host.pause();
  5799. }
  5800. },
  5801. resume: function() {
  5802. if (this.host.resume) {
  5803. this.host.resume();
  5804. }
  5805. },
  5806. end: function() {
  5807. if (this.host.end) {
  5808. this.host.end();
  5809. }
  5810. this._resolve(true);
  5811. },
  5812. cancel: function() {
  5813. if (this.host.cancel) {
  5814. this.host.cancel();
  5815. }
  5816. this._resolve(false);
  5817. },
  5818. complete: function(response) {
  5819. var self = this;
  5820. if (self._state === INITIAL_STATE) {
  5821. self._state = DONE_PENDING_STATE;
  5822. self._tick(function() {
  5823. self._resolve(response);
  5824. });
  5825. }
  5826. },
  5827. _resolve: function(response) {
  5828. if (this._state !== DONE_COMPLETE_STATE) {
  5829. forEach(this._doneCallbacks, function(fn) {
  5830. fn(response);
  5831. });
  5832. this._doneCallbacks.length = 0;
  5833. this._state = DONE_COMPLETE_STATE;
  5834. }
  5835. }
  5836. };
  5837. return AnimateRunner;
  5838. }];
  5839. };
  5840. /* exported $CoreAnimateCssProvider */
  5841. /**
  5842. * @ngdoc service
  5843. * @name $animateCss
  5844. * @kind object
  5845. * @this
  5846. *
  5847. * @description
  5848. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5849. * then the `$animateCss` service will actually perform animations.
  5850. *
  5851. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5852. */
  5853. var $CoreAnimateCssProvider = function() {
  5854. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5855. return function(element, initialOptions) {
  5856. // all of the animation functions should create
  5857. // a copy of the options data, however, if a
  5858. // parent service has already created a copy then
  5859. // we should stick to using that
  5860. var options = initialOptions || {};
  5861. if (!options.$$prepared) {
  5862. options = copy(options);
  5863. }
  5864. // there is no point in applying the styles since
  5865. // there is no animation that goes on at all in
  5866. // this version of $animateCss.
  5867. if (options.cleanupStyles) {
  5868. options.from = options.to = null;
  5869. }
  5870. if (options.from) {
  5871. element.css(options.from);
  5872. options.from = null;
  5873. }
  5874. var closed, runner = new $$AnimateRunner();
  5875. return {
  5876. start: run,
  5877. end: run
  5878. };
  5879. function run() {
  5880. $$rAF(function() {
  5881. applyAnimationContents();
  5882. if (!closed) {
  5883. runner.complete();
  5884. }
  5885. closed = true;
  5886. });
  5887. return runner;
  5888. }
  5889. function applyAnimationContents() {
  5890. if (options.addClass) {
  5891. element.addClass(options.addClass);
  5892. options.addClass = null;
  5893. }
  5894. if (options.removeClass) {
  5895. element.removeClass(options.removeClass);
  5896. options.removeClass = null;
  5897. }
  5898. if (options.to) {
  5899. element.css(options.to);
  5900. options.to = null;
  5901. }
  5902. }
  5903. };
  5904. }];
  5905. };
  5906. /* global getHash: true, stripHash: false */
  5907. function getHash(url) {
  5908. var index = url.indexOf('#');
  5909. return index === -1 ? '' : url.substr(index);
  5910. }
  5911. function trimEmptyHash(url) {
  5912. return url.replace(/#$/, '');
  5913. }
  5914. /**
  5915. * ! This is a private undocumented service !
  5916. *
  5917. * @name $browser
  5918. * @requires $log
  5919. * @description
  5920. * This object has two goals:
  5921. *
  5922. * - hide all the global state in the browser caused by the window object
  5923. * - abstract away all the browser specific features and inconsistencies
  5924. *
  5925. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5926. * service, which can be used for convenient testing of the application without the interaction with
  5927. * the real browser apis.
  5928. */
  5929. /**
  5930. * @param {object} window The global window object.
  5931. * @param {object} document jQuery wrapped document.
  5932. * @param {object} $log window.console or an object with the same interface.
  5933. * @param {object} $sniffer $sniffer service
  5934. */
  5935. function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) {
  5936. var self = this,
  5937. location = window.location,
  5938. history = window.history,
  5939. setTimeout = window.setTimeout,
  5940. clearTimeout = window.clearTimeout,
  5941. pendingDeferIds = {},
  5942. taskTracker = $$taskTrackerFactory($log);
  5943. self.isMock = false;
  5944. //////////////////////////////////////////////////////////////
  5945. // Task-tracking API
  5946. //////////////////////////////////////////////////////////////
  5947. // TODO(vojta): remove this temporary api
  5948. self.$$completeOutstandingRequest = taskTracker.completeTask;
  5949. self.$$incOutstandingRequestCount = taskTracker.incTaskCount;
  5950. // TODO(vojta): prefix this method with $$ ?
  5951. self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks;
  5952. //////////////////////////////////////////////////////////////
  5953. // URL API
  5954. //////////////////////////////////////////////////////////////
  5955. var cachedState, lastHistoryState,
  5956. lastBrowserUrl = location.href,
  5957. baseElement = document.find('base'),
  5958. pendingLocation = null,
  5959. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5960. try {
  5961. return history.state;
  5962. } catch (e) {
  5963. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5964. }
  5965. };
  5966. cacheState();
  5967. /**
  5968. * @name $browser#url
  5969. *
  5970. * @description
  5971. * GETTER:
  5972. * Without any argument, this method just returns current value of `location.href` (with a
  5973. * trailing `#` stripped of if the hash is empty).
  5974. *
  5975. * SETTER:
  5976. * With at least one argument, this method sets url to new value.
  5977. * If html5 history api supported, `pushState`/`replaceState` is used, otherwise
  5978. * `location.href`/`location.replace` is used.
  5979. * Returns its own instance to allow chaining.
  5980. *
  5981. * NOTE: this api is intended for use only by the `$location` service. Please use the
  5982. * {@link ng.$location $location service} to change url.
  5983. *
  5984. * @param {string} url New url (when used as setter)
  5985. * @param {boolean=} replace Should new url replace current history record?
  5986. * @param {object=} state State object to use with `pushState`/`replaceState`
  5987. */
  5988. self.url = function(url, replace, state) {
  5989. // In modern browsers `history.state` is `null` by default; treating it separately
  5990. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5991. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5992. if (isUndefined(state)) {
  5993. state = null;
  5994. }
  5995. // Android Browser BFCache causes location, history reference to become stale.
  5996. if (location !== window.location) location = window.location;
  5997. if (history !== window.history) history = window.history;
  5998. // setter
  5999. if (url) {
  6000. var sameState = lastHistoryState === state;
  6001. // Normalize the inputted URL
  6002. url = urlResolve(url).href;
  6003. // Don't change anything if previous and current URLs and states match. This also prevents
  6004. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  6005. // See https://github.com/angular/angular.js/commit/ffb2701
  6006. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  6007. return self;
  6008. }
  6009. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  6010. lastBrowserUrl = url;
  6011. lastHistoryState = state;
  6012. // Don't use history API if only the hash changed
  6013. // due to a bug in IE10/IE11 which leads
  6014. // to not firing a `hashchange` nor `popstate` event
  6015. // in some cases (see #9143).
  6016. if ($sniffer.history && (!sameBase || !sameState)) {
  6017. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  6018. cacheState();
  6019. } else {
  6020. if (!sameBase) {
  6021. pendingLocation = url;
  6022. }
  6023. if (replace) {
  6024. location.replace(url);
  6025. } else if (!sameBase) {
  6026. location.href = url;
  6027. } else {
  6028. location.hash = getHash(url);
  6029. }
  6030. if (location.href !== url) {
  6031. pendingLocation = url;
  6032. }
  6033. }
  6034. if (pendingLocation) {
  6035. pendingLocation = url;
  6036. }
  6037. return self;
  6038. // getter
  6039. } else {
  6040. // - pendingLocation is needed as browsers don't allow to read out
  6041. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  6042. // https://openradar.appspot.com/22186109).
  6043. return trimEmptyHash(pendingLocation || location.href);
  6044. }
  6045. };
  6046. /**
  6047. * @name $browser#state
  6048. *
  6049. * @description
  6050. * This method is a getter.
  6051. *
  6052. * Return history.state or null if history.state is undefined.
  6053. *
  6054. * @returns {object} state
  6055. */
  6056. self.state = function() {
  6057. return cachedState;
  6058. };
  6059. var urlChangeListeners = [],
  6060. urlChangeInit = false;
  6061. function cacheStateAndFireUrlChange() {
  6062. pendingLocation = null;
  6063. fireStateOrUrlChange();
  6064. }
  6065. // This variable should be used *only* inside the cacheState function.
  6066. var lastCachedState = null;
  6067. function cacheState() {
  6068. // This should be the only place in $browser where `history.state` is read.
  6069. cachedState = getCurrentState();
  6070. cachedState = isUndefined(cachedState) ? null : cachedState;
  6071. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  6072. if (equals(cachedState, lastCachedState)) {
  6073. cachedState = lastCachedState;
  6074. }
  6075. lastCachedState = cachedState;
  6076. lastHistoryState = cachedState;
  6077. }
  6078. function fireStateOrUrlChange() {
  6079. var prevLastHistoryState = lastHistoryState;
  6080. cacheState();
  6081. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  6082. return;
  6083. }
  6084. lastBrowserUrl = self.url();
  6085. lastHistoryState = cachedState;
  6086. forEach(urlChangeListeners, function(listener) {
  6087. listener(self.url(), cachedState);
  6088. });
  6089. }
  6090. /**
  6091. * @name $browser#onUrlChange
  6092. *
  6093. * @description
  6094. * Register callback function that will be called, when url changes.
  6095. *
  6096. * It's only called when the url is changed from outside of AngularJS:
  6097. * - user types different url into address bar
  6098. * - user clicks on history (forward/back) button
  6099. * - user clicks on a link
  6100. *
  6101. * It's not called when url is changed by $browser.url() method
  6102. *
  6103. * The listener gets called with new url as parameter.
  6104. *
  6105. * NOTE: this api is intended for use only by the $location service. Please use the
  6106. * {@link ng.$location $location service} to monitor url changes in AngularJS apps.
  6107. *
  6108. * @param {function(string)} listener Listener function to be called when url changes.
  6109. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  6110. */
  6111. self.onUrlChange = function(callback) {
  6112. // TODO(vojta): refactor to use node's syntax for events
  6113. if (!urlChangeInit) {
  6114. // We listen on both (hashchange/popstate) when available, as some browsers don't
  6115. // fire popstate when user changes the address bar and don't fire hashchange when url
  6116. // changed by push/replaceState
  6117. // html5 history api - popstate event
  6118. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  6119. // hashchange event
  6120. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  6121. urlChangeInit = true;
  6122. }
  6123. urlChangeListeners.push(callback);
  6124. return callback;
  6125. };
  6126. /**
  6127. * @private
  6128. * Remove popstate and hashchange handler from window.
  6129. *
  6130. * NOTE: this api is intended for use only by $rootScope.
  6131. */
  6132. self.$$applicationDestroyed = function() {
  6133. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  6134. };
  6135. /**
  6136. * Checks whether the url has changed outside of AngularJS.
  6137. * Needs to be exported to be able to check for changes that have been done in sync,
  6138. * as hashchange/popstate events fire in async.
  6139. */
  6140. self.$$checkUrlChange = fireStateOrUrlChange;
  6141. //////////////////////////////////////////////////////////////
  6142. // Misc API
  6143. //////////////////////////////////////////////////////////////
  6144. /**
  6145. * @name $browser#baseHref
  6146. *
  6147. * @description
  6148. * Returns current <base href>
  6149. * (always relative - without domain)
  6150. *
  6151. * @returns {string} The current base href
  6152. */
  6153. self.baseHref = function() {
  6154. var href = baseElement.attr('href');
  6155. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  6156. };
  6157. /**
  6158. * @name $browser#defer
  6159. * @param {function()} fn A function, who's execution should be deferred.
  6160. * @param {number=} [delay=0] Number of milliseconds to defer the function execution.
  6161. * @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred.
  6162. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  6163. *
  6164. * @description
  6165. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  6166. *
  6167. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  6168. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  6169. * via `$browser.defer.flush()`.
  6170. *
  6171. */
  6172. self.defer = function(fn, delay, taskType) {
  6173. var timeoutId;
  6174. delay = delay || 0;
  6175. taskType = taskType || taskTracker.DEFAULT_TASK_TYPE;
  6176. taskTracker.incTaskCount(taskType);
  6177. timeoutId = setTimeout(function() {
  6178. delete pendingDeferIds[timeoutId];
  6179. taskTracker.completeTask(fn, taskType);
  6180. }, delay);
  6181. pendingDeferIds[timeoutId] = taskType;
  6182. return timeoutId;
  6183. };
  6184. /**
  6185. * @name $browser#defer.cancel
  6186. *
  6187. * @description
  6188. * Cancels a deferred task identified with `deferId`.
  6189. *
  6190. * @param {*} deferId Token returned by the `$browser.defer` function.
  6191. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  6192. * canceled.
  6193. */
  6194. self.defer.cancel = function(deferId) {
  6195. if (pendingDeferIds.hasOwnProperty(deferId)) {
  6196. var taskType = pendingDeferIds[deferId];
  6197. delete pendingDeferIds[deferId];
  6198. clearTimeout(deferId);
  6199. taskTracker.completeTask(noop, taskType);
  6200. return true;
  6201. }
  6202. return false;
  6203. };
  6204. }
  6205. /** @this */
  6206. function $BrowserProvider() {
  6207. this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory',
  6208. function($window, $log, $sniffer, $document, $$taskTrackerFactory) {
  6209. return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory);
  6210. }];
  6211. }
  6212. /**
  6213. * @ngdoc service
  6214. * @name $cacheFactory
  6215. * @this
  6216. *
  6217. * @description
  6218. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  6219. * them.
  6220. *
  6221. * ```js
  6222. *
  6223. * var cache = $cacheFactory('cacheId');
  6224. * expect($cacheFactory.get('cacheId')).toBe(cache);
  6225. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  6226. *
  6227. * cache.put("key", "value");
  6228. * cache.put("another key", "another value");
  6229. *
  6230. * // We've specified no options on creation
  6231. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  6232. *
  6233. * ```
  6234. *
  6235. *
  6236. * @param {string} cacheId Name or id of the newly created cache.
  6237. * @param {object=} options Options object that specifies the cache behavior. Properties:
  6238. *
  6239. * - `{number=}` `capacity` — turns the cache into LRU cache.
  6240. *
  6241. * @returns {object} Newly created cache object with the following set of methods:
  6242. *
  6243. * - `{object}` `info()` — Returns id, size, and options of cache.
  6244. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  6245. * it.
  6246. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  6247. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  6248. * - `{void}` `removeAll()` — Removes all cached values.
  6249. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  6250. *
  6251. * @example
  6252. <example module="cacheExampleApp" name="cache-factory">
  6253. <file name="index.html">
  6254. <div ng-controller="CacheController">
  6255. <input ng-model="newCacheKey" placeholder="Key">
  6256. <input ng-model="newCacheValue" placeholder="Value">
  6257. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  6258. <p ng-if="keys.length">Cached Values</p>
  6259. <div ng-repeat="key in keys">
  6260. <span ng-bind="key"></span>
  6261. <span>: </span>
  6262. <b ng-bind="cache.get(key)"></b>
  6263. </div>
  6264. <p>Cache Info</p>
  6265. <div ng-repeat="(key, value) in cache.info()">
  6266. <span ng-bind="key"></span>
  6267. <span>: </span>
  6268. <b ng-bind="value"></b>
  6269. </div>
  6270. </div>
  6271. </file>
  6272. <file name="script.js">
  6273. angular.module('cacheExampleApp', []).
  6274. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  6275. $scope.keys = [];
  6276. $scope.cache = $cacheFactory('cacheId');
  6277. $scope.put = function(key, value) {
  6278. if (angular.isUndefined($scope.cache.get(key))) {
  6279. $scope.keys.push(key);
  6280. }
  6281. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  6282. };
  6283. }]);
  6284. </file>
  6285. <file name="style.css">
  6286. p {
  6287. margin: 10px 0 3px;
  6288. }
  6289. </file>
  6290. </example>
  6291. */
  6292. function $CacheFactoryProvider() {
  6293. this.$get = function() {
  6294. var caches = {};
  6295. function cacheFactory(cacheId, options) {
  6296. if (cacheId in caches) {
  6297. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6298. }
  6299. var size = 0,
  6300. stats = extend({}, options, {id: cacheId}),
  6301. data = createMap(),
  6302. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6303. lruHash = createMap(),
  6304. freshEnd = null,
  6305. staleEnd = null;
  6306. /**
  6307. * @ngdoc type
  6308. * @name $cacheFactory.Cache
  6309. *
  6310. * @description
  6311. * A cache object used to store and retrieve data, primarily used by
  6312. * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
  6313. * directive to cache templates and other data.
  6314. *
  6315. * ```js
  6316. * angular.module('superCache')
  6317. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6318. * return $cacheFactory('super-cache');
  6319. * }]);
  6320. * ```
  6321. *
  6322. * Example test:
  6323. *
  6324. * ```js
  6325. * it('should behave like a cache', inject(function(superCache) {
  6326. * superCache.put('key', 'value');
  6327. * superCache.put('another key', 'another value');
  6328. *
  6329. * expect(superCache.info()).toEqual({
  6330. * id: 'super-cache',
  6331. * size: 2
  6332. * });
  6333. *
  6334. * superCache.remove('another key');
  6335. * expect(superCache.get('another key')).toBeUndefined();
  6336. *
  6337. * superCache.removeAll();
  6338. * expect(superCache.info()).toEqual({
  6339. * id: 'super-cache',
  6340. * size: 0
  6341. * });
  6342. * }));
  6343. * ```
  6344. */
  6345. return (caches[cacheId] = {
  6346. /**
  6347. * @ngdoc method
  6348. * @name $cacheFactory.Cache#put
  6349. * @kind function
  6350. *
  6351. * @description
  6352. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6353. * retrieved later, and incrementing the size of the cache if the key was not already
  6354. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6355. * entries from the set.
  6356. *
  6357. * It will not insert undefined values into the cache.
  6358. *
  6359. * @param {string} key the key under which the cached data is stored.
  6360. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6361. * will not be stored.
  6362. * @returns {*} the value stored.
  6363. */
  6364. put: function(key, value) {
  6365. if (isUndefined(value)) return;
  6366. if (capacity < Number.MAX_VALUE) {
  6367. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6368. refresh(lruEntry);
  6369. }
  6370. if (!(key in data)) size++;
  6371. data[key] = value;
  6372. if (size > capacity) {
  6373. this.remove(staleEnd.key);
  6374. }
  6375. return value;
  6376. },
  6377. /**
  6378. * @ngdoc method
  6379. * @name $cacheFactory.Cache#get
  6380. * @kind function
  6381. *
  6382. * @description
  6383. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6384. *
  6385. * @param {string} key the key of the data to be retrieved
  6386. * @returns {*} the value stored.
  6387. */
  6388. get: function(key) {
  6389. if (capacity < Number.MAX_VALUE) {
  6390. var lruEntry = lruHash[key];
  6391. if (!lruEntry) return;
  6392. refresh(lruEntry);
  6393. }
  6394. return data[key];
  6395. },
  6396. /**
  6397. * @ngdoc method
  6398. * @name $cacheFactory.Cache#remove
  6399. * @kind function
  6400. *
  6401. * @description
  6402. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6403. *
  6404. * @param {string} key the key of the entry to be removed
  6405. */
  6406. remove: function(key) {
  6407. if (capacity < Number.MAX_VALUE) {
  6408. var lruEntry = lruHash[key];
  6409. if (!lruEntry) return;
  6410. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6411. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6412. link(lruEntry.n,lruEntry.p);
  6413. delete lruHash[key];
  6414. }
  6415. if (!(key in data)) return;
  6416. delete data[key];
  6417. size--;
  6418. },
  6419. /**
  6420. * @ngdoc method
  6421. * @name $cacheFactory.Cache#removeAll
  6422. * @kind function
  6423. *
  6424. * @description
  6425. * Clears the cache object of any entries.
  6426. */
  6427. removeAll: function() {
  6428. data = createMap();
  6429. size = 0;
  6430. lruHash = createMap();
  6431. freshEnd = staleEnd = null;
  6432. },
  6433. /**
  6434. * @ngdoc method
  6435. * @name $cacheFactory.Cache#destroy
  6436. * @kind function
  6437. *
  6438. * @description
  6439. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6440. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6441. */
  6442. destroy: function() {
  6443. data = null;
  6444. stats = null;
  6445. lruHash = null;
  6446. delete caches[cacheId];
  6447. },
  6448. /**
  6449. * @ngdoc method
  6450. * @name $cacheFactory.Cache#info
  6451. * @kind function
  6452. *
  6453. * @description
  6454. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6455. *
  6456. * @returns {object} an object with the following properties:
  6457. * <ul>
  6458. * <li>**id**: the id of the cache instance</li>
  6459. * <li>**size**: the number of entries kept in the cache instance</li>
  6460. * <li>**...**: any additional properties from the options object when creating the
  6461. * cache.</li>
  6462. * </ul>
  6463. */
  6464. info: function() {
  6465. return extend({}, stats, {size: size});
  6466. }
  6467. });
  6468. /**
  6469. * makes the `entry` the freshEnd of the LRU linked list
  6470. */
  6471. function refresh(entry) {
  6472. if (entry !== freshEnd) {
  6473. if (!staleEnd) {
  6474. staleEnd = entry;
  6475. } else if (staleEnd === entry) {
  6476. staleEnd = entry.n;
  6477. }
  6478. link(entry.n, entry.p);
  6479. link(entry, freshEnd);
  6480. freshEnd = entry;
  6481. freshEnd.n = null;
  6482. }
  6483. }
  6484. /**
  6485. * bidirectionally links two entries of the LRU linked list
  6486. */
  6487. function link(nextEntry, prevEntry) {
  6488. if (nextEntry !== prevEntry) {
  6489. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6490. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6491. }
  6492. }
  6493. }
  6494. /**
  6495. * @ngdoc method
  6496. * @name $cacheFactory#info
  6497. *
  6498. * @description
  6499. * Get information about all the caches that have been created
  6500. *
  6501. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6502. */
  6503. cacheFactory.info = function() {
  6504. var info = {};
  6505. forEach(caches, function(cache, cacheId) {
  6506. info[cacheId] = cache.info();
  6507. });
  6508. return info;
  6509. };
  6510. /**
  6511. * @ngdoc method
  6512. * @name $cacheFactory#get
  6513. *
  6514. * @description
  6515. * Get access to a cache object by the `cacheId` used when it was created.
  6516. *
  6517. * @param {string} cacheId Name or id of a cache to access.
  6518. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6519. */
  6520. cacheFactory.get = function(cacheId) {
  6521. return caches[cacheId];
  6522. };
  6523. return cacheFactory;
  6524. };
  6525. }
  6526. /**
  6527. * @ngdoc service
  6528. * @name $templateCache
  6529. * @this
  6530. *
  6531. * @description
  6532. * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
  6533. * {@link ng.$cacheFactory $cacheFactory}.
  6534. *
  6535. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6536. * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
  6537. * or by consuming the `$templateCache` service directly.
  6538. *
  6539. * Adding via the `script` tag:
  6540. *
  6541. * ```html
  6542. * <script type="text/ng-template" id="templateId.html">
  6543. * <p>This is the content of the template</p>
  6544. * </script>
  6545. * ```
  6546. *
  6547. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6548. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
  6549. * element with {@link ngApp} attribute), otherwise the template will be ignored.
  6550. *
  6551. * Adding via the `$templateCache` service:
  6552. *
  6553. * ```js
  6554. * var myApp = angular.module('myApp', []);
  6555. * myApp.run(function($templateCache) {
  6556. * $templateCache.put('templateId.html', 'This is the content of the template');
  6557. * });
  6558. * ```
  6559. *
  6560. * To retrieve the template later, simply use it in your component:
  6561. * ```js
  6562. * myApp.component('myComponent', {
  6563. * templateUrl: 'templateId.html'
  6564. * });
  6565. * ```
  6566. *
  6567. * or get it via the `$templateCache` service:
  6568. * ```js
  6569. * $templateCache.get('templateId.html')
  6570. * ```
  6571. *
  6572. */
  6573. function $TemplateCacheProvider() {
  6574. this.$get = ['$cacheFactory', function($cacheFactory) {
  6575. return $cacheFactory('templates');
  6576. }];
  6577. }
  6578. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6579. * Any commits to this file should be reviewed with security in mind. *
  6580. * Changes to this file can potentially create security vulnerabilities. *
  6581. * An approval from 2 Core members with history of modifying *
  6582. * this file is required. *
  6583. * *
  6584. * Does the change somehow allow for arbitrary javascript to be executed? *
  6585. * Or allows for someone to change the prototype of built-in objects? *
  6586. * Or gives undesired access to variables like document or window? *
  6587. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6588. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6589. *
  6590. * DOM-related variables:
  6591. *
  6592. * - "node" - DOM Node
  6593. * - "element" - DOM Element or Node
  6594. * - "$node" or "$element" - jqLite-wrapped node or element
  6595. *
  6596. *
  6597. * Compiler related stuff:
  6598. *
  6599. * - "linkFn" - linking fn of a single directive
  6600. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6601. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6602. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6603. */
  6604. /**
  6605. * @ngdoc service
  6606. * @name $compile
  6607. * @kind function
  6608. *
  6609. * @description
  6610. * Compiles an HTML string or DOM into a template and produces a template function, which
  6611. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6612. *
  6613. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6614. * {@link ng.$compileProvider#directive directives}.
  6615. *
  6616. * <div class="alert alert-warning">
  6617. * **Note:** This document is an in-depth reference of all directive options.
  6618. * For a gentle introduction to directives with examples of common use cases,
  6619. * see the {@link guide/directive directive guide}.
  6620. * </div>
  6621. *
  6622. * ## Comprehensive Directive API
  6623. *
  6624. * There are many different options for a directive.
  6625. *
  6626. * The difference resides in the return value of the factory function.
  6627. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6628. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6629. * the default values).
  6630. *
  6631. * <div class="alert alert-success">
  6632. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6633. * </div>
  6634. *
  6635. * Here's an example directive declared with a Directive Definition Object:
  6636. *
  6637. * ```js
  6638. * var myModule = angular.module(...);
  6639. *
  6640. * myModule.directive('directiveName', function factory(injectables) {
  6641. * var directiveDefinitionObject = {
  6642. * {@link $compile#-priority- priority}: 0,
  6643. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6644. * // or
  6645. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6646. * {@link $compile#-transclude- transclude}: false,
  6647. * {@link $compile#-restrict- restrict}: 'A',
  6648. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6649. * {@link $compile#-scope- scope}: false,
  6650. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6651. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6652. * {@link $compile#-bindtocontroller- bindToController}: false,
  6653. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6654. * {@link $compile#-multielement- multiElement}: false,
  6655. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6656. * return {
  6657. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6658. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6659. * }
  6660. * // or
  6661. * // return function postLink( ... ) { ... }
  6662. * },
  6663. * // or
  6664. * // {@link $compile#-link- link}: {
  6665. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6666. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6667. * // }
  6668. * // or
  6669. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6670. * };
  6671. * return directiveDefinitionObject;
  6672. * });
  6673. * ```
  6674. *
  6675. * <div class="alert alert-warning">
  6676. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6677. * </div>
  6678. *
  6679. * Therefore the above can be simplified as:
  6680. *
  6681. * ```js
  6682. * var myModule = angular.module(...);
  6683. *
  6684. * myModule.directive('directiveName', function factory(injectables) {
  6685. * var directiveDefinitionObject = {
  6686. * link: function postLink(scope, iElement, iAttrs) { ... }
  6687. * };
  6688. * return directiveDefinitionObject;
  6689. * // or
  6690. * // return function postLink(scope, iElement, iAttrs) { ... }
  6691. * });
  6692. * ```
  6693. *
  6694. * ### Life-cycle hooks
  6695. * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the
  6696. * directive:
  6697. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6698. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6699. * this element). This is a good place to put initialization code for your controller.
  6700. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6701. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6702. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6703. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6704. * also be called when your bindings are initialized.
  6705. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6706. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6707. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6708. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6709. * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6710. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6711. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6712. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6713. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6714. * components will have their `$onDestroy()` hook called before child components.
  6715. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6716. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6717. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6718. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6719. * suspended until that occurs.
  6720. *
  6721. * #### Comparison with life-cycle hooks in the new Angular
  6722. * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are
  6723. * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:
  6724. *
  6725. * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.
  6726. * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6727. * In Angular you can only define hooks on the prototype of the Component class.
  6728. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to
  6729. * `ngDoCheck` in Angular.
  6730. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6731. * propagated throughout the application.
  6732. * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6733. * error or do nothing depending upon the state of `enableProdMode()`.
  6734. *
  6735. * #### Life-cycle hook examples
  6736. *
  6737. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6738. * has not changed.
  6739. *
  6740. * <example name="doCheckDateExample" module="do-check-module">
  6741. * <file name="app.js">
  6742. * angular.module('do-check-module', [])
  6743. * .component('app', {
  6744. * template:
  6745. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6746. * 'Date: {{ $ctrl.date }}' +
  6747. * '<test date="$ctrl.date"></test>',
  6748. * controller: function() {
  6749. * this.date = new Date();
  6750. * this.month = this.date.getMonth();
  6751. * this.updateDate = function() {
  6752. * this.date.setMonth(this.month);
  6753. * };
  6754. * }
  6755. * })
  6756. * .component('test', {
  6757. * bindings: { date: '<' },
  6758. * template:
  6759. * '<pre>{{ $ctrl.log | json }}</pre>',
  6760. * controller: function() {
  6761. * var previousValue;
  6762. * this.log = [];
  6763. * this.$doCheck = function() {
  6764. * var currentValue = this.date && this.date.valueOf();
  6765. * if (previousValue !== currentValue) {
  6766. * this.log.push('doCheck: date mutated: ' + this.date);
  6767. * previousValue = currentValue;
  6768. * }
  6769. * };
  6770. * }
  6771. * });
  6772. * </file>
  6773. * <file name="index.html">
  6774. * <app></app>
  6775. * </file>
  6776. * </example>
  6777. *
  6778. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6779. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6780. * arrays or objects can have a negative impact on your application performance.)
  6781. *
  6782. * <example name="doCheckArrayExample" module="do-check-module">
  6783. * <file name="index.html">
  6784. * <div ng-init="items = []">
  6785. * <button ng-click="items.push(items.length)">Add Item</button>
  6786. * <button ng-click="items = []">Reset Items</button>
  6787. * <pre>{{ items }}</pre>
  6788. * <test items="items"></test>
  6789. * </div>
  6790. * </file>
  6791. * <file name="app.js">
  6792. * angular.module('do-check-module', [])
  6793. * .component('test', {
  6794. * bindings: { items: '<' },
  6795. * template:
  6796. * '<pre>{{ $ctrl.log | json }}</pre>',
  6797. * controller: function() {
  6798. * this.log = [];
  6799. *
  6800. * this.$doCheck = function() {
  6801. * if (this.items_ref !== this.items) {
  6802. * this.log.push('doCheck: items changed');
  6803. * this.items_ref = this.items;
  6804. * }
  6805. * if (!angular.equals(this.items_clone, this.items)) {
  6806. * this.log.push('doCheck: items mutated');
  6807. * this.items_clone = angular.copy(this.items);
  6808. * }
  6809. * };
  6810. * }
  6811. * });
  6812. * </file>
  6813. * </example>
  6814. *
  6815. *
  6816. * ### Directive Definition Object
  6817. *
  6818. * The directive definition object provides instructions to the {@link ng.$compile
  6819. * compiler}. The attributes are:
  6820. *
  6821. * #### `multiElement`
  6822. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6823. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6824. * together as the directive elements. It is recommended that this feature be used on directives
  6825. * which are not strictly behavioral (such as {@link ngClick}), and which
  6826. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6827. *
  6828. * #### `priority`
  6829. * When there are multiple directives defined on a single DOM element, sometimes it
  6830. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6831. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6832. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6833. * are also run in priority order, but post-link functions are run in reverse order. The order
  6834. * of directives with the same priority is undefined. The default priority is `0`.
  6835. *
  6836. * #### `terminal`
  6837. * If set to true then the current `priority` will be the last set of directives
  6838. * which will execute (any directives at the current priority will still execute
  6839. * as the order of execution on same `priority` is undefined). Note that expressions
  6840. * and other directives used in the directive's template will also be excluded from execution.
  6841. *
  6842. * #### `scope`
  6843. * The scope property can be `false`, `true`, or an object:
  6844. *
  6845. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6846. * parent's scope.
  6847. *
  6848. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6849. * the directive's element. If multiple directives on the same element request a new scope,
  6850. * only one new scope is created.
  6851. *
  6852. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6853. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6854. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6855. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6856. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6857. * to its children elements.
  6858. *
  6859. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6860. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6861. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6862. * is bound to the parent scope, via matching attributes on the directive's element:
  6863. *
  6864. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6865. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6866. * attribute name is assumed to be the same as the local name. Given `<my-component
  6867. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6868. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6869. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6870. * scope. The `name` is read from the parent scope (not the directive's scope).
  6871. *
  6872. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6873. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6874. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6875. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6876. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6877. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6878. * `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute
  6879. * isn't optional and doesn't exist, an exception
  6880. * ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes
  6881. * to the local value, since it will be impossible to sync them back to the parent scope.
  6882. *
  6883. * By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6884. * method is used for tracking changes, and the equality check is based on object identity.
  6885. * However, if an object literal or an array literal is passed as the binding expression, the
  6886. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6887. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6888. * `$watchCollection`}: use `=*` or `=*attr`
  6889. *
  6890. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6891. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6892. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6893. * local name.
  6894. *
  6895. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6896. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6897. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6898. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6899. * two caveats:
  6900. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6901. * sets the same value. That means if your bound value is an object, changes to its properties
  6902. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6903. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6904. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6905. * to the value has changed. In most cases, this should not be of concern, but can be important
  6906. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6907. * If you now change a property of the object in your parent scope, the change will not be
  6908. * propagated to the isolated scope, because the identity of the object on the parent scope
  6909. * has not changed. Instead you must assign a new object.
  6910. *
  6911. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6912. * back to the parent. However, it does not make this completely impossible.
  6913. *
  6914. * By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6915. * method is used for tracking changes, and the equality check is based on object identity.
  6916. * It's also possible to watch the evaluated value shallowly with
  6917. * {@link ng.$rootScope.Scope#$watchCollection `$watchCollection`}: use `<*` or `<*attr`
  6918. *
  6919. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6920. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6921. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6922. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6923. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6924. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6925. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6926. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6927. *
  6928. * All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression.
  6929. * The marker must come after the mode and before the attribute name.
  6930. * See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples.
  6931. * This is useful to refine the interface directives provide.
  6932. * One subtle difference between optional and non-optional happens **when the binding attribute is not
  6933. * set**:
  6934. * - the binding is optional: the property will not be defined
  6935. * - the binding is not optional: the property is defined
  6936. *
  6937. * ```js
  6938. *app.directive('testDir', function() {
  6939. return {
  6940. scope: {
  6941. notoptional: '=',
  6942. optional: '=?',
  6943. },
  6944. bindToController: true,
  6945. controller: function() {
  6946. this.$onInit = function() {
  6947. console.log(this.hasOwnProperty('notoptional')) // true
  6948. console.log(this.hasOwnProperty('optional')) // false
  6949. }
  6950. }
  6951. }
  6952. })
  6953. *```
  6954. *
  6955. *
  6956. * ##### Combining directives with different scope defintions
  6957. *
  6958. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6959. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6960. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6961. *
  6962. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6963. * * **child scope** + **no scope** => Both directives will share one single child scope
  6964. * * **child scope** + **child scope** => Both directives will share one single child scope
  6965. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6966. * its parent's scope
  6967. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6968. * be applied to the same element.
  6969. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6970. * cannot be applied to the same element.
  6971. *
  6972. *
  6973. * #### `bindToController`
  6974. * This property is used to bind scope properties directly to the controller. It can be either
  6975. * `true` or an object hash with the same format as the `scope` property.
  6976. *
  6977. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6978. * allow a component to have its properties bound to the controller, rather than to scope.
  6979. *
  6980. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6981. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6982. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6983. * initialized.
  6984. *
  6985. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6986. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6987. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6988. * scope (useful for component directives).
  6989. *
  6990. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6991. *
  6992. *
  6993. * #### `controller`
  6994. * Controller constructor function. The controller is instantiated before the
  6995. * pre-linking phase and can be accessed by other directives (see
  6996. * `require` attribute). This allows the directives to communicate with each other and augment
  6997. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6998. *
  6999. * * `$scope` - Current scope associated with the element
  7000. * * `$element` - Current element
  7001. * * `$attrs` - Current attributes object for the element
  7002. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  7003. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  7004. * * `scope`: (optional) override the scope.
  7005. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  7006. * * `futureParentElement` (optional):
  7007. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  7008. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  7009. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  7010. * and when the `cloneLinkingFn` is passed,
  7011. * as those elements need to created and cloned in a special way when they are defined outside their
  7012. * usual containers (e.g. like `<svg>`).
  7013. * * See also the `directive.templateNamespace` property.
  7014. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  7015. * then the default transclusion is provided.
  7016. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  7017. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  7018. *
  7019. * #### `require`
  7020. * Require another directive and inject its controller as the fourth argument to the linking function. The
  7021. * `require` property can be a string, an array or an object:
  7022. * * a **string** containing the name of the directive to pass to the linking function
  7023. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  7024. * linking function will be an array of controllers in the same order as the names in the `require` property
  7025. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  7026. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  7027. * controllers.
  7028. *
  7029. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  7030. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  7031. * have been constructed but before `$onInit` is called.
  7032. * If the name of the required controller is the same as the local name (the key), the name can be
  7033. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  7034. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  7035. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  7036. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  7037. * controller, in which case error checking is skipped). The name can be prefixed with:
  7038. *
  7039. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  7040. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  7041. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  7042. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  7043. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  7044. * `null` to the `link` fn if not found.
  7045. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  7046. * `null` to the `link` fn if not found.
  7047. *
  7048. *
  7049. * #### `controllerAs`
  7050. * Identifier name for a reference to the controller in the directive's scope.
  7051. * This allows the controller to be referenced from the directive template. This is especially
  7052. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  7053. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  7054. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  7055. *
  7056. *
  7057. * #### `restrict`
  7058. * String of subset of `EACM` which restricts the directive to a specific directive
  7059. * declaration style. If omitted, the defaults (elements and attributes) are used.
  7060. *
  7061. * * `E` - Element name (default): `<my-directive></my-directive>`
  7062. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  7063. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  7064. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  7065. *
  7066. *
  7067. * #### `templateNamespace`
  7068. * String representing the document type used by the markup in the template.
  7069. * AngularJS needs this information as those elements need to be created and cloned
  7070. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  7071. *
  7072. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  7073. * top-level elements such as `<svg>` or `<math>`.
  7074. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  7075. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  7076. *
  7077. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  7078. *
  7079. * #### `template`
  7080. * HTML markup that may:
  7081. * * Replace the contents of the directive's element (default).
  7082. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  7083. * * Wrap the contents of the directive's element (if `transclude` is true).
  7084. *
  7085. * Value may be:
  7086. *
  7087. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  7088. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  7089. * function api below) and returns a string value.
  7090. *
  7091. *
  7092. * #### `templateUrl`
  7093. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  7094. *
  7095. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  7096. * for later when the template has been resolved. In the meantime it will continue to compile and link
  7097. * sibling and parent elements as though this element had not contained any directives.
  7098. *
  7099. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  7100. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  7101. * case when only one deeply nested directive has `templateUrl`.
  7102. *
  7103. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}.
  7104. *
  7105. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  7106. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  7107. * a string value representing the url. In either case, the template URL is passed through {@link
  7108. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  7109. *
  7110. *
  7111. * #### `replace`
  7112. * <div class="alert alert-danger">
  7113. * **Note:** `replace` is deprecated in AngularJS and has been removed in the new Angular (v2+).
  7114. * </div>
  7115. *
  7116. * Specifies what the template should replace. Defaults to `false`.
  7117. *
  7118. * * `true` - the template will replace the directive's element.
  7119. * * `false` - the template will replace the contents of the directive's element.
  7120. *
  7121. * The replacement process migrates all of the attributes / classes from the old element to the new
  7122. * one. See the {@link guide/directive#template-expanding-directive
  7123. * Directives Guide} for an example.
  7124. *
  7125. * There are very few scenarios where element replacement is required for the application function,
  7126. * the main one being reusable custom components that are used within SVG contexts
  7127. * (because SVG doesn't work with custom elements in the DOM tree).
  7128. *
  7129. * #### `transclude`
  7130. * Extract the contents of the element where the directive appears and make it available to the directive.
  7131. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  7132. * {@link $compile#transclusion Transclusion} section below.
  7133. *
  7134. *
  7135. * #### `compile`
  7136. *
  7137. * ```js
  7138. * function compile(tElement, tAttrs, transclude) { ... }
  7139. * ```
  7140. *
  7141. * The compile function deals with transforming the template DOM. Since most directives do not do
  7142. * template transformation, it is not used often. The compile function takes the following arguments:
  7143. *
  7144. * * `tElement` - template element - The element where the directive has been declared. It is
  7145. * safe to do template transformation on the element and child elements only.
  7146. *
  7147. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  7148. * between all directive compile functions.
  7149. *
  7150. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  7151. *
  7152. * <div class="alert alert-warning">
  7153. * **Note:** The template instance and the link instance may be different objects if the template has
  7154. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  7155. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  7156. * should be done in a linking function rather than in a compile function.
  7157. * </div>
  7158. * <div class="alert alert-warning">
  7159. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  7160. * own templates or compile functions. Compiling these directives results in an infinite loop and
  7161. * stack overflow errors.
  7162. *
  7163. * This can be avoided by manually using `$compile` in the postLink function to imperatively compile
  7164. * a directive's template instead of relying on automatic template compilation via `template` or
  7165. * `templateUrl` declaration or manual compilation inside the compile function.
  7166. * </div>
  7167. *
  7168. * <div class="alert alert-danger">
  7169. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  7170. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  7171. * to the link function instead.
  7172. * </div>
  7173. * A compile function can have a return value which can be either a function or an object.
  7174. *
  7175. * * returning a (post-link) function - is equivalent to registering the linking function via the
  7176. * `link` property of the config object when the compile function is empty.
  7177. *
  7178. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  7179. * control when a linking function should be called during the linking phase. See info about
  7180. * pre-linking and post-linking functions below.
  7181. *
  7182. *
  7183. * #### `link`
  7184. * This property is used only if the `compile` property is not defined.
  7185. *
  7186. * ```js
  7187. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  7188. * ```
  7189. *
  7190. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  7191. * executed after the template has been cloned. This is where most of the directive logic will be
  7192. * put.
  7193. *
  7194. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  7195. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  7196. *
  7197. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  7198. * manipulate the children of the element only in `postLink` function since the children have
  7199. * already been linked.
  7200. *
  7201. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  7202. * between all directive linking functions.
  7203. *
  7204. * * `controller` - the directive's required controller instance(s) - Instances are shared
  7205. * among all directives, which allows the directives to use the controllers as a communication
  7206. * channel. The exact value depends on the directive's `require` property:
  7207. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  7208. * * `string`: the controller instance
  7209. * * `array`: array of controller instances
  7210. *
  7211. * If a required controller cannot be found, and it is optional, the instance is `null`,
  7212. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  7213. *
  7214. * Note that you can also require the directive's own controller - it will be made available like
  7215. * any other controller.
  7216. *
  7217. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  7218. * This is the same as the `$transclude` parameter of directive controllers,
  7219. * see {@link ng.$compile#-controller- the controller section for details}.
  7220. * `function([scope], cloneLinkingFn, futureParentElement)`.
  7221. *
  7222. * #### Pre-linking function
  7223. *
  7224. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  7225. * compiler linking function will fail to locate the correct elements for linking.
  7226. *
  7227. * #### Post-linking function
  7228. *
  7229. * Executed after the child elements are linked.
  7230. *
  7231. * Note that child elements that contain `templateUrl` directives will not have been compiled
  7232. * and linked since they are waiting for their template to load asynchronously and their own
  7233. * compilation and linking has been suspended until that occurs.
  7234. *
  7235. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  7236. * for their async templates to be resolved.
  7237. *
  7238. *
  7239. * ### Transclusion
  7240. *
  7241. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  7242. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  7243. * scope from where they were taken.
  7244. *
  7245. * Transclusion is used (often with {@link ngTransclude}) to insert the
  7246. * original contents of a directive's element into a specified place in the template of the directive.
  7247. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  7248. * content has access to the properties on the scope from which it was taken, even if the directive
  7249. * has isolated scope.
  7250. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  7251. *
  7252. * This makes it possible for the widget to have private state for its template, while the transcluded
  7253. * content has access to its originating scope.
  7254. *
  7255. * <div class="alert alert-warning">
  7256. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  7257. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  7258. * Testing Transclusion Directives}.
  7259. * </div>
  7260. *
  7261. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  7262. * directive's element, the entire element or multiple parts of the element contents:
  7263. *
  7264. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  7265. * * `'element'` - transclude the whole of the directive's element including any directives on this
  7266. * element that are defined at a lower priority than this directive. When used, the `template`
  7267. * property is ignored.
  7268. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  7269. *
  7270. * **Multi-slot transclusion** is declared by providing an object for the `transclude` property.
  7271. *
  7272. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  7273. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  7274. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  7275. *
  7276. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}.
  7277. *
  7278. * If the element selector is prefixed with a `?` then that slot is optional.
  7279. *
  7280. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  7281. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  7282. *
  7283. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  7284. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  7285. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  7286. * injectable into the directive's controller.
  7287. *
  7288. *
  7289. * #### Transclusion Functions
  7290. *
  7291. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  7292. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  7293. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  7294. *
  7295. * <div class="alert alert-info">
  7296. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  7297. * ngTransclude will deal with it for us.
  7298. * </div>
  7299. *
  7300. * If you want to manually control the insertion and removal of the transcluded content in your directive
  7301. * then you must use this transclude function. When you call a transclude function it returns a jqLite/JQuery
  7302. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  7303. *
  7304. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  7305. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  7306. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  7307. *
  7308. * <div class="alert alert-info">
  7309. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  7310. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  7311. * </div>
  7312. *
  7313. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  7314. * attach function**:
  7315. *
  7316. * ```js
  7317. * var transcludedContent, transclusionScope;
  7318. *
  7319. * $transclude(function(clone, scope) {
  7320. * element.append(clone);
  7321. * transcludedContent = clone;
  7322. * transclusionScope = scope;
  7323. * });
  7324. * ```
  7325. *
  7326. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  7327. * associated transclusion scope:
  7328. *
  7329. * ```js
  7330. * transcludedContent.remove();
  7331. * transclusionScope.$destroy();
  7332. * ```
  7333. *
  7334. * <div class="alert alert-info">
  7335. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7336. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7337. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7338. * </div>
  7339. *
  7340. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7341. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7342. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7343. *
  7344. *
  7345. * #### Transclusion Scopes
  7346. *
  7347. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7348. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7349. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7350. * was taken.
  7351. *
  7352. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7353. * like this:
  7354. *
  7355. * ```html
  7356. * <div ng-app>
  7357. * <div isolate>
  7358. * <div transclusion>
  7359. * </div>
  7360. * </div>
  7361. * </div>
  7362. * ```
  7363. *
  7364. * The `$parent` scope hierarchy will look like this:
  7365. *
  7366. ```
  7367. - $rootScope
  7368. - isolate
  7369. - transclusion
  7370. ```
  7371. *
  7372. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7373. *
  7374. ```
  7375. - $rootScope
  7376. - transclusion
  7377. - isolate
  7378. ```
  7379. *
  7380. *
  7381. * ### Attributes
  7382. *
  7383. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7384. * `link()` or `compile()` functions. It has a variety of uses.
  7385. *
  7386. * * *Accessing normalized attribute names:* Directives like `ngBind` can be expressed in many ways:
  7387. * `ng:bind`, `data-ng-bind`, or `x-ng-bind`. The attributes object allows for normalized access
  7388. * to the attributes.
  7389. *
  7390. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7391. * object which allows the directives to use the attributes object as inter directive
  7392. * communication.
  7393. *
  7394. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7395. * allowing other directives to read the interpolated value.
  7396. *
  7397. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7398. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7399. * the only way to easily get the actual value because during the linking phase the interpolation
  7400. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7401. *
  7402. * ```js
  7403. * function linkingFn(scope, elm, attrs, ctrl) {
  7404. * // get the attribute value
  7405. * console.log(attrs.ngModel);
  7406. *
  7407. * // change the attribute
  7408. * attrs.$set('ngModel', 'new value');
  7409. *
  7410. * // observe changes to interpolated attribute
  7411. * attrs.$observe('ngModel', function(value) {
  7412. * console.log('ngModel has changed value to ' + value);
  7413. * });
  7414. * }
  7415. * ```
  7416. *
  7417. * ## Example
  7418. *
  7419. * <div class="alert alert-warning">
  7420. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7421. * to illustrate how `$compile` works.
  7422. * </div>
  7423. *
  7424. <example module="compileExample" name="compile">
  7425. <file name="index.html">
  7426. <script>
  7427. angular.module('compileExample', [], function($compileProvider) {
  7428. // Configure new 'compile' directive by passing a directive
  7429. // factory function. The factory function injects '$compile'.
  7430. $compileProvider.directive('compile', function($compile) {
  7431. // The directive factory creates a link function.
  7432. return function(scope, element, attrs) {
  7433. scope.$watch(
  7434. function(scope) {
  7435. // Watch the 'compile' expression for changes.
  7436. return scope.$eval(attrs.compile);
  7437. },
  7438. function(value) {
  7439. // When the 'compile' expression changes
  7440. // assign it into the current DOM.
  7441. element.html(value);
  7442. // Compile the new DOM and link it to the current scope.
  7443. // NOTE: we only compile '.childNodes' so that we
  7444. // don't get into an infinite loop compiling ourselves.
  7445. $compile(element.contents())(scope);
  7446. }
  7447. );
  7448. };
  7449. });
  7450. })
  7451. .controller('GreeterController', ['$scope', function($scope) {
  7452. $scope.name = 'AngularJS';
  7453. $scope.html = 'Hello {{name}}';
  7454. }]);
  7455. </script>
  7456. <div ng-controller="GreeterController">
  7457. <input ng-model="name"> <br/>
  7458. <textarea ng-model="html"></textarea> <br/>
  7459. <div compile="html"></div>
  7460. </div>
  7461. </file>
  7462. <file name="protractor.js" type="protractor">
  7463. it('should auto compile', function() {
  7464. var textarea = $('textarea');
  7465. var output = $('div[compile]');
  7466. // The initial state reads 'Hello AngularJS'.
  7467. expect(output.getText()).toBe('Hello AngularJS');
  7468. textarea.clear();
  7469. textarea.sendKeys('{{name}}!');
  7470. expect(output.getText()).toBe('AngularJS!');
  7471. });
  7472. </file>
  7473. </example>
  7474. *
  7475. *
  7476. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7477. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7478. *
  7479. * <div class="alert alert-danger">
  7480. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7481. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7482. * `parentBoundTranscludeFn` to the link function instead.
  7483. * </div>
  7484. *
  7485. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7486. * root element(s), not their children)
  7487. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7488. * (a DOM element/tree) to a scope. Where:
  7489. *
  7490. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7491. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7492. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7493. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7494. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7495. *
  7496. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7497. * * `scope` - is the current scope with which the linking function is working with.
  7498. *
  7499. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7500. * keys may be used to control linking behavior:
  7501. *
  7502. * * `parentBoundTranscludeFn` - the transclude function made available to
  7503. * directives; if given, it will be passed through to the link functions of
  7504. * directives found in `element` during compilation.
  7505. * * `transcludeControllers` - an object hash with keys that map controller names
  7506. * to a hash with the key `instance`, which maps to the controller instance;
  7507. * if given, it will make the controllers available to directives on the compileNode:
  7508. * ```
  7509. * {
  7510. * parent: {
  7511. * instance: parentControllerInstance
  7512. * }
  7513. * }
  7514. * ```
  7515. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7516. * the cloned elements; only needed for transcludes that are allowed to contain non HTML
  7517. * elements (e.g. SVG elements). See also the `directive.controller` property.
  7518. *
  7519. * Calling the linking function returns the element of the template. It is either the original
  7520. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7521. *
  7522. * After linking the view is not updated until after a call to `$digest`, which typically is done by
  7523. * AngularJS automatically.
  7524. *
  7525. * If you need access to the bound view, there are two ways to do it:
  7526. *
  7527. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7528. * before you send them to the compiler and keep this reference around.
  7529. * ```js
  7530. * var element = angular.element('<p>{{total}}</p>');
  7531. * $compile(element)(scope);
  7532. * ```
  7533. *
  7534. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7535. * example would not point to the clone, but rather to the original template that was cloned. In
  7536. * this case, you can access the clone either via the `cloneAttachFn` or the value returned by the
  7537. * linking function:
  7538. * ```js
  7539. * var templateElement = angular.element('<p>{{total}}</p>');
  7540. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7541. * // Attach the clone to DOM document at the right place.
  7542. * });
  7543. *
  7544. * // Now we have reference to the cloned DOM via `clonedElement`.
  7545. * // NOTE: The `clonedElement` returned by the linking function is the same as the
  7546. * // `clonedElement` passed to `cloneAttachFn`.
  7547. * ```
  7548. *
  7549. *
  7550. * For information on how the compiler works, see the
  7551. * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide.
  7552. *
  7553. * @knownIssue
  7554. *
  7555. * ### Double Compilation
  7556. *
  7557. Double compilation occurs when an already compiled part of the DOM gets
  7558. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7559. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7560. section on double compilation} for an in-depth explanation and ways to avoid it.
  7561. * @knownIssue
  7562. ### Issues with `replace: true`
  7563. *
  7564. * <div class="alert alert-danger">
  7565. * **Note**: {@link $compile#-replace- `replace: true`} is deprecated and not recommended to use,
  7566. * mainly due to the issues listed here. It has been completely removed in the new Angular.
  7567. * </div>
  7568. *
  7569. * #### Attribute values are not merged
  7570. *
  7571. * When a `replace` directive encounters the same attribute on the original and the replace node,
  7572. * it will simply deduplicate the attribute and join the values with a space or with a `;` in case of
  7573. * the `style` attribute.
  7574. * ```html
  7575. * Original Node: <span class="original" style="color: red;"></span>
  7576. * Replace Template: <span class="replaced" style="background: blue;"></span>
  7577. * Result: <span class="original replaced" style="color: red; background: blue;"></span>
  7578. * ```
  7579. *
  7580. * That means attributes that contain AngularJS expressions will not be merged correctly, e.g.
  7581. * {@link ngShow} or {@link ngClass} will cause a {@link $parse} error:
  7582. *
  7583. * ```html
  7584. * Original Node: <span ng-class="{'something': something}" ng-show="!condition"></span>
  7585. * Replace Template: <span ng-class="{'else': else}" ng-show="otherCondition"></span>
  7586. * Result: <span ng-class="{'something': something} {'else': else}" ng-show="!condition otherCondition"></span>
  7587. * ```
  7588. *
  7589. * See issue [#5695](https://github.com/angular/angular.js/issues/5695).
  7590. *
  7591. * #### Directives are not deduplicated before compilation
  7592. *
  7593. * When the original node and the replace template declare the same directive(s), they will be
  7594. * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler
  7595. * does not deduplicate them. In many cases, this is not noticeable, but e.g. {@link ngModel} will
  7596. * attach `$formatters` and `$parsers` twice.
  7597. *
  7598. * See issue [#2573](https://github.com/angular/angular.js/issues/2573).
  7599. *
  7600. * #### `transclude: element` in the replace template root can have unexpected effects
  7601. *
  7602. * When the replace template has a directive at the root node that uses
  7603. * {@link $compile#-transclude- `transclude: element`}, e.g.
  7604. * {@link ngIf} or {@link ngRepeat}, the DOM structure or scope inheritance can be incorrect.
  7605. * See the following issues:
  7606. *
  7607. * - Incorrect scope on replaced element:
  7608. * [#9837](https://github.com/angular/angular.js/issues/9837)
  7609. * - Different DOM between `template` and `templateUrl`:
  7610. * [#10612](https://github.com/angular/angular.js/issues/14326)
  7611. *
  7612. */
  7613. /**
  7614. * @ngdoc directive
  7615. * @name ngProp
  7616. * @restrict A
  7617. * @element ANY
  7618. *
  7619. * @usage
  7620. *
  7621. * ```html
  7622. * <ANY ng-prop-propname="expression">
  7623. * </ANY>
  7624. * ```
  7625. *
  7626. * or with uppercase letters in property (e.g. "propName"):
  7627. *
  7628. *
  7629. * ```html
  7630. * <ANY ng-prop-prop_name="expression">
  7631. * </ANY>
  7632. * ```
  7633. *
  7634. *
  7635. * @description
  7636. * The `ngProp` directive binds an expression to a DOM element property.
  7637. * `ngProp` allows writing to arbitrary properties by including
  7638. * the property name in the attribute, e.g. `ng-prop-value="'my value'"` binds 'my value' to
  7639. * the `value` property.
  7640. *
  7641. * Usually, it's not necessary to write to properties in AngularJS, as the built-in directives
  7642. * handle the most common use cases (instead of the above example, you would use {@link ngValue}).
  7643. *
  7644. * However, [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements)
  7645. * often use custom properties to hold data, and `ngProp` can be used to provide input to these
  7646. * custom elements.
  7647. *
  7648. * ## Binding to camelCase properties
  7649. *
  7650. * Since HTML attributes are case-insensitive, camelCase properties like `innerHTML` must be escaped.
  7651. * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so
  7652. * `innerHTML` must be written as `ng-prop-inner_h_t_m_l="expression"` (Note that this is just an
  7653. * example, and for binding HTML {@link ngBindHtml} should be used.
  7654. *
  7655. * ## Security
  7656. *
  7657. * Binding expressions to arbitrary properties poses a security risk, as properties like `innerHTML`
  7658. * can insert potentially dangerous HTML into the application, e.g. script tags that execute
  7659. * malicious code.
  7660. * For this reason, `ngProp` applies Strict Contextual Escaping with the {@link ng.$sce $sce service}.
  7661. * This means vulnerable properties require their content to be "trusted", based on the
  7662. * context of the property. For example, the `innerHTML` is in the `HTML` context, and the
  7663. * `iframe.src` property is in the `RESOURCE_URL` context, which requires that values written to
  7664. * this property are trusted as a `RESOURCE_URL`.
  7665. *
  7666. * This can be set explicitly by calling $sce.trustAs(type, value) on the value that is
  7667. * trusted before passing it to the `ng-prop-*` directive. There are exist shorthand methods for
  7668. * each context type in the form of {@link ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl()} et al.
  7669. *
  7670. * In some cases you can also rely upon automatic sanitization of untrusted values - see below.
  7671. *
  7672. * Based on the context, other options may exist to mark a value as trusted / configure the behavior
  7673. * of {@link ng.$sce}. For example, to restrict the `RESOURCE_URL` context to specific origins, use
  7674. * the {@link $sceDelegateProvider#trustedResourceUrlList trustedResourceUrlList()}
  7675. * and {@link $sceDelegateProvider#bannedResourceUrlList bannedResourceUrlList()}.
  7676. *
  7677. * {@link ng.$sce#what-trusted-context-types-are-supported- Find out more about the different context types}.
  7678. *
  7679. * ### HTML Sanitization
  7680. *
  7681. * By default, `$sce` will throw an error if it detects untrusted HTML content, and will not bind the
  7682. * content.
  7683. * However, if you include the {@link ngSanitize ngSanitize module}, it will try to sanitize the
  7684. * potentially dangerous HTML, e.g. strip non-trusted tags and attributes when binding to
  7685. * `innerHTML`.
  7686. *
  7687. * @example
  7688. * ### Binding to different contexts
  7689. *
  7690. * <example name="ngProp" module="exampleNgProp">
  7691. * <file name="app.js">
  7692. * angular.module('exampleNgProp', [])
  7693. * .component('main', {
  7694. * templateUrl: 'main.html',
  7695. * controller: function($sce) {
  7696. * this.safeContent = '<strong>Safe content</strong>';
  7697. * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>';
  7698. * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);
  7699. * }
  7700. * });
  7701. * </file>
  7702. * <file name="main.html">
  7703. * <div>
  7704. * <div class="prop-unit">
  7705. * Binding to a property without security context:
  7706. * <div class="prop-binding" ng-prop-inner_text="$ctrl.safeContent"></div>
  7707. * <span class="prop-note">innerText</span> (safeContent)
  7708. * </div>
  7709. *
  7710. * <div class="prop-unit">
  7711. * "Safe" content that requires a security context will throw because the contents could potentially be dangerous ...
  7712. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div>
  7713. * <span class="prop-note">innerHTML</span> (safeContent)
  7714. * </div>
  7715. *
  7716. * <div class="prop-unit">
  7717. * ... so that actually dangerous content cannot be executed:
  7718. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div>
  7719. * <span class="prop-note">innerHTML</span> (unsafeContent)
  7720. * </div>
  7721. *
  7722. * <div class="prop-unit">
  7723. * ... but unsafe Content that has been trusted explicitly works - only do this if you are 100% sure!
  7724. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div>
  7725. * <span class="prop-note">innerHTML</span> (trustedUnsafeContent)
  7726. * </div>
  7727. * </div>
  7728. * </file>
  7729. * <file name="index.html">
  7730. * <main></main>
  7731. * </file>
  7732. * <file name="styles.css">
  7733. * .prop-unit {
  7734. * margin-bottom: 10px;
  7735. * }
  7736. *
  7737. * .prop-binding {
  7738. * min-height: 30px;
  7739. * border: 1px solid blue;
  7740. * }
  7741. *
  7742. * .prop-note {
  7743. * font-family: Monospace;
  7744. * }
  7745. * </file>
  7746. * </example>
  7747. *
  7748. *
  7749. * @example
  7750. * ### Binding to innerHTML with ngSanitize
  7751. *
  7752. * <example name="ngProp" module="exampleNgProp" deps="angular-sanitize.js">
  7753. * <file name="app.js">
  7754. * angular.module('exampleNgProp', ['ngSanitize'])
  7755. * .component('main', {
  7756. * templateUrl: 'main.html',
  7757. * controller: function($sce) {
  7758. * this.safeContent = '<strong>Safe content</strong>';
  7759. * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>';
  7760. * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);
  7761. * }
  7762. * });
  7763. * </file>
  7764. * <file name="main.html">
  7765. * <div>
  7766. * <div class="prop-unit">
  7767. * "Safe" content will be sanitized ...
  7768. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div>
  7769. * <span class="prop-note">innerHTML</span> (safeContent)
  7770. * </div>
  7771. *
  7772. * <div class="prop-unit">
  7773. * ... as will dangerous content:
  7774. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div>
  7775. * <span class="prop-note">innerHTML</span> (unsafeContent)
  7776. * </div>
  7777. *
  7778. * <div class="prop-unit">
  7779. * ... and content that has been trusted explicitly works the same as without ngSanitize:
  7780. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div>
  7781. * <span class="prop-note">innerHTML</span> (trustedUnsafeContent)
  7782. * </div>
  7783. * </div>
  7784. * </file>
  7785. * <file name="index.html">
  7786. * <main></main>
  7787. * </file>
  7788. * <file name="styles.css">
  7789. * .prop-unit {
  7790. * margin-bottom: 10px;
  7791. * }
  7792. *
  7793. * .prop-binding {
  7794. * min-height: 30px;
  7795. * border: 1px solid blue;
  7796. * }
  7797. *
  7798. * .prop-note {
  7799. * font-family: Monospace;
  7800. * }
  7801. * </file>
  7802. * </example>
  7803. *
  7804. */
  7805. /** @ngdoc directive
  7806. * @name ngOn
  7807. * @restrict A
  7808. * @element ANY
  7809. *
  7810. * @usage
  7811. *
  7812. * ```html
  7813. * <ANY ng-on-eventname="expression">
  7814. * </ANY>
  7815. * ```
  7816. *
  7817. * or with uppercase letters in property (e.g. "eventName"):
  7818. *
  7819. *
  7820. * ```html
  7821. * <ANY ng-on-event_name="expression">
  7822. * </ANY>
  7823. * ```
  7824. *
  7825. * @description
  7826. * The `ngOn` directive adds an event listener to a DOM element via
  7827. * {@link angular.element angular.element().on()}, and evaluates an expression when the event is
  7828. * fired.
  7829. * `ngOn` allows adding listeners for arbitrary events by including
  7830. * the event name in the attribute, e.g. `ng-on-drop="onDrop()"` executes the 'onDrop()' expression
  7831. * when the `drop` event is fired.
  7832. *
  7833. * AngularJS provides specific directives for many events, such as {@link ngClick}, so in most
  7834. * cases it is not necessary to use `ngOn`. However, AngularJS does not support all events
  7835. * (e.g. the `drop` event in the example above), and new events might be introduced in later DOM
  7836. * standards.
  7837. *
  7838. * Another use-case for `ngOn` is listening to
  7839. * [custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
  7840. * fired by
  7841. * [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements).
  7842. *
  7843. * ## Binding to camelCase properties
  7844. *
  7845. * Since HTML attributes are case-insensitive, camelCase properties like `myEvent` must be escaped.
  7846. * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so
  7847. * `myEvent` must be written as `ng-on-my_event="expression"`.
  7848. *
  7849. * @example
  7850. * ### Bind to built-in DOM events
  7851. *
  7852. * <example name="ngOn" module="exampleNgOn">
  7853. * <file name="app.js">
  7854. * angular.module('exampleNgOn', [])
  7855. * .component('main', {
  7856. * templateUrl: 'main.html',
  7857. * controller: function() {
  7858. * this.clickCount = 0;
  7859. * this.mouseoverCount = 0;
  7860. *
  7861. * this.loadingState = 0;
  7862. * }
  7863. * });
  7864. * </file>
  7865. * <file name="main.html">
  7866. * <div>
  7867. * This is equivalent to `ngClick` and `ngMouseover`:<br>
  7868. * <button
  7869. * ng-on-click="$ctrl.clickCount = $ctrl.clickCount + 1"
  7870. * ng-on-mouseover="$ctrl.mouseoverCount = $ctrl.mouseoverCount + 1">Click or mouseover</button><br>
  7871. * clickCount: {{$ctrl.clickCount}}<br>
  7872. * mouseover: {{$ctrl.mouseoverCount}}
  7873. *
  7874. * <hr>
  7875. *
  7876. * For the `error` and `load` event on images no built-in AngularJS directives exist:<br>
  7877. * <img src="thisimagedoesnotexist.png" ng-on-error="$ctrl.loadingState = -1" ng-on-load="$ctrl.loadingState = 1"><br>
  7878. * <div ng-switch="$ctrl.loadingState">
  7879. * <span ng-switch-when="0">Image is loading</span>
  7880. * <span ng-switch-when="-1">Image load error</span>
  7881. * <span ng-switch-when="1">Image loaded successfully</span>
  7882. * </div>
  7883. * </div>
  7884. * </file>
  7885. * <file name="index.html">
  7886. * <main></main>
  7887. * </file>
  7888. * </example>
  7889. *
  7890. *
  7891. * @example
  7892. * ### Bind to custom DOM events
  7893. *
  7894. * <example name="ngOnCustom" module="exampleNgOn">
  7895. * <file name="app.js">
  7896. * angular.module('exampleNgOn', [])
  7897. * .component('main', {
  7898. * templateUrl: 'main.html',
  7899. * controller: function() {
  7900. * this.eventLog = '';
  7901. *
  7902. * this.listener = function($event) {
  7903. * this.eventLog = 'Event with type "' + $event.type + '" fired at ' + $event.detail;
  7904. * };
  7905. * }
  7906. * })
  7907. * .component('childComponent', {
  7908. * templateUrl: 'child.html',
  7909. * controller: function($element) {
  7910. * this.fireEvent = function() {
  7911. * var event = new CustomEvent('customtype', { detail: new Date()});
  7912. *
  7913. * $element[0].dispatchEvent(event);
  7914. * };
  7915. * }
  7916. * });
  7917. * </file>
  7918. * <file name="main.html">
  7919. * <child-component ng-on-customtype="$ctrl.listener($event)"></child-component><br>
  7920. * <span>Event log: {{$ctrl.eventLog}}</span>
  7921. * </file>
  7922. * <file name="child.html">
  7923. <button ng-click="$ctrl.fireEvent()">Fire custom event</button>
  7924. * </file>
  7925. * <file name="index.html">
  7926. * <main></main>
  7927. * </file>
  7928. * </example>
  7929. */
  7930. var $compileMinErr = minErr('$compile');
  7931. function UNINITIALIZED_VALUE() {}
  7932. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7933. /**
  7934. * @ngdoc provider
  7935. * @name $compileProvider
  7936. *
  7937. * @description
  7938. */
  7939. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7940. /** @this */
  7941. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7942. var hasDirectives = {},
  7943. Suffix = 'Directive',
  7944. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7945. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7946. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7947. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7948. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7949. // The assumption is that future DOM event attribute names will begin with
  7950. // 'on' and be composed of only English letters.
  7951. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7952. var bindingCache = createMap();
  7953. function parseIsolateBindings(scope, directiveName, isController) {
  7954. var LOCAL_REGEXP = /^([@&]|[=<](\*?))(\??)\s*([\w$]*)$/;
  7955. var bindings = createMap();
  7956. forEach(scope, function(definition, scopeName) {
  7957. definition = definition.trim();
  7958. if (definition in bindingCache) {
  7959. bindings[scopeName] = bindingCache[definition];
  7960. return;
  7961. }
  7962. var match = definition.match(LOCAL_REGEXP);
  7963. if (!match) {
  7964. throw $compileMinErr('iscp',
  7965. 'Invalid {3} for directive \'{0}\'.' +
  7966. ' Definition: {... {1}: \'{2}\' ...}',
  7967. directiveName, scopeName, definition,
  7968. (isController ? 'controller bindings definition' :
  7969. 'isolate scope definition'));
  7970. }
  7971. bindings[scopeName] = {
  7972. mode: match[1][0],
  7973. collection: match[2] === '*',
  7974. optional: match[3] === '?',
  7975. attrName: match[4] || scopeName
  7976. };
  7977. if (match[4]) {
  7978. bindingCache[definition] = bindings[scopeName];
  7979. }
  7980. });
  7981. return bindings;
  7982. }
  7983. function parseDirectiveBindings(directive, directiveName) {
  7984. var bindings = {
  7985. isolateScope: null,
  7986. bindToController: null
  7987. };
  7988. if (isObject(directive.scope)) {
  7989. if (directive.bindToController === true) {
  7990. bindings.bindToController = parseIsolateBindings(directive.scope,
  7991. directiveName, true);
  7992. bindings.isolateScope = {};
  7993. } else {
  7994. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7995. directiveName, false);
  7996. }
  7997. }
  7998. if (isObject(directive.bindToController)) {
  7999. bindings.bindToController =
  8000. parseIsolateBindings(directive.bindToController, directiveName, true);
  8001. }
  8002. if (bindings.bindToController && !directive.controller) {
  8003. // There is no controller
  8004. throw $compileMinErr('noctrl',
  8005. 'Cannot bind to controller without directive \'{0}\'s controller.',
  8006. directiveName);
  8007. }
  8008. return bindings;
  8009. }
  8010. function assertValidDirectiveName(name) {
  8011. var letter = name.charAt(0);
  8012. if (!letter || letter !== lowercase(letter)) {
  8013. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  8014. }
  8015. if (name !== name.trim()) {
  8016. throw $compileMinErr('baddir',
  8017. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  8018. name);
  8019. }
  8020. }
  8021. function getDirectiveRequire(directive) {
  8022. var require = directive.require || (directive.controller && directive.name);
  8023. if (!isArray(require) && isObject(require)) {
  8024. forEach(require, function(value, key) {
  8025. var match = value.match(REQUIRE_PREFIX_REGEXP);
  8026. var name = value.substring(match[0].length);
  8027. if (!name) require[key] = match[0] + key;
  8028. });
  8029. }
  8030. return require;
  8031. }
  8032. function getDirectiveRestrict(restrict, name) {
  8033. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  8034. throw $compileMinErr('badrestrict',
  8035. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  8036. restrict,
  8037. name);
  8038. }
  8039. return restrict || 'EA';
  8040. }
  8041. /**
  8042. * @ngdoc method
  8043. * @name $compileProvider#directive
  8044. * @kind function
  8045. *
  8046. * @description
  8047. * Register a new directive with the compiler.
  8048. *
  8049. * @param {string|Object} name Name of the directive in camel-case (i.e. `ngBind` which will match
  8050. * as `ng-bind`), or an object map of directives where the keys are the names and the values
  8051. * are the factories.
  8052. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  8053. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  8054. * @returns {ng.$compileProvider} Self for chaining.
  8055. */
  8056. this.directive = function registerDirective(name, directiveFactory) {
  8057. assertArg(name, 'name');
  8058. assertNotHasOwnProperty(name, 'directive');
  8059. if (isString(name)) {
  8060. assertValidDirectiveName(name);
  8061. assertArg(directiveFactory, 'directiveFactory');
  8062. if (!hasDirectives.hasOwnProperty(name)) {
  8063. hasDirectives[name] = [];
  8064. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  8065. function($injector, $exceptionHandler) {
  8066. var directives = [];
  8067. forEach(hasDirectives[name], function(directiveFactory, index) {
  8068. try {
  8069. var directive = $injector.invoke(directiveFactory);
  8070. if (isFunction(directive)) {
  8071. directive = { compile: valueFn(directive) };
  8072. } else if (!directive.compile && directive.link) {
  8073. directive.compile = valueFn(directive.link);
  8074. }
  8075. directive.priority = directive.priority || 0;
  8076. directive.index = index;
  8077. directive.name = directive.name || name;
  8078. directive.require = getDirectiveRequire(directive);
  8079. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  8080. directive.$$moduleName = directiveFactory.$$moduleName;
  8081. directives.push(directive);
  8082. } catch (e) {
  8083. $exceptionHandler(e);
  8084. }
  8085. });
  8086. return directives;
  8087. }]);
  8088. }
  8089. hasDirectives[name].push(directiveFactory);
  8090. } else {
  8091. forEach(name, reverseParams(registerDirective));
  8092. }
  8093. return this;
  8094. };
  8095. /**
  8096. * @ngdoc method
  8097. * @name $compileProvider#component
  8098. * @module ng
  8099. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  8100. * or an object map of components where the keys are the names and the values are the component definition objects.
  8101. * @param {Object} options Component definition object (a simplified
  8102. * {@link ng.$compile#directive-definition-object directive definition object}),
  8103. * with the following properties (all optional):
  8104. *
  8105. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  8106. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  8107. * registered controller} if passed as a string. An empty `noop` function by default.
  8108. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  8109. * If present, the controller will be published to scope under the `controllerAs` name.
  8110. * If not present, this will default to be `$ctrl`.
  8111. * - `template` – `{string=|function()=}` – html template as a string or a function that
  8112. * returns an html template as a string which should be used as the contents of this component.
  8113. * Empty string by default.
  8114. *
  8115. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  8116. * the following locals:
  8117. *
  8118. * - `$element` - Current element
  8119. * - `$attrs` - Current attributes object for the element
  8120. *
  8121. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  8122. * template that should be used as the contents of this component.
  8123. *
  8124. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  8125. * the following locals:
  8126. *
  8127. * - `$element` - Current element
  8128. * - `$attrs` - Current attributes object for the element
  8129. *
  8130. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  8131. * Component properties are always bound to the component controller and not to the scope.
  8132. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  8133. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  8134. * Disabled by default.
  8135. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  8136. * this component's controller. The object keys specify the property names under which the required
  8137. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  8138. * - `$...` – additional properties to attach to the directive factory function and the controller
  8139. * constructor function. (This is used by the component router to annotate)
  8140. *
  8141. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  8142. * @description
  8143. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  8144. * type of directive, which represents a self-contained UI component in your application. Such components
  8145. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  8146. *
  8147. * Component definitions are very simple and do not require as much configuration as defining general
  8148. * directives. Component definitions usually consist only of a template and a controller backing it.
  8149. *
  8150. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  8151. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  8152. *
  8153. * Here are a few examples of how you would usually define components:
  8154. *
  8155. * ```js
  8156. * var myMod = angular.module(...);
  8157. * myMod.component('myComp', {
  8158. * template: '<div>My name is {{$ctrl.name}}</div>',
  8159. * controller: function() {
  8160. * this.name = 'shahar';
  8161. * }
  8162. * });
  8163. *
  8164. * myMod.component('myComp', {
  8165. * template: '<div>My name is {{$ctrl.name}}</div>',
  8166. * bindings: {name: '@'}
  8167. * });
  8168. *
  8169. * myMod.component('myComp', {
  8170. * templateUrl: 'views/my-comp.html',
  8171. * controller: 'MyCtrl',
  8172. * controllerAs: 'ctrl',
  8173. * bindings: {name: '@'}
  8174. * });
  8175. *
  8176. * ```
  8177. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  8178. *
  8179. * <br />
  8180. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  8181. */
  8182. this.component = function registerComponent(name, options) {
  8183. if (!isString(name)) {
  8184. forEach(name, reverseParams(bind(this, registerComponent)));
  8185. return this;
  8186. }
  8187. var controller = options.controller || function() {};
  8188. function factory($injector) {
  8189. function makeInjectable(fn) {
  8190. if (isFunction(fn) || isArray(fn)) {
  8191. return /** @this */ function(tElement, tAttrs) {
  8192. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  8193. };
  8194. } else {
  8195. return fn;
  8196. }
  8197. }
  8198. var template = (!options.template && !options.templateUrl ? '' : options.template);
  8199. var ddo = {
  8200. controller: controller,
  8201. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  8202. template: makeInjectable(template),
  8203. templateUrl: makeInjectable(options.templateUrl),
  8204. transclude: options.transclude,
  8205. scope: {},
  8206. bindToController: options.bindings || {},
  8207. restrict: 'E',
  8208. require: options.require
  8209. };
  8210. // Copy annotations (starting with $) over to the DDO
  8211. forEach(options, function(val, key) {
  8212. if (key.charAt(0) === '$') ddo[key] = val;
  8213. });
  8214. return ddo;
  8215. }
  8216. // TODO(pete) remove the following `forEach` before we release 1.6.0
  8217. // The component-router@0.2.0 looks for the annotations on the controller constructor
  8218. // Nothing in AngularJS looks for annotations on the factory function but we can't remove
  8219. // it from 1.5.x yet.
  8220. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  8221. // These could be used by libraries such as the new component router
  8222. forEach(options, function(val, key) {
  8223. if (key.charAt(0) === '$') {
  8224. factory[key] = val;
  8225. // Don't try to copy over annotations to named controller
  8226. if (isFunction(controller)) controller[key] = val;
  8227. }
  8228. });
  8229. factory.$inject = ['$injector'];
  8230. return this.directive(name, factory);
  8231. };
  8232. /**
  8233. * @ngdoc method
  8234. * @name $compileProvider#aHrefSanitizationTrustedUrlList
  8235. * @kind function
  8236. *
  8237. * @description
  8238. * Retrieves or overrides the default regular expression that is used for determining trusted safe
  8239. * urls during a[href] sanitization.
  8240. *
  8241. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  8242. *
  8243. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  8244. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationTrustedUrlList`
  8245. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  8246. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  8247. *
  8248. * @param {RegExp=} regexp New regexp to trust urls with.
  8249. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  8250. * chaining otherwise.
  8251. */
  8252. this.aHrefSanitizationTrustedUrlList = function(regexp) {
  8253. if (isDefined(regexp)) {
  8254. $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList(regexp);
  8255. return this;
  8256. } else {
  8257. return $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList();
  8258. }
  8259. };
  8260. /**
  8261. * @ngdoc method
  8262. * @name $compileProvider#aHrefSanitizationWhitelist
  8263. * @kind function
  8264. *
  8265. * @deprecated
  8266. * sinceVersion="1.8.1"
  8267. *
  8268. * This method is deprecated. Use {@link $compileProvider#aHrefSanitizationTrustedUrlList
  8269. * aHrefSanitizationTrustedUrlList} instead.
  8270. */
  8271. Object.defineProperty(this, 'aHrefSanitizationWhitelist', {
  8272. get: function() {
  8273. return this.aHrefSanitizationTrustedUrlList;
  8274. },
  8275. set: function(value) {
  8276. this.aHrefSanitizationTrustedUrlList = value;
  8277. }
  8278. });
  8279. /**
  8280. * @ngdoc method
  8281. * @name $compileProvider#imgSrcSanitizationTrustedUrlList
  8282. * @kind function
  8283. *
  8284. * @description
  8285. * Retrieves or overrides the default regular expression that is used for determining trusted safe
  8286. * urls during img[src] sanitization.
  8287. *
  8288. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  8289. *
  8290. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  8291. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationTrustedUrlList`
  8292. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  8293. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  8294. *
  8295. * @param {RegExp=} regexp New regexp to trust urls with.
  8296. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  8297. * chaining otherwise.
  8298. */
  8299. this.imgSrcSanitizationTrustedUrlList = function(regexp) {
  8300. if (isDefined(regexp)) {
  8301. $$sanitizeUriProvider.imgSrcSanitizationTrustedUrlList(regexp);
  8302. return this;
  8303. } else {
  8304. return $$sanitizeUriProvider.imgSrcSanitizationTrustedUrlList();
  8305. }
  8306. };
  8307. /**
  8308. * @ngdoc method
  8309. * @name $compileProvider#imgSrcSanitizationWhitelist
  8310. * @kind function
  8311. *
  8312. * @deprecated
  8313. * sinceVersion="1.8.1"
  8314. *
  8315. * This method is deprecated. Use {@link $compileProvider#imgSrcSanitizationTrustedUrlList
  8316. * imgSrcSanitizationTrustedUrlList} instead.
  8317. */
  8318. Object.defineProperty(this, 'imgSrcSanitizationWhitelist', {
  8319. get: function() {
  8320. return this.imgSrcSanitizationTrustedUrlList;
  8321. },
  8322. set: function(value) {
  8323. this.imgSrcSanitizationTrustedUrlList = value;
  8324. }
  8325. });
  8326. /**
  8327. * @ngdoc method
  8328. * @name $compileProvider#debugInfoEnabled
  8329. *
  8330. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  8331. * current debugInfoEnabled state
  8332. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8333. *
  8334. * @kind function
  8335. *
  8336. * @description
  8337. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  8338. * binding information and a reference to the current scope on to DOM elements.
  8339. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  8340. * * `ng-binding` CSS class
  8341. * * `ng-scope` and `ng-isolated-scope` CSS classes
  8342. * * `$binding` data property containing an array of the binding expressions
  8343. * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return
  8344. * the element's scope.
  8345. * * Placeholder comments will contain information about what directive and binding caused the placeholder.
  8346. * E.g. `<!-- ngIf: shouldShow() -->`.
  8347. *
  8348. * You may want to disable this in production for a significant performance boost. See
  8349. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  8350. *
  8351. * The default value is true.
  8352. */
  8353. var debugInfoEnabled = true;
  8354. this.debugInfoEnabled = function(enabled) {
  8355. if (isDefined(enabled)) {
  8356. debugInfoEnabled = enabled;
  8357. return this;
  8358. }
  8359. return debugInfoEnabled;
  8360. };
  8361. /**
  8362. * @ngdoc method
  8363. * @name $compileProvider#strictComponentBindingsEnabled
  8364. *
  8365. * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided,
  8366. * otherwise return the current strictComponentBindingsEnabled state.
  8367. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8368. *
  8369. * @kind function
  8370. *
  8371. * @description
  8372. * Call this method to enable / disable the strict component bindings check. If enabled, the
  8373. * compiler will enforce that all scope / controller bindings of a
  8374. * {@link $compileProvider#directive directive} / {@link $compileProvider#component component}
  8375. * that are not set as optional with `?`, must be provided when the directive is instantiated.
  8376. * If not provided, the compiler will throw the
  8377. * {@link error/$compile/missingattr $compile:missingattr error}.
  8378. *
  8379. * The default value is false.
  8380. */
  8381. var strictComponentBindingsEnabled = false;
  8382. this.strictComponentBindingsEnabled = function(enabled) {
  8383. if (isDefined(enabled)) {
  8384. strictComponentBindingsEnabled = enabled;
  8385. return this;
  8386. }
  8387. return strictComponentBindingsEnabled;
  8388. };
  8389. var TTL = 10;
  8390. /**
  8391. * @ngdoc method
  8392. * @name $compileProvider#onChangesTtl
  8393. * @description
  8394. *
  8395. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  8396. * assuming that the model is unstable.
  8397. *
  8398. * The current default is 10 iterations.
  8399. *
  8400. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  8401. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  8402. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  8403. * the `$onChanges` hook execution.
  8404. *
  8405. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  8406. *
  8407. * @param {number} limit The number of `$onChanges` hook iterations.
  8408. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  8409. */
  8410. this.onChangesTtl = function(value) {
  8411. if (arguments.length) {
  8412. TTL = value;
  8413. return this;
  8414. }
  8415. return TTL;
  8416. };
  8417. var commentDirectivesEnabledConfig = true;
  8418. /**
  8419. * @ngdoc method
  8420. * @name $compileProvider#commentDirectivesEnabled
  8421. * @description
  8422. *
  8423. * It indicates to the compiler
  8424. * whether or not directives on comments should be compiled.
  8425. * Defaults to `true`.
  8426. *
  8427. * Calling this function with false disables the compilation of directives
  8428. * on comments for the whole application.
  8429. * This results in a compilation performance gain,
  8430. * as the compiler doesn't have to check comments when looking for directives.
  8431. * This should however only be used if you are sure that no comment directives are used in
  8432. * the application (including any 3rd party directives).
  8433. *
  8434. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  8435. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  8436. */
  8437. this.commentDirectivesEnabled = function(value) {
  8438. if (arguments.length) {
  8439. commentDirectivesEnabledConfig = value;
  8440. return this;
  8441. }
  8442. return commentDirectivesEnabledConfig;
  8443. };
  8444. var cssClassDirectivesEnabledConfig = true;
  8445. /**
  8446. * @ngdoc method
  8447. * @name $compileProvider#cssClassDirectivesEnabled
  8448. * @description
  8449. *
  8450. * It indicates to the compiler
  8451. * whether or not directives on element classes should be compiled.
  8452. * Defaults to `true`.
  8453. *
  8454. * Calling this function with false disables the compilation of directives
  8455. * on element classes for the whole application.
  8456. * This results in a compilation performance gain,
  8457. * as the compiler doesn't have to check element classes when looking for directives.
  8458. * This should however only be used if you are sure that no class directives are used in
  8459. * the application (including any 3rd party directives).
  8460. *
  8461. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  8462. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  8463. */
  8464. this.cssClassDirectivesEnabled = function(value) {
  8465. if (arguments.length) {
  8466. cssClassDirectivesEnabledConfig = value;
  8467. return this;
  8468. }
  8469. return cssClassDirectivesEnabledConfig;
  8470. };
  8471. /**
  8472. * The security context of DOM Properties.
  8473. * @private
  8474. */
  8475. var PROP_CONTEXTS = createMap();
  8476. /**
  8477. * @ngdoc method
  8478. * @name $compileProvider#addPropertySecurityContext
  8479. * @description
  8480. *
  8481. * Defines the security context for DOM properties bound by ng-prop-*.
  8482. *
  8483. * @param {string} elementName The element name or '*' to match any element.
  8484. * @param {string} propertyName The DOM property name.
  8485. * @param {string} ctx The {@link $sce} security context in which this value is safe for use, e.g. `$sce.URL`
  8486. * @returns {object} `this` for chaining
  8487. */
  8488. this.addPropertySecurityContext = function(elementName, propertyName, ctx) {
  8489. var key = (elementName.toLowerCase() + '|' + propertyName.toLowerCase());
  8490. if (key in PROP_CONTEXTS && PROP_CONTEXTS[key] !== ctx) {
  8491. throw $compileMinErr('ctxoverride', 'Property context \'{0}.{1}\' already set to \'{2}\', cannot override to \'{3}\'.', elementName, propertyName, PROP_CONTEXTS[key], ctx);
  8492. }
  8493. PROP_CONTEXTS[key] = ctx;
  8494. return this;
  8495. };
  8496. /* Default property contexts.
  8497. *
  8498. * Copy of https://github.com/angular/angular/blob/6.0.6/packages/compiler/src/schema/dom_security_schema.ts#L31-L58
  8499. * Changing:
  8500. * - SecurityContext.* => SCE_CONTEXTS/$sce.*
  8501. * - STYLE => CSS
  8502. * - various URL => MEDIA_URL
  8503. * - *|formAction, form|action URL => RESOURCE_URL (like the attribute)
  8504. */
  8505. (function registerNativePropertyContexts() {
  8506. function registerContext(ctx, values) {
  8507. forEach(values, function(v) { PROP_CONTEXTS[v.toLowerCase()] = ctx; });
  8508. }
  8509. registerContext(SCE_CONTEXTS.HTML, [
  8510. 'iframe|srcdoc',
  8511. '*|innerHTML',
  8512. '*|outerHTML'
  8513. ]);
  8514. registerContext(SCE_CONTEXTS.CSS, ['*|style']);
  8515. registerContext(SCE_CONTEXTS.URL, [
  8516. 'area|href', 'area|ping',
  8517. 'a|href', 'a|ping',
  8518. 'blockquote|cite',
  8519. 'body|background',
  8520. 'del|cite',
  8521. 'input|src',
  8522. 'ins|cite',
  8523. 'q|cite'
  8524. ]);
  8525. registerContext(SCE_CONTEXTS.MEDIA_URL, [
  8526. 'audio|src',
  8527. 'img|src', 'img|srcset',
  8528. 'source|src', 'source|srcset',
  8529. 'track|src',
  8530. 'video|src', 'video|poster'
  8531. ]);
  8532. registerContext(SCE_CONTEXTS.RESOURCE_URL, [
  8533. '*|formAction',
  8534. 'applet|code', 'applet|codebase',
  8535. 'base|href',
  8536. 'embed|src',
  8537. 'frame|src',
  8538. 'form|action',
  8539. 'head|profile',
  8540. 'html|manifest',
  8541. 'iframe|src',
  8542. 'link|href',
  8543. 'media|src',
  8544. 'object|codebase', 'object|data',
  8545. 'script|src'
  8546. ]);
  8547. })();
  8548. this.$get = [
  8549. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  8550. '$controller', '$rootScope', '$sce', '$animate',
  8551. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  8552. $controller, $rootScope, $sce, $animate) {
  8553. var SIMPLE_ATTR_NAME = /^\w/;
  8554. var specialAttrHolder = window.document.createElement('div');
  8555. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  8556. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  8557. var onChangesTtl = TTL;
  8558. // The onChanges hooks should all be run together in a single digest
  8559. // When changes occur, the call to trigger their hooks will be added to this queue
  8560. var onChangesQueue;
  8561. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  8562. function flushOnChangesQueue() {
  8563. try {
  8564. if (!(--onChangesTtl)) {
  8565. // We have hit the TTL limit so reset everything
  8566. onChangesQueue = undefined;
  8567. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  8568. }
  8569. // We must run this hook in an apply since the $$postDigest runs outside apply
  8570. $rootScope.$apply(function() {
  8571. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  8572. try {
  8573. onChangesQueue[i]();
  8574. } catch (e) {
  8575. $exceptionHandler(e);
  8576. }
  8577. }
  8578. // Reset the queue to trigger a new schedule next time there is a change
  8579. onChangesQueue = undefined;
  8580. });
  8581. } finally {
  8582. onChangesTtl++;
  8583. }
  8584. }
  8585. function sanitizeSrcset(value, invokeType) {
  8586. if (!value) {
  8587. return value;
  8588. }
  8589. if (!isString(value)) {
  8590. throw $compileMinErr('srcset', 'Can\'t pass trusted values to `{0}`: "{1}"', invokeType, value.toString());
  8591. }
  8592. // Such values are a bit too complex to handle automatically inside $sce.
  8593. // Instead, we sanitize each of the URIs individually, which works, even dynamically.
  8594. // It's not possible to work around this using `$sce.trustAsMediaUrl`.
  8595. // If you want to programmatically set explicitly trusted unsafe URLs, you should use
  8596. // `$sce.trustAsHtml` on the whole `img` tag and inject it into the DOM using the
  8597. // `ng-bind-html` directive.
  8598. var result = '';
  8599. // first check if there are spaces because it's not the same pattern
  8600. var trimmedSrcset = trim(value);
  8601. // ( 999x ,| 999w ,| ,|, )
  8602. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  8603. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  8604. // split srcset into tuple of uri and descriptor except for the last item
  8605. var rawUris = trimmedSrcset.split(pattern);
  8606. // for each tuples
  8607. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  8608. for (var i = 0; i < nbrUrisWith2parts; i++) {
  8609. var innerIdx = i * 2;
  8610. // sanitize the uri
  8611. result += $sce.getTrustedMediaUrl(trim(rawUris[innerIdx]));
  8612. // add the descriptor
  8613. result += ' ' + trim(rawUris[innerIdx + 1]);
  8614. }
  8615. // split the last item into uri and descriptor
  8616. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  8617. // sanitize the last uri
  8618. result += $sce.getTrustedMediaUrl(trim(lastTuple[0]));
  8619. // and add the last descriptor if any
  8620. if (lastTuple.length === 2) {
  8621. result += (' ' + trim(lastTuple[1]));
  8622. }
  8623. return result;
  8624. }
  8625. function Attributes(element, attributesToCopy) {
  8626. if (attributesToCopy) {
  8627. var keys = Object.keys(attributesToCopy);
  8628. var i, l, key;
  8629. for (i = 0, l = keys.length; i < l; i++) {
  8630. key = keys[i];
  8631. this[key] = attributesToCopy[key];
  8632. }
  8633. } else {
  8634. this.$attr = {};
  8635. }
  8636. this.$$element = element;
  8637. }
  8638. Attributes.prototype = {
  8639. /**
  8640. * @ngdoc method
  8641. * @name $compile.directive.Attributes#$normalize
  8642. * @kind function
  8643. *
  8644. * @description
  8645. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  8646. * `data-`) to its normalized, camelCase form.
  8647. *
  8648. * Also there is special case for Moz prefix starting with upper case letter.
  8649. *
  8650. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  8651. *
  8652. * @param {string} name Name to normalize
  8653. */
  8654. $normalize: directiveNormalize,
  8655. /**
  8656. * @ngdoc method
  8657. * @name $compile.directive.Attributes#$addClass
  8658. * @kind function
  8659. *
  8660. * @description
  8661. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  8662. * are enabled then an animation will be triggered for the class addition.
  8663. *
  8664. * @param {string} classVal The className value that will be added to the element
  8665. */
  8666. $addClass: function(classVal) {
  8667. if (classVal && classVal.length > 0) {
  8668. $animate.addClass(this.$$element, classVal);
  8669. }
  8670. },
  8671. /**
  8672. * @ngdoc method
  8673. * @name $compile.directive.Attributes#$removeClass
  8674. * @kind function
  8675. *
  8676. * @description
  8677. * Removes the CSS class value specified by the classVal parameter from the element. If
  8678. * animations are enabled then an animation will be triggered for the class removal.
  8679. *
  8680. * @param {string} classVal The className value that will be removed from the element
  8681. */
  8682. $removeClass: function(classVal) {
  8683. if (classVal && classVal.length > 0) {
  8684. $animate.removeClass(this.$$element, classVal);
  8685. }
  8686. },
  8687. /**
  8688. * @ngdoc method
  8689. * @name $compile.directive.Attributes#$updateClass
  8690. * @kind function
  8691. *
  8692. * @description
  8693. * Adds and removes the appropriate CSS class values to the element based on the difference
  8694. * between the new and old CSS class values (specified as newClasses and oldClasses).
  8695. *
  8696. * @param {string} newClasses The current CSS className value
  8697. * @param {string} oldClasses The former CSS className value
  8698. */
  8699. $updateClass: function(newClasses, oldClasses) {
  8700. var toAdd = tokenDifference(newClasses, oldClasses);
  8701. if (toAdd && toAdd.length) {
  8702. $animate.addClass(this.$$element, toAdd);
  8703. }
  8704. var toRemove = tokenDifference(oldClasses, newClasses);
  8705. if (toRemove && toRemove.length) {
  8706. $animate.removeClass(this.$$element, toRemove);
  8707. }
  8708. },
  8709. /**
  8710. * Set a normalized attribute on the element in a way such that all directives
  8711. * can share the attribute. This function properly handles boolean attributes.
  8712. * @param {string} key Normalized key. (ie ngAttribute)
  8713. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  8714. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  8715. * Defaults to true.
  8716. * @param {string=} attrName Optional none normalized name. Defaults to key.
  8717. */
  8718. $set: function(key, value, writeAttr, attrName) {
  8719. // TODO: decide whether or not to throw an error if "class"
  8720. // is set through this function since it may cause $updateClass to
  8721. // become unstable.
  8722. var node = this.$$element[0],
  8723. booleanKey = getBooleanAttrName(node, key),
  8724. aliasedKey = getAliasedAttrName(key),
  8725. observer = key,
  8726. nodeName;
  8727. if (booleanKey) {
  8728. this.$$element.prop(key, value);
  8729. attrName = booleanKey;
  8730. } else if (aliasedKey) {
  8731. this[aliasedKey] = value;
  8732. observer = aliasedKey;
  8733. }
  8734. this[key] = value;
  8735. // translate normalized key to actual key
  8736. if (attrName) {
  8737. this.$attr[key] = attrName;
  8738. } else {
  8739. attrName = this.$attr[key];
  8740. if (!attrName) {
  8741. this.$attr[key] = attrName = snake_case(key, '-');
  8742. }
  8743. }
  8744. nodeName = nodeName_(this.$$element);
  8745. // Sanitize img[srcset] values.
  8746. if (nodeName === 'img' && key === 'srcset') {
  8747. this[key] = value = sanitizeSrcset(value, '$set(\'srcset\', value)');
  8748. }
  8749. if (writeAttr !== false) {
  8750. if (value === null || isUndefined(value)) {
  8751. this.$$element.removeAttr(attrName);
  8752. } else {
  8753. if (SIMPLE_ATTR_NAME.test(attrName)) {
  8754. // jQuery skips special boolean attrs treatment in XML nodes for
  8755. // historical reasons and hence AngularJS cannot freely call
  8756. // `.attr(attrName, false) with such attributes. To avoid issues
  8757. // in XHTML, call `removeAttr` in such cases instead.
  8758. // See https://github.com/jquery/jquery/issues/4249
  8759. if (booleanKey && value === false) {
  8760. this.$$element.removeAttr(attrName);
  8761. } else {
  8762. this.$$element.attr(attrName, value);
  8763. }
  8764. } else {
  8765. setSpecialAttr(this.$$element[0], attrName, value);
  8766. }
  8767. }
  8768. }
  8769. // fire observers
  8770. var $$observers = this.$$observers;
  8771. if ($$observers) {
  8772. forEach($$observers[observer], function(fn) {
  8773. try {
  8774. fn(value);
  8775. } catch (e) {
  8776. $exceptionHandler(e);
  8777. }
  8778. });
  8779. }
  8780. },
  8781. /**
  8782. * @ngdoc method
  8783. * @name $compile.directive.Attributes#$observe
  8784. * @kind function
  8785. *
  8786. * @description
  8787. * Observes an interpolated attribute.
  8788. *
  8789. * The observer function will be invoked once during the next `$digest` following
  8790. * compilation. The observer is then invoked whenever the interpolated value
  8791. * changes.
  8792. *
  8793. * @param {string} key Normalized key. (ie ngAttribute) .
  8794. * @param {function(interpolatedValue)} fn Function that will be called whenever
  8795. the interpolated value of the attribute changes.
  8796. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  8797. * guide} for more info.
  8798. * @returns {function()} Returns a deregistration function for this observer.
  8799. */
  8800. $observe: function(key, fn) {
  8801. var attrs = this,
  8802. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  8803. listeners = ($$observers[key] || ($$observers[key] = []));
  8804. listeners.push(fn);
  8805. $rootScope.$evalAsync(function() {
  8806. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  8807. // no one registered attribute interpolation function, so lets call it manually
  8808. fn(attrs[key]);
  8809. }
  8810. });
  8811. return function() {
  8812. arrayRemove(listeners, fn);
  8813. };
  8814. }
  8815. };
  8816. function setSpecialAttr(element, attrName, value) {
  8817. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  8818. // so we have to jump through some hoops to get such an attribute
  8819. // https://github.com/angular/angular.js/pull/13318
  8820. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  8821. var attributes = specialAttrHolder.firstChild.attributes;
  8822. var attribute = attributes[0];
  8823. // We have to remove the attribute from its container element before we can add it to the destination element
  8824. attributes.removeNamedItem(attribute.name);
  8825. attribute.value = value;
  8826. element.attributes.setNamedItem(attribute);
  8827. }
  8828. function safeAddClass($element, className) {
  8829. try {
  8830. $element.addClass(className);
  8831. } catch (e) {
  8832. // ignore, since it means that we are trying to set class on
  8833. // SVG element, where class name is read-only.
  8834. }
  8835. }
  8836. var startSymbol = $interpolate.startSymbol(),
  8837. endSymbol = $interpolate.endSymbol(),
  8838. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8839. ? identity
  8840. : function denormalizeTemplate(template) {
  8841. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8842. },
  8843. NG_PREFIX_BINDING = /^ng(Attr|Prop|On)([A-Z].*)$/;
  8844. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8845. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8846. var bindings = $element.data('$binding') || [];
  8847. if (isArray(binding)) {
  8848. bindings = bindings.concat(binding);
  8849. } else {
  8850. bindings.push(binding);
  8851. }
  8852. $element.data('$binding', bindings);
  8853. } : noop;
  8854. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8855. safeAddClass($element, 'ng-binding');
  8856. } : noop;
  8857. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8858. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8859. $element.data(dataName, scope);
  8860. } : noop;
  8861. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8862. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8863. } : noop;
  8864. compile.$$createComment = function(directiveName, comment) {
  8865. var content = '';
  8866. if (debugInfoEnabled) {
  8867. content = ' ' + (directiveName || '') + ': ';
  8868. if (comment) content += comment + ' ';
  8869. }
  8870. return window.document.createComment(content);
  8871. };
  8872. return compile;
  8873. //================================
  8874. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8875. previousCompileContext) {
  8876. if (!($compileNodes instanceof jqLite)) {
  8877. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8878. // modify it.
  8879. $compileNodes = jqLite($compileNodes);
  8880. }
  8881. var compositeLinkFn =
  8882. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8883. maxPriority, ignoreDirective, previousCompileContext);
  8884. compile.$$addScopeClass($compileNodes);
  8885. var namespace = null;
  8886. return function publicLinkFn(scope, cloneConnectFn, options) {
  8887. if (!$compileNodes) {
  8888. throw $compileMinErr('multilink', 'This element has already been linked.');
  8889. }
  8890. assertArg(scope, 'scope');
  8891. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8892. // A parent directive did a replace and a directive on this element asked
  8893. // for transclusion, which caused us to lose a layer of element on which
  8894. // we could hold the new transclusion scope, so we will create it manually
  8895. // here.
  8896. scope = scope.$parent.$new();
  8897. }
  8898. options = options || {};
  8899. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8900. transcludeControllers = options.transcludeControllers,
  8901. futureParentElement = options.futureParentElement;
  8902. // When `parentBoundTranscludeFn` is passed, it is a
  8903. // `controllersBoundTransclude` function (it was previously passed
  8904. // as `transclude` to directive.link) so we must unwrap it to get
  8905. // its `boundTranscludeFn`
  8906. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8907. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8908. }
  8909. if (!namespace) {
  8910. namespace = detectNamespaceForChildElements(futureParentElement);
  8911. }
  8912. var $linkNode;
  8913. if (namespace !== 'html') {
  8914. // When using a directive with replace:true and templateUrl the $compileNodes
  8915. // (or a child element inside of them)
  8916. // might change, so we need to recreate the namespace adapted compileNodes
  8917. // for call to the link function.
  8918. // Note: This will already clone the nodes...
  8919. $linkNode = jqLite(
  8920. wrapTemplate(namespace, jqLite('<div></div>').append($compileNodes).html())
  8921. );
  8922. } else if (cloneConnectFn) {
  8923. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8924. // and sometimes changes the structure of the DOM.
  8925. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8926. } else {
  8927. $linkNode = $compileNodes;
  8928. }
  8929. if (transcludeControllers) {
  8930. for (var controllerName in transcludeControllers) {
  8931. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8932. }
  8933. }
  8934. compile.$$addScopeInfo($linkNode, scope);
  8935. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8936. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8937. if (!cloneConnectFn) {
  8938. $compileNodes = compositeLinkFn = null;
  8939. }
  8940. return $linkNode;
  8941. };
  8942. }
  8943. function detectNamespaceForChildElements(parentElement) {
  8944. // TODO: Make this detect MathML as well...
  8945. var node = parentElement && parentElement[0];
  8946. if (!node) {
  8947. return 'html';
  8948. } else {
  8949. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8950. }
  8951. }
  8952. /**
  8953. * Compile function matches each node in nodeList against the directives. Once all directives
  8954. * for a particular node are collected their compile functions are executed. The compile
  8955. * functions return values - the linking functions - are combined into a composite linking
  8956. * function, which is the a linking function for the node.
  8957. *
  8958. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8959. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8960. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8961. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8962. * the rootElement must be set the jqLite collection of the compile root. This is
  8963. * needed so that the jqLite collection items can be replaced with widgets.
  8964. * @param {number=} maxPriority Max directive priority.
  8965. * @returns {Function} A composite linking function of all of the matched directives or null.
  8966. */
  8967. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8968. previousCompileContext) {
  8969. var linkFns = [],
  8970. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8971. // or a jqLite/jQuery collection or an array
  8972. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8973. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8974. for (var i = 0; i < nodeList.length; i++) {
  8975. attrs = new Attributes();
  8976. // Support: IE 11 only
  8977. // Workaround for #11781 and #14924
  8978. if (msie === 11) {
  8979. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8980. }
  8981. // We must always refer to `nodeList[i]` hereafter,
  8982. // since the nodes can be replaced underneath us.
  8983. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8984. ignoreDirective);
  8985. nodeLinkFn = (directives.length)
  8986. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8987. null, [], [], previousCompileContext)
  8988. : null;
  8989. if (nodeLinkFn && nodeLinkFn.scope) {
  8990. compile.$$addScopeClass(attrs.$$element);
  8991. }
  8992. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8993. !(childNodes = nodeList[i].childNodes) ||
  8994. !childNodes.length)
  8995. ? null
  8996. : compileNodes(childNodes,
  8997. nodeLinkFn ? (
  8998. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8999. && nodeLinkFn.transclude) : transcludeFn);
  9000. if (nodeLinkFn || childLinkFn) {
  9001. linkFns.push(i, nodeLinkFn, childLinkFn);
  9002. linkFnFound = true;
  9003. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  9004. }
  9005. //use the previous context only for the first element in the virtual group
  9006. previousCompileContext = null;
  9007. }
  9008. // return a linking function if we have found anything, null otherwise
  9009. return linkFnFound ? compositeLinkFn : null;
  9010. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  9011. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  9012. var stableNodeList;
  9013. if (nodeLinkFnFound) {
  9014. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  9015. // offsets don't get screwed up
  9016. var nodeListLength = nodeList.length;
  9017. stableNodeList = new Array(nodeListLength);
  9018. // create a sparse array by only copying the elements which have a linkFn
  9019. for (i = 0; i < linkFns.length; i += 3) {
  9020. idx = linkFns[i];
  9021. stableNodeList[idx] = nodeList[idx];
  9022. }
  9023. } else {
  9024. stableNodeList = nodeList;
  9025. }
  9026. for (i = 0, ii = linkFns.length; i < ii;) {
  9027. node = stableNodeList[linkFns[i++]];
  9028. nodeLinkFn = linkFns[i++];
  9029. childLinkFn = linkFns[i++];
  9030. if (nodeLinkFn) {
  9031. if (nodeLinkFn.scope) {
  9032. childScope = scope.$new();
  9033. compile.$$addScopeInfo(jqLite(node), childScope);
  9034. } else {
  9035. childScope = scope;
  9036. }
  9037. if (nodeLinkFn.transcludeOnThisElement) {
  9038. childBoundTranscludeFn = createBoundTranscludeFn(
  9039. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  9040. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  9041. childBoundTranscludeFn = parentBoundTranscludeFn;
  9042. } else if (!parentBoundTranscludeFn && transcludeFn) {
  9043. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  9044. } else {
  9045. childBoundTranscludeFn = null;
  9046. }
  9047. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  9048. } else if (childLinkFn) {
  9049. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  9050. }
  9051. }
  9052. }
  9053. }
  9054. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  9055. var node = nodeList[idx];
  9056. var parent = node.parentNode;
  9057. var sibling;
  9058. if (node.nodeType !== NODE_TYPE_TEXT) {
  9059. return;
  9060. }
  9061. while (true) {
  9062. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  9063. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  9064. break;
  9065. }
  9066. node.nodeValue = node.nodeValue + sibling.nodeValue;
  9067. if (sibling.parentNode) {
  9068. sibling.parentNode.removeChild(sibling);
  9069. }
  9070. if (notLiveList && sibling === nodeList[idx + 1]) {
  9071. nodeList.splice(idx + 1, 1);
  9072. }
  9073. }
  9074. }
  9075. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  9076. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  9077. if (!transcludedScope) {
  9078. transcludedScope = scope.$new(false, containingScope);
  9079. transcludedScope.$$transcluded = true;
  9080. }
  9081. return transcludeFn(transcludedScope, cloneFn, {
  9082. parentBoundTranscludeFn: previousBoundTranscludeFn,
  9083. transcludeControllers: controllers,
  9084. futureParentElement: futureParentElement
  9085. });
  9086. }
  9087. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  9088. // so that they are available inside the `controllersBoundTransclude` function
  9089. var boundSlots = boundTranscludeFn.$$slots = createMap();
  9090. for (var slotName in transcludeFn.$$slots) {
  9091. if (transcludeFn.$$slots[slotName]) {
  9092. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  9093. } else {
  9094. boundSlots[slotName] = null;
  9095. }
  9096. }
  9097. return boundTranscludeFn;
  9098. }
  9099. /**
  9100. * Looks for directives on the given node and adds them to the directive collection which is
  9101. * sorted.
  9102. *
  9103. * @param node Node to search.
  9104. * @param directives An array to which the directives are added to. This array is sorted before
  9105. * the function returns.
  9106. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  9107. * @param {number=} maxPriority Max directive priority.
  9108. */
  9109. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  9110. var nodeType = node.nodeType,
  9111. attrsMap = attrs.$attr,
  9112. match,
  9113. nodeName,
  9114. className;
  9115. switch (nodeType) {
  9116. case NODE_TYPE_ELEMENT: /* Element */
  9117. nodeName = nodeName_(node);
  9118. // use the node name: <directive>
  9119. addDirective(directives,
  9120. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  9121. // iterate over the attributes
  9122. for (var attr, name, nName, value, ngPrefixMatch, nAttrs = node.attributes,
  9123. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  9124. var attrStartName = false;
  9125. var attrEndName = false;
  9126. var isNgAttr = false, isNgProp = false, isNgEvent = false;
  9127. var multiElementMatch;
  9128. attr = nAttrs[j];
  9129. name = attr.name;
  9130. value = attr.value;
  9131. nName = directiveNormalize(name.toLowerCase());
  9132. // Support ng-attr-*, ng-prop-* and ng-on-*
  9133. if ((ngPrefixMatch = nName.match(NG_PREFIX_BINDING))) {
  9134. isNgAttr = ngPrefixMatch[1] === 'Attr';
  9135. isNgProp = ngPrefixMatch[1] === 'Prop';
  9136. isNgEvent = ngPrefixMatch[1] === 'On';
  9137. // Normalize the non-prefixed name
  9138. name = name.replace(PREFIX_REGEXP, '')
  9139. .toLowerCase()
  9140. .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) {
  9141. return letter.toUpperCase();
  9142. });
  9143. // Support *-start / *-end multi element directives
  9144. } else if ((multiElementMatch = nName.match(MULTI_ELEMENT_DIR_RE)) && directiveIsMultiElement(multiElementMatch[1])) {
  9145. attrStartName = name;
  9146. attrEndName = name.substr(0, name.length - 5) + 'end';
  9147. name = name.substr(0, name.length - 6);
  9148. }
  9149. if (isNgProp || isNgEvent) {
  9150. attrs[nName] = value;
  9151. attrsMap[nName] = attr.name;
  9152. if (isNgProp) {
  9153. addPropertyDirective(node, directives, nName, name);
  9154. } else {
  9155. addEventDirective(directives, nName, name);
  9156. }
  9157. } else {
  9158. // Update nName for cases where a prefix was removed
  9159. // NOTE: the .toLowerCase() is unnecessary and causes https://github.com/angular/angular.js/issues/16624 for ng-attr-*
  9160. nName = directiveNormalize(name.toLowerCase());
  9161. attrsMap[nName] = name;
  9162. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  9163. attrs[nName] = value;
  9164. if (getBooleanAttrName(node, nName)) {
  9165. attrs[nName] = true; // presence means true
  9166. }
  9167. }
  9168. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  9169. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  9170. attrEndName);
  9171. }
  9172. }
  9173. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  9174. // Hidden input elements can have strange behaviour when navigating back to the page
  9175. // This tells the browser not to try to cache and reinstate previous values
  9176. node.setAttribute('autocomplete', 'off');
  9177. }
  9178. // use class as directive
  9179. if (!cssClassDirectivesEnabled) break;
  9180. className = node.className;
  9181. if (isObject(className)) {
  9182. // Maybe SVGAnimatedString
  9183. className = className.animVal;
  9184. }
  9185. if (isString(className) && className !== '') {
  9186. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  9187. nName = directiveNormalize(match[2]);
  9188. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  9189. attrs[nName] = trim(match[3]);
  9190. }
  9191. className = className.substr(match.index + match[0].length);
  9192. }
  9193. }
  9194. break;
  9195. case NODE_TYPE_TEXT: /* Text Node */
  9196. addTextInterpolateDirective(directives, node.nodeValue);
  9197. break;
  9198. case NODE_TYPE_COMMENT: /* Comment */
  9199. if (!commentDirectivesEnabled) break;
  9200. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  9201. break;
  9202. }
  9203. directives.sort(byPriority);
  9204. return directives;
  9205. }
  9206. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  9207. // function created because of performance, try/catch disables
  9208. // the optimization of the whole function #14848
  9209. try {
  9210. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  9211. if (match) {
  9212. var nName = directiveNormalize(match[1]);
  9213. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  9214. attrs[nName] = trim(match[2]);
  9215. }
  9216. }
  9217. } catch (e) {
  9218. // turns out that under some circumstances IE9 throws errors when one attempts to read
  9219. // comment's node value.
  9220. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  9221. }
  9222. }
  9223. /**
  9224. * Given a node with a directive-start it collects all of the siblings until it finds
  9225. * directive-end.
  9226. * @param node
  9227. * @param attrStart
  9228. * @param attrEnd
  9229. * @returns {*}
  9230. */
  9231. function groupScan(node, attrStart, attrEnd) {
  9232. var nodes = [];
  9233. var depth = 0;
  9234. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  9235. do {
  9236. if (!node) {
  9237. throw $compileMinErr('uterdir',
  9238. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  9239. attrStart, attrEnd);
  9240. }
  9241. if (node.nodeType === NODE_TYPE_ELEMENT) {
  9242. if (node.hasAttribute(attrStart)) depth++;
  9243. if (node.hasAttribute(attrEnd)) depth--;
  9244. }
  9245. nodes.push(node);
  9246. node = node.nextSibling;
  9247. } while (depth > 0);
  9248. } else {
  9249. nodes.push(node);
  9250. }
  9251. return jqLite(nodes);
  9252. }
  9253. /**
  9254. * Wrapper for linking function which converts normal linking function into a grouped
  9255. * linking function.
  9256. * @param linkFn
  9257. * @param attrStart
  9258. * @param attrEnd
  9259. * @returns {Function}
  9260. */
  9261. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  9262. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  9263. element = groupScan(element[0], attrStart, attrEnd);
  9264. return linkFn(scope, element, attrs, controllers, transcludeFn);
  9265. };
  9266. }
  9267. /**
  9268. * A function generator that is used to support both eager and lazy compilation
  9269. * linking function.
  9270. * @param eager
  9271. * @param $compileNodes
  9272. * @param transcludeFn
  9273. * @param maxPriority
  9274. * @param ignoreDirective
  9275. * @param previousCompileContext
  9276. * @returns {Function}
  9277. */
  9278. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  9279. var compiled;
  9280. if (eager) {
  9281. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  9282. }
  9283. return /** @this */ function lazyCompilation() {
  9284. if (!compiled) {
  9285. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  9286. // Null out all of these references in order to make them eligible for garbage collection
  9287. // since this is a potentially long lived closure
  9288. $compileNodes = transcludeFn = previousCompileContext = null;
  9289. }
  9290. return compiled.apply(this, arguments);
  9291. };
  9292. }
  9293. /**
  9294. * Once the directives have been collected, their compile functions are executed. This method
  9295. * is responsible for inlining directive templates as well as terminating the application
  9296. * of the directives if the terminal directive has been reached.
  9297. *
  9298. * @param {Array} directives Array of collected directives to execute their compile function.
  9299. * this needs to be pre-sorted by priority order.
  9300. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  9301. * @param {Object} templateAttrs The shared attribute function
  9302. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  9303. * scope argument is auto-generated to the new
  9304. * child of the transcluded parent scope.
  9305. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  9306. * argument has the root jqLite array so that we can replace nodes
  9307. * on it.
  9308. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  9309. * compiling the transclusion.
  9310. * @param {Array.<Function>} preLinkFns
  9311. * @param {Array.<Function>} postLinkFns
  9312. * @param {Object} previousCompileContext Context used for previous compilation of the current
  9313. * node
  9314. * @returns {Function} linkFn
  9315. */
  9316. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  9317. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  9318. previousCompileContext) {
  9319. previousCompileContext = previousCompileContext || {};
  9320. var terminalPriority = -Number.MAX_VALUE,
  9321. newScopeDirective = previousCompileContext.newScopeDirective,
  9322. controllerDirectives = previousCompileContext.controllerDirectives,
  9323. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  9324. templateDirective = previousCompileContext.templateDirective,
  9325. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  9326. hasTranscludeDirective = false,
  9327. hasTemplate = false,
  9328. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  9329. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  9330. directive,
  9331. directiveName,
  9332. $template,
  9333. replaceDirective = originalReplaceDirective,
  9334. childTranscludeFn = transcludeFn,
  9335. linkFn,
  9336. didScanForMultipleTransclusion = false,
  9337. mightHaveMultipleTransclusionError = false,
  9338. directiveValue;
  9339. // executes all directives on the current element
  9340. for (var i = 0, ii = directives.length; i < ii; i++) {
  9341. directive = directives[i];
  9342. var attrStart = directive.$$start;
  9343. var attrEnd = directive.$$end;
  9344. // collect multiblock sections
  9345. if (attrStart) {
  9346. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  9347. }
  9348. $template = undefined;
  9349. if (terminalPriority > directive.priority) {
  9350. break; // prevent further processing of directives
  9351. }
  9352. directiveValue = directive.scope;
  9353. if (directiveValue) {
  9354. // skip the check for directives with async templates, we'll check the derived sync
  9355. // directive when the template arrives
  9356. if (!directive.templateUrl) {
  9357. if (isObject(directiveValue)) {
  9358. // This directive is trying to add an isolated scope.
  9359. // Check that there is no scope of any kind already
  9360. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  9361. directive, $compileNode);
  9362. newIsolateScopeDirective = directive;
  9363. } else {
  9364. // This directive is trying to add a child scope.
  9365. // Check that there is no isolated scope already
  9366. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  9367. $compileNode);
  9368. }
  9369. }
  9370. newScopeDirective = newScopeDirective || directive;
  9371. }
  9372. directiveName = directive.name;
  9373. // If we encounter a condition that can result in transclusion on the directive,
  9374. // then scan ahead in the remaining directives for others that may cause a multiple
  9375. // transclusion error to be thrown during the compilation process. If a matching directive
  9376. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  9377. // compile the `transclude` function rather than doing it lazily in order to throw
  9378. // exceptions at the correct time
  9379. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  9380. || (directive.transclude && !directive.$$tlb))) {
  9381. var candidateDirective;
  9382. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  9383. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  9384. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  9385. mightHaveMultipleTransclusionError = true;
  9386. break;
  9387. }
  9388. }
  9389. didScanForMultipleTransclusion = true;
  9390. }
  9391. if (!directive.templateUrl && directive.controller) {
  9392. controllerDirectives = controllerDirectives || createMap();
  9393. assertNoDuplicate('\'' + directiveName + '\' controller',
  9394. controllerDirectives[directiveName], directive, $compileNode);
  9395. controllerDirectives[directiveName] = directive;
  9396. }
  9397. directiveValue = directive.transclude;
  9398. if (directiveValue) {
  9399. hasTranscludeDirective = true;
  9400. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  9401. // This option should only be used by directives that know how to safely handle element transclusion,
  9402. // where the transcluded nodes are added or replaced after linking.
  9403. if (!directive.$$tlb) {
  9404. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  9405. nonTlbTranscludeDirective = directive;
  9406. }
  9407. if (directiveValue === 'element') {
  9408. hasElementTranscludeDirective = true;
  9409. terminalPriority = directive.priority;
  9410. $template = $compileNode;
  9411. $compileNode = templateAttrs.$$element =
  9412. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  9413. compileNode = $compileNode[0];
  9414. replaceWith(jqCollection, sliceArgs($template), compileNode);
  9415. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  9416. replaceDirective && replaceDirective.name, {
  9417. // Don't pass in:
  9418. // - controllerDirectives - otherwise we'll create duplicates controllers
  9419. // - newIsolateScopeDirective or templateDirective - combining templates with
  9420. // element transclusion doesn't make sense.
  9421. //
  9422. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  9423. // on the same element more than once.
  9424. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  9425. });
  9426. } else {
  9427. var slots = createMap();
  9428. if (!isObject(directiveValue)) {
  9429. $template = jqLite(jqLiteClone(compileNode)).contents();
  9430. } else {
  9431. // We have transclusion slots,
  9432. // collect them up, compile them and store their transclusion functions
  9433. $template = window.document.createDocumentFragment();
  9434. var slotMap = createMap();
  9435. var filledSlots = createMap();
  9436. // Parse the element selectors
  9437. forEach(directiveValue, function(elementSelector, slotName) {
  9438. // If an element selector starts with a ? then it is optional
  9439. var optional = (elementSelector.charAt(0) === '?');
  9440. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  9441. slotMap[elementSelector] = slotName;
  9442. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  9443. // Later when calling boundTransclusion functions with a slot name we only error if the
  9444. // slot is `undefined`
  9445. slots[slotName] = null;
  9446. // filledSlots contains `true` for all slots that are either optional or have been
  9447. // filled. This is used to check that we have not missed any required slots
  9448. filledSlots[slotName] = optional;
  9449. });
  9450. // Add the matching elements into their slot
  9451. forEach($compileNode.contents(), function(node) {
  9452. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  9453. if (slotName) {
  9454. filledSlots[slotName] = true;
  9455. slots[slotName] = slots[slotName] || window.document.createDocumentFragment();
  9456. slots[slotName].appendChild(node);
  9457. } else {
  9458. $template.appendChild(node);
  9459. }
  9460. });
  9461. // Check for required slots that were not filled
  9462. forEach(filledSlots, function(filled, slotName) {
  9463. if (!filled) {
  9464. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  9465. }
  9466. });
  9467. for (var slotName in slots) {
  9468. if (slots[slotName]) {
  9469. // Only define a transclusion function if the slot was filled
  9470. var slotCompileNodes = jqLite(slots[slotName].childNodes);
  9471. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slotCompileNodes, transcludeFn);
  9472. }
  9473. }
  9474. $template = jqLite($template.childNodes);
  9475. }
  9476. $compileNode.empty(); // clear contents
  9477. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  9478. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  9479. childTranscludeFn.$$slots = slots;
  9480. }
  9481. }
  9482. if (directive.template) {
  9483. hasTemplate = true;
  9484. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  9485. templateDirective = directive;
  9486. directiveValue = (isFunction(directive.template))
  9487. ? directive.template($compileNode, templateAttrs)
  9488. : directive.template;
  9489. directiveValue = denormalizeTemplate(directiveValue);
  9490. if (directive.replace) {
  9491. replaceDirective = directive;
  9492. if (jqLiteIsTextNode(directiveValue)) {
  9493. $template = [];
  9494. } else {
  9495. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  9496. }
  9497. compileNode = $template[0];
  9498. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9499. throw $compileMinErr('tplrt',
  9500. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9501. directiveName, '');
  9502. }
  9503. replaceWith(jqCollection, $compileNode, compileNode);
  9504. var newTemplateAttrs = {$attr: {}};
  9505. // combine directives from the original node and from the template:
  9506. // - take the array of directives for this element
  9507. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  9508. // - collect directives from the template and sort them by priority
  9509. // - combine directives as: processed + template + unprocessed
  9510. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  9511. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  9512. if (newIsolateScopeDirective || newScopeDirective) {
  9513. // The original directive caused the current element to be replaced but this element
  9514. // also needs to have a new scope, so we need to tell the template directives
  9515. // that they would need to get their scope from further up, if they require transclusion
  9516. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  9517. }
  9518. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  9519. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  9520. ii = directives.length;
  9521. } else {
  9522. $compileNode.html(directiveValue);
  9523. }
  9524. }
  9525. if (directive.templateUrl) {
  9526. hasTemplate = true;
  9527. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  9528. templateDirective = directive;
  9529. if (directive.replace) {
  9530. replaceDirective = directive;
  9531. }
  9532. // eslint-disable-next-line no-func-assign
  9533. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  9534. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  9535. controllerDirectives: controllerDirectives,
  9536. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  9537. newIsolateScopeDirective: newIsolateScopeDirective,
  9538. templateDirective: templateDirective,
  9539. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  9540. });
  9541. ii = directives.length;
  9542. } else if (directive.compile) {
  9543. try {
  9544. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  9545. var context = directive.$$originalDirective || directive;
  9546. if (isFunction(linkFn)) {
  9547. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  9548. } else if (linkFn) {
  9549. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  9550. }
  9551. } catch (e) {
  9552. $exceptionHandler(e, startingTag($compileNode));
  9553. }
  9554. }
  9555. if (directive.terminal) {
  9556. nodeLinkFn.terminal = true;
  9557. terminalPriority = Math.max(terminalPriority, directive.priority);
  9558. }
  9559. }
  9560. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  9561. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  9562. nodeLinkFn.templateOnThisElement = hasTemplate;
  9563. nodeLinkFn.transclude = childTranscludeFn;
  9564. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  9565. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  9566. return nodeLinkFn;
  9567. ////////////////////
  9568. function addLinkFns(pre, post, attrStart, attrEnd) {
  9569. if (pre) {
  9570. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  9571. pre.require = directive.require;
  9572. pre.directiveName = directiveName;
  9573. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  9574. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  9575. }
  9576. preLinkFns.push(pre);
  9577. }
  9578. if (post) {
  9579. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  9580. post.require = directive.require;
  9581. post.directiveName = directiveName;
  9582. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  9583. post = cloneAndAnnotateFn(post, {isolateScope: true});
  9584. }
  9585. postLinkFns.push(post);
  9586. }
  9587. }
  9588. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  9589. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  9590. attrs, scopeBindingInfo;
  9591. if (compileNode === linkNode) {
  9592. attrs = templateAttrs;
  9593. $element = templateAttrs.$$element;
  9594. } else {
  9595. $element = jqLite(linkNode);
  9596. attrs = new Attributes($element, templateAttrs);
  9597. }
  9598. controllerScope = scope;
  9599. if (newIsolateScopeDirective) {
  9600. isolateScope = scope.$new(true);
  9601. } else if (newScopeDirective) {
  9602. controllerScope = scope.$parent;
  9603. }
  9604. if (boundTranscludeFn) {
  9605. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  9606. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  9607. transcludeFn = controllersBoundTransclude;
  9608. transcludeFn.$$boundTransclude = boundTranscludeFn;
  9609. // expose the slots on the `$transclude` function
  9610. transcludeFn.isSlotFilled = function(slotName) {
  9611. return !!boundTranscludeFn.$$slots[slotName];
  9612. };
  9613. }
  9614. if (controllerDirectives) {
  9615. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  9616. }
  9617. if (newIsolateScopeDirective) {
  9618. // Initialize isolate scope bindings for new isolate scope directive.
  9619. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  9620. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  9621. compile.$$addScopeClass($element, true);
  9622. isolateScope.$$isolateBindings =
  9623. newIsolateScopeDirective.$$isolateBindings;
  9624. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  9625. isolateScope.$$isolateBindings,
  9626. newIsolateScopeDirective);
  9627. if (scopeBindingInfo.removeWatches) {
  9628. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  9629. }
  9630. }
  9631. // Initialize bindToController bindings
  9632. for (var name in elementControllers) {
  9633. var controllerDirective = controllerDirectives[name];
  9634. var controller = elementControllers[name];
  9635. var bindings = controllerDirective.$$bindings.bindToController;
  9636. controller.instance = controller();
  9637. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  9638. controller.bindingInfo =
  9639. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  9640. }
  9641. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  9642. forEach(controllerDirectives, function(controllerDirective, name) {
  9643. var require = controllerDirective.require;
  9644. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  9645. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  9646. }
  9647. });
  9648. // Handle the init and destroy lifecycle hooks on all controllers that have them
  9649. forEach(elementControllers, function(controller) {
  9650. var controllerInstance = controller.instance;
  9651. if (isFunction(controllerInstance.$onChanges)) {
  9652. try {
  9653. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  9654. } catch (e) {
  9655. $exceptionHandler(e);
  9656. }
  9657. }
  9658. if (isFunction(controllerInstance.$onInit)) {
  9659. try {
  9660. controllerInstance.$onInit();
  9661. } catch (e) {
  9662. $exceptionHandler(e);
  9663. }
  9664. }
  9665. if (isFunction(controllerInstance.$doCheck)) {
  9666. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  9667. controllerInstance.$doCheck();
  9668. }
  9669. if (isFunction(controllerInstance.$onDestroy)) {
  9670. controllerScope.$on('$destroy', function callOnDestroyHook() {
  9671. controllerInstance.$onDestroy();
  9672. });
  9673. }
  9674. });
  9675. // PRELINKING
  9676. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  9677. linkFn = preLinkFns[i];
  9678. invokeLinkFn(linkFn,
  9679. linkFn.isolateScope ? isolateScope : scope,
  9680. $element,
  9681. attrs,
  9682. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9683. transcludeFn
  9684. );
  9685. }
  9686. // RECURSION
  9687. // We only pass the isolate scope, if the isolate directive has a template,
  9688. // otherwise the child elements do not belong to the isolate directive.
  9689. var scopeToChild = scope;
  9690. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  9691. scopeToChild = isolateScope;
  9692. }
  9693. if (childLinkFn) {
  9694. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  9695. }
  9696. // POSTLINKING
  9697. for (i = postLinkFns.length - 1; i >= 0; i--) {
  9698. linkFn = postLinkFns[i];
  9699. invokeLinkFn(linkFn,
  9700. linkFn.isolateScope ? isolateScope : scope,
  9701. $element,
  9702. attrs,
  9703. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9704. transcludeFn
  9705. );
  9706. }
  9707. // Trigger $postLink lifecycle hooks
  9708. forEach(elementControllers, function(controller) {
  9709. var controllerInstance = controller.instance;
  9710. if (isFunction(controllerInstance.$postLink)) {
  9711. controllerInstance.$postLink();
  9712. }
  9713. });
  9714. // This is the function that is injected as `$transclude`.
  9715. // Note: all arguments are optional!
  9716. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  9717. var transcludeControllers;
  9718. // No scope passed in:
  9719. if (!isScope(scope)) {
  9720. slotName = futureParentElement;
  9721. futureParentElement = cloneAttachFn;
  9722. cloneAttachFn = scope;
  9723. scope = undefined;
  9724. }
  9725. if (hasElementTranscludeDirective) {
  9726. transcludeControllers = elementControllers;
  9727. }
  9728. if (!futureParentElement) {
  9729. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  9730. }
  9731. if (slotName) {
  9732. // slotTranscludeFn can be one of three things:
  9733. // * a transclude function - a filled slot
  9734. // * `null` - an optional slot that was not filled
  9735. // * `undefined` - a slot that was not declared (i.e. invalid)
  9736. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  9737. if (slotTranscludeFn) {
  9738. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9739. } else if (isUndefined(slotTranscludeFn)) {
  9740. throw $compileMinErr('noslot',
  9741. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  9742. 'Element: {1}',
  9743. slotName, startingTag($element));
  9744. }
  9745. } else {
  9746. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9747. }
  9748. }
  9749. }
  9750. }
  9751. function getControllers(directiveName, require, $element, elementControllers) {
  9752. var value;
  9753. if (isString(require)) {
  9754. var match = require.match(REQUIRE_PREFIX_REGEXP);
  9755. var name = require.substring(match[0].length);
  9756. var inheritType = match[1] || match[3];
  9757. var optional = match[2] === '?';
  9758. //If only parents then start at the parent element
  9759. if (inheritType === '^^') {
  9760. $element = $element.parent();
  9761. //Otherwise attempt getting the controller from elementControllers in case
  9762. //the element is transcluded (and has no data) and to avoid .data if possible
  9763. } else {
  9764. value = elementControllers && elementControllers[name];
  9765. value = value && value.instance;
  9766. }
  9767. if (!value) {
  9768. var dataName = '$' + name + 'Controller';
  9769. if (inheritType === '^^' && $element[0] && $element[0].nodeType === NODE_TYPE_DOCUMENT) {
  9770. // inheritedData() uses the documentElement when it finds the document, so we would
  9771. // require from the element itself.
  9772. value = null;
  9773. } else {
  9774. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  9775. }
  9776. }
  9777. if (!value && !optional) {
  9778. throw $compileMinErr('ctreq',
  9779. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  9780. name, directiveName);
  9781. }
  9782. } else if (isArray(require)) {
  9783. value = [];
  9784. for (var i = 0, ii = require.length; i < ii; i++) {
  9785. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  9786. }
  9787. } else if (isObject(require)) {
  9788. value = {};
  9789. forEach(require, function(controller, property) {
  9790. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  9791. });
  9792. }
  9793. return value || null;
  9794. }
  9795. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  9796. var elementControllers = createMap();
  9797. for (var controllerKey in controllerDirectives) {
  9798. var directive = controllerDirectives[controllerKey];
  9799. var locals = {
  9800. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  9801. $element: $element,
  9802. $attrs: attrs,
  9803. $transclude: transcludeFn
  9804. };
  9805. var controller = directive.controller;
  9806. if (controller === '@') {
  9807. controller = attrs[directive.name];
  9808. }
  9809. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  9810. // For directives with element transclusion the element is a comment.
  9811. // In this case .data will not attach any data.
  9812. // Instead, we save the controllers for the element in a local hash and attach to .data
  9813. // later, once we have the actual element.
  9814. elementControllers[directive.name] = controllerInstance;
  9815. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  9816. }
  9817. return elementControllers;
  9818. }
  9819. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  9820. // or child scope created. For instance:
  9821. // * if the directive has been pulled into a template because another directive with a higher priority
  9822. // asked for element transclusion
  9823. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  9824. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  9825. function markDirectiveScope(directives, isolateScope, newScope) {
  9826. for (var j = 0, jj = directives.length; j < jj; j++) {
  9827. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  9828. }
  9829. }
  9830. /**
  9831. * looks up the directive and decorates it with exception handling and proper parameters. We
  9832. * call this the boundDirective.
  9833. *
  9834. * @param {string} name name of the directive to look up.
  9835. * @param {string} location The directive must be found in specific format.
  9836. * String containing any of theses characters:
  9837. *
  9838. * * `E`: element name
  9839. * * `A': attribute
  9840. * * `C`: class
  9841. * * `M`: comment
  9842. * @returns {boolean} true if directive was added.
  9843. */
  9844. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9845. endAttrName) {
  9846. if (name === ignoreDirective) return null;
  9847. var match = null;
  9848. if (hasDirectives.hasOwnProperty(name)) {
  9849. for (var directive, directives = $injector.get(name + Suffix),
  9850. i = 0, ii = directives.length; i < ii; i++) {
  9851. directive = directives[i];
  9852. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9853. directive.restrict.indexOf(location) !== -1) {
  9854. if (startAttrName) {
  9855. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9856. }
  9857. if (!directive.$$bindings) {
  9858. var bindings = directive.$$bindings =
  9859. parseDirectiveBindings(directive, directive.name);
  9860. if (isObject(bindings.isolateScope)) {
  9861. directive.$$isolateBindings = bindings.isolateScope;
  9862. }
  9863. }
  9864. tDirectives.push(directive);
  9865. match = directive;
  9866. }
  9867. }
  9868. }
  9869. return match;
  9870. }
  9871. /**
  9872. * looks up the directive and returns true if it is a multi-element directive,
  9873. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9874. * together.
  9875. *
  9876. * @param {string} name name of the directive to look up.
  9877. * @returns true if directive was registered as multi-element.
  9878. */
  9879. function directiveIsMultiElement(name) {
  9880. if (hasDirectives.hasOwnProperty(name)) {
  9881. for (var directive, directives = $injector.get(name + Suffix),
  9882. i = 0, ii = directives.length; i < ii; i++) {
  9883. directive = directives[i];
  9884. if (directive.multiElement) {
  9885. return true;
  9886. }
  9887. }
  9888. }
  9889. return false;
  9890. }
  9891. /**
  9892. * When the element is replaced with HTML template then the new attributes
  9893. * on the template need to be merged with the existing attributes in the DOM.
  9894. * The desired effect is to have both of the attributes present.
  9895. *
  9896. * @param {object} dst destination attributes (original DOM)
  9897. * @param {object} src source attributes (from the directive template)
  9898. */
  9899. function mergeTemplateAttributes(dst, src) {
  9900. var srcAttr = src.$attr,
  9901. dstAttr = dst.$attr;
  9902. // reapply the old attributes to the new element
  9903. forEach(dst, function(value, key) {
  9904. if (key.charAt(0) !== '$') {
  9905. if (src[key] && src[key] !== value) {
  9906. if (value.length) {
  9907. value += (key === 'style' ? ';' : ' ') + src[key];
  9908. } else {
  9909. value = src[key];
  9910. }
  9911. }
  9912. dst.$set(key, value, true, srcAttr[key]);
  9913. }
  9914. });
  9915. // copy the new attributes on the old attrs object
  9916. forEach(src, function(value, key) {
  9917. // Check if we already set this attribute in the loop above.
  9918. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9919. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9920. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9921. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9922. dst[key] = value;
  9923. if (key !== 'class' && key !== 'style') {
  9924. dstAttr[key] = srcAttr[key];
  9925. }
  9926. }
  9927. });
  9928. }
  9929. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9930. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9931. var linkQueue = [],
  9932. afterTemplateNodeLinkFn,
  9933. afterTemplateChildLinkFn,
  9934. beforeTemplateCompileNode = $compileNode[0],
  9935. origAsyncDirective = directives.shift(),
  9936. derivedSyncDirective = inherit(origAsyncDirective, {
  9937. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9938. }),
  9939. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9940. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9941. : origAsyncDirective.templateUrl,
  9942. templateNamespace = origAsyncDirective.templateNamespace;
  9943. $compileNode.empty();
  9944. $templateRequest(templateUrl)
  9945. .then(function(content) {
  9946. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9947. content = denormalizeTemplate(content);
  9948. if (origAsyncDirective.replace) {
  9949. if (jqLiteIsTextNode(content)) {
  9950. $template = [];
  9951. } else {
  9952. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9953. }
  9954. compileNode = $template[0];
  9955. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9956. throw $compileMinErr('tplrt',
  9957. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9958. origAsyncDirective.name, templateUrl);
  9959. }
  9960. tempTemplateAttrs = {$attr: {}};
  9961. replaceWith($rootElement, $compileNode, compileNode);
  9962. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9963. if (isObject(origAsyncDirective.scope)) {
  9964. // the original directive that caused the template to be loaded async required
  9965. // an isolate scope
  9966. markDirectiveScope(templateDirectives, true);
  9967. }
  9968. directives = templateDirectives.concat(directives);
  9969. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9970. } else {
  9971. compileNode = beforeTemplateCompileNode;
  9972. $compileNode.html(content);
  9973. }
  9974. directives.unshift(derivedSyncDirective);
  9975. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9976. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9977. previousCompileContext);
  9978. forEach($rootElement, function(node, i) {
  9979. if (node === compileNode) {
  9980. $rootElement[i] = $compileNode[0];
  9981. }
  9982. });
  9983. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9984. while (linkQueue.length) {
  9985. var scope = linkQueue.shift(),
  9986. beforeTemplateLinkNode = linkQueue.shift(),
  9987. linkRootElement = linkQueue.shift(),
  9988. boundTranscludeFn = linkQueue.shift(),
  9989. linkNode = $compileNode[0];
  9990. if (scope.$$destroyed) continue;
  9991. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9992. var oldClasses = beforeTemplateLinkNode.className;
  9993. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9994. origAsyncDirective.replace)) {
  9995. // it was cloned therefore we have to clone as well.
  9996. linkNode = jqLiteClone(compileNode);
  9997. }
  9998. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9999. // Copy in CSS classes from original node
  10000. safeAddClass(jqLite(linkNode), oldClasses);
  10001. }
  10002. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  10003. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  10004. } else {
  10005. childBoundTranscludeFn = boundTranscludeFn;
  10006. }
  10007. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  10008. childBoundTranscludeFn);
  10009. }
  10010. linkQueue = null;
  10011. }).catch(function(error) {
  10012. if (isError(error)) {
  10013. $exceptionHandler(error);
  10014. }
  10015. });
  10016. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  10017. var childBoundTranscludeFn = boundTranscludeFn;
  10018. if (scope.$$destroyed) return;
  10019. if (linkQueue) {
  10020. linkQueue.push(scope,
  10021. node,
  10022. rootElement,
  10023. childBoundTranscludeFn);
  10024. } else {
  10025. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  10026. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  10027. }
  10028. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  10029. }
  10030. };
  10031. }
  10032. /**
  10033. * Sorting function for bound directives.
  10034. */
  10035. function byPriority(a, b) {
  10036. var diff = b.priority - a.priority;
  10037. if (diff !== 0) return diff;
  10038. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  10039. return a.index - b.index;
  10040. }
  10041. function assertNoDuplicate(what, previousDirective, directive, element) {
  10042. function wrapModuleNameIfDefined(moduleName) {
  10043. return moduleName ?
  10044. (' (module: ' + moduleName + ')') :
  10045. '';
  10046. }
  10047. if (previousDirective) {
  10048. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  10049. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  10050. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  10051. }
  10052. }
  10053. function addTextInterpolateDirective(directives, text) {
  10054. var interpolateFn = $interpolate(text, true);
  10055. if (interpolateFn) {
  10056. directives.push({
  10057. priority: 0,
  10058. compile: function textInterpolateCompileFn(templateNode) {
  10059. var templateNodeParent = templateNode.parent(),
  10060. hasCompileParent = !!templateNodeParent.length;
  10061. // When transcluding a template that has bindings in the root
  10062. // we don't have a parent and thus need to add the class during linking fn.
  10063. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  10064. return function textInterpolateLinkFn(scope, node) {
  10065. var parent = node.parent();
  10066. if (!hasCompileParent) compile.$$addBindingClass(parent);
  10067. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  10068. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  10069. node[0].nodeValue = value;
  10070. });
  10071. };
  10072. }
  10073. });
  10074. }
  10075. }
  10076. function wrapTemplate(type, template) {
  10077. type = lowercase(type || 'html');
  10078. switch (type) {
  10079. case 'svg':
  10080. case 'math':
  10081. var wrapper = window.document.createElement('div');
  10082. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  10083. return wrapper.childNodes[0].childNodes;
  10084. default:
  10085. return template;
  10086. }
  10087. }
  10088. function getTrustedAttrContext(nodeName, attrNormalizedName) {
  10089. if (attrNormalizedName === 'srcdoc') {
  10090. return $sce.HTML;
  10091. }
  10092. // All nodes with src attributes require a RESOURCE_URL value, except for
  10093. // img and various html5 media nodes, which require the MEDIA_URL context.
  10094. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  10095. if (['img', 'video', 'audio', 'source', 'track'].indexOf(nodeName) === -1) {
  10096. return $sce.RESOURCE_URL;
  10097. }
  10098. return $sce.MEDIA_URL;
  10099. } else if (attrNormalizedName === 'xlinkHref') {
  10100. // Some xlink:href are okay, most aren't
  10101. if (nodeName === 'image') return $sce.MEDIA_URL;
  10102. if (nodeName === 'a') return $sce.URL;
  10103. return $sce.RESOURCE_URL;
  10104. } else if (
  10105. // Formaction
  10106. (nodeName === 'form' && attrNormalizedName === 'action') ||
  10107. // If relative URLs can go where they are not expected to, then
  10108. // all sorts of trust issues can arise.
  10109. (nodeName === 'base' && attrNormalizedName === 'href') ||
  10110. // links can be stylesheets or imports, which can run script in the current origin
  10111. (nodeName === 'link' && attrNormalizedName === 'href')
  10112. ) {
  10113. return $sce.RESOURCE_URL;
  10114. } else if (nodeName === 'a' && (attrNormalizedName === 'href' ||
  10115. attrNormalizedName === 'ngHref')) {
  10116. return $sce.URL;
  10117. }
  10118. }
  10119. function getTrustedPropContext(nodeName, propNormalizedName) {
  10120. var prop = propNormalizedName.toLowerCase();
  10121. return PROP_CONTEXTS[nodeName + '|' + prop] || PROP_CONTEXTS['*|' + prop];
  10122. }
  10123. function sanitizeSrcsetPropertyValue(value) {
  10124. return sanitizeSrcset($sce.valueOf(value), 'ng-prop-srcset');
  10125. }
  10126. function addPropertyDirective(node, directives, attrName, propName) {
  10127. if (EVENT_HANDLER_ATTR_REGEXP.test(propName)) {
  10128. throw $compileMinErr('nodomevents', 'Property bindings for HTML DOM event properties are disallowed');
  10129. }
  10130. var nodeName = nodeName_(node);
  10131. var trustedContext = getTrustedPropContext(nodeName, propName);
  10132. var sanitizer = identity;
  10133. // Sanitize img[srcset] + source[srcset] values.
  10134. if (propName === 'srcset' && (nodeName === 'img' || nodeName === 'source')) {
  10135. sanitizer = sanitizeSrcsetPropertyValue;
  10136. } else if (trustedContext) {
  10137. sanitizer = $sce.getTrusted.bind($sce, trustedContext);
  10138. }
  10139. directives.push({
  10140. priority: 100,
  10141. compile: function ngPropCompileFn(_, attr) {
  10142. var ngPropGetter = $parse(attr[attrName]);
  10143. var ngPropWatch = $parse(attr[attrName], function sceValueOf(val) {
  10144. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  10145. return $sce.valueOf(val);
  10146. });
  10147. return {
  10148. pre: function ngPropPreLinkFn(scope, $element) {
  10149. function applyPropValue() {
  10150. var propValue = ngPropGetter(scope);
  10151. $element[0][propName] = sanitizer(propValue);
  10152. }
  10153. applyPropValue();
  10154. scope.$watch(ngPropWatch, applyPropValue);
  10155. }
  10156. };
  10157. }
  10158. });
  10159. }
  10160. function addEventDirective(directives, attrName, eventName) {
  10161. directives.push(
  10162. createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false)
  10163. );
  10164. }
  10165. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  10166. var nodeName = nodeName_(node);
  10167. var trustedContext = getTrustedAttrContext(nodeName, name);
  10168. var mustHaveExpression = !isNgAttr;
  10169. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  10170. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  10171. // no interpolation found -> ignore
  10172. if (!interpolateFn) return;
  10173. if (name === 'multiple' && nodeName === 'select') {
  10174. throw $compileMinErr('selmulti',
  10175. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  10176. startingTag(node));
  10177. }
  10178. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  10179. throw $compileMinErr('nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
  10180. }
  10181. directives.push({
  10182. priority: 100,
  10183. compile: function() {
  10184. return {
  10185. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  10186. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  10187. // If the attribute has changed since last $interpolate()ed
  10188. var newValue = attr[name];
  10189. if (newValue !== value) {
  10190. // we need to interpolate again since the attribute value has been updated
  10191. // (e.g. by another directive's compile function)
  10192. // ensure unset/empty values make interpolateFn falsy
  10193. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  10194. value = newValue;
  10195. }
  10196. // if attribute was updated so that there is no interpolation going on we don't want to
  10197. // register any observers
  10198. if (!interpolateFn) return;
  10199. // initialize attr object so that it's ready in case we need the value for isolate
  10200. // scope initialization, otherwise the value would not be available from isolate
  10201. // directive's linking fn during linking phase
  10202. attr[name] = interpolateFn(scope);
  10203. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  10204. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  10205. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  10206. //special case for class attribute addition + removal
  10207. //so that class changes can tap into the animation
  10208. //hooks provided by the $animate service. Be sure to
  10209. //skip animations when the first digest occurs (when
  10210. //both the new and the old values are the same) since
  10211. //the CSS classes are the non-interpolated values
  10212. if (name === 'class' && newValue !== oldValue) {
  10213. attr.$updateClass(newValue, oldValue);
  10214. } else {
  10215. attr.$set(name, newValue);
  10216. }
  10217. });
  10218. }
  10219. };
  10220. }
  10221. });
  10222. }
  10223. /**
  10224. * This is a special jqLite.replaceWith, which can replace items which
  10225. * have no parents, provided that the containing jqLite collection is provided.
  10226. *
  10227. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  10228. * in the root of the tree.
  10229. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  10230. * the shell, but replace its DOM node reference.
  10231. * @param {Node} newNode The new DOM node.
  10232. */
  10233. function replaceWith($rootElement, elementsToRemove, newNode) {
  10234. var firstElementToRemove = elementsToRemove[0],
  10235. removeCount = elementsToRemove.length,
  10236. parent = firstElementToRemove.parentNode,
  10237. i, ii;
  10238. if ($rootElement) {
  10239. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  10240. if ($rootElement[i] === firstElementToRemove) {
  10241. $rootElement[i++] = newNode;
  10242. for (var j = i, j2 = j + removeCount - 1,
  10243. jj = $rootElement.length;
  10244. j < jj; j++, j2++) {
  10245. if (j2 < jj) {
  10246. $rootElement[j] = $rootElement[j2];
  10247. } else {
  10248. delete $rootElement[j];
  10249. }
  10250. }
  10251. $rootElement.length -= removeCount - 1;
  10252. // If the replaced element is also the jQuery .context then replace it
  10253. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  10254. // http://api.jquery.com/context/
  10255. if ($rootElement.context === firstElementToRemove) {
  10256. $rootElement.context = newNode;
  10257. }
  10258. break;
  10259. }
  10260. }
  10261. }
  10262. if (parent) {
  10263. parent.replaceChild(newNode, firstElementToRemove);
  10264. }
  10265. // Append all the `elementsToRemove` to a fragment. This will...
  10266. // - remove them from the DOM
  10267. // - allow them to still be traversed with .nextSibling
  10268. // - allow a single fragment.qSA to fetch all elements being removed
  10269. var fragment = window.document.createDocumentFragment();
  10270. for (i = 0; i < removeCount; i++) {
  10271. fragment.appendChild(elementsToRemove[i]);
  10272. }
  10273. if (jqLite.hasData(firstElementToRemove)) {
  10274. // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private
  10275. // data here because there's no public interface in jQuery to do that and copying over
  10276. // event listeners (which is the main use of private data) wouldn't work anyway.
  10277. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  10278. // Remove $destroy event listeners from `firstElementToRemove`
  10279. jqLite(firstElementToRemove).off('$destroy');
  10280. }
  10281. // Cleanup any data/listeners on the elements and children.
  10282. // This includes invoking the $destroy event on any elements with listeners.
  10283. jqLite.cleanData(fragment.querySelectorAll('*'));
  10284. // Update the jqLite collection to only contain the `newNode`
  10285. for (i = 1; i < removeCount; i++) {
  10286. delete elementsToRemove[i];
  10287. }
  10288. elementsToRemove[0] = newNode;
  10289. elementsToRemove.length = 1;
  10290. }
  10291. function cloneAndAnnotateFn(fn, annotation) {
  10292. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  10293. }
  10294. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  10295. try {
  10296. linkFn(scope, $element, attrs, controllers, transcludeFn);
  10297. } catch (e) {
  10298. $exceptionHandler(e, startingTag($element));
  10299. }
  10300. }
  10301. function strictBindingsCheck(attrName, directiveName) {
  10302. if (strictComponentBindingsEnabled) {
  10303. throw $compileMinErr('missingattr',
  10304. 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!',
  10305. attrName, directiveName);
  10306. }
  10307. }
  10308. // Set up $watches for isolate scope and controller bindings.
  10309. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  10310. var removeWatchCollection = [];
  10311. var initialChanges = {};
  10312. var changes;
  10313. forEach(bindings, function initializeBinding(definition, scopeName) {
  10314. var attrName = definition.attrName,
  10315. optional = definition.optional,
  10316. mode = definition.mode, // @, =, <, or &
  10317. lastValue,
  10318. parentGet, parentSet, compare, removeWatch;
  10319. switch (mode) {
  10320. case '@':
  10321. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  10322. strictBindingsCheck(attrName, directive.name);
  10323. destination[scopeName] = attrs[attrName] = undefined;
  10324. }
  10325. removeWatch = attrs.$observe(attrName, function(value) {
  10326. if (isString(value) || isBoolean(value)) {
  10327. var oldValue = destination[scopeName];
  10328. recordChanges(scopeName, value, oldValue);
  10329. destination[scopeName] = value;
  10330. }
  10331. });
  10332. attrs.$$observers[attrName].$$scope = scope;
  10333. lastValue = attrs[attrName];
  10334. if (isString(lastValue)) {
  10335. // If the attribute has been provided then we trigger an interpolation to ensure
  10336. // the value is there for use in the link fn
  10337. destination[scopeName] = $interpolate(lastValue)(scope);
  10338. } else if (isBoolean(lastValue)) {
  10339. // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted
  10340. // the value to boolean rather than a string, so we special case this situation
  10341. destination[scopeName] = lastValue;
  10342. }
  10343. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  10344. removeWatchCollection.push(removeWatch);
  10345. break;
  10346. case '=':
  10347. if (!hasOwnProperty.call(attrs, attrName)) {
  10348. if (optional) break;
  10349. strictBindingsCheck(attrName, directive.name);
  10350. attrs[attrName] = undefined;
  10351. }
  10352. if (optional && !attrs[attrName]) break;
  10353. parentGet = $parse(attrs[attrName]);
  10354. if (parentGet.literal) {
  10355. compare = equals;
  10356. } else {
  10357. compare = simpleCompare;
  10358. }
  10359. parentSet = parentGet.assign || function() {
  10360. // reset the change, or we will throw this exception on every $digest
  10361. lastValue = destination[scopeName] = parentGet(scope);
  10362. throw $compileMinErr('nonassign',
  10363. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  10364. attrs[attrName], attrName, directive.name);
  10365. };
  10366. lastValue = destination[scopeName] = parentGet(scope);
  10367. var parentValueWatch = function parentValueWatch(parentValue) {
  10368. if (!compare(parentValue, destination[scopeName])) {
  10369. // we are out of sync and need to copy
  10370. if (!compare(parentValue, lastValue)) {
  10371. // parent changed and it has precedence
  10372. destination[scopeName] = parentValue;
  10373. } else {
  10374. // if the parent can be assigned then do so
  10375. parentSet(scope, parentValue = destination[scopeName]);
  10376. }
  10377. }
  10378. lastValue = parentValue;
  10379. return lastValue;
  10380. };
  10381. parentValueWatch.$stateful = true;
  10382. if (definition.collection) {
  10383. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  10384. } else {
  10385. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  10386. }
  10387. removeWatchCollection.push(removeWatch);
  10388. break;
  10389. case '<':
  10390. if (!hasOwnProperty.call(attrs, attrName)) {
  10391. if (optional) break;
  10392. strictBindingsCheck(attrName, directive.name);
  10393. attrs[attrName] = undefined;
  10394. }
  10395. if (optional && !attrs[attrName]) break;
  10396. parentGet = $parse(attrs[attrName]);
  10397. var isLiteral = parentGet.literal;
  10398. var initialValue = destination[scopeName] = parentGet(scope);
  10399. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  10400. removeWatch = scope[definition.collection ? '$watchCollection' : '$watch'](parentGet, function parentValueWatchAction(newValue, oldValue) {
  10401. if (oldValue === newValue) {
  10402. if (oldValue === initialValue || (isLiteral && equals(oldValue, initialValue))) {
  10403. return;
  10404. }
  10405. oldValue = initialValue;
  10406. }
  10407. recordChanges(scopeName, newValue, oldValue);
  10408. destination[scopeName] = newValue;
  10409. });
  10410. removeWatchCollection.push(removeWatch);
  10411. break;
  10412. case '&':
  10413. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  10414. strictBindingsCheck(attrName, directive.name);
  10415. }
  10416. // Don't assign Object.prototype method to scope
  10417. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  10418. // Don't assign noop to destination if expression is not valid
  10419. if (parentGet === noop && optional) break;
  10420. destination[scopeName] = function(locals) {
  10421. return parentGet(scope, locals);
  10422. };
  10423. break;
  10424. }
  10425. });
  10426. function recordChanges(key, currentValue, previousValue) {
  10427. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  10428. // If we have not already scheduled the top level onChangesQueue handler then do so now
  10429. if (!onChangesQueue) {
  10430. scope.$$postDigest(flushOnChangesQueue);
  10431. onChangesQueue = [];
  10432. }
  10433. // If we have not already queued a trigger of onChanges for this controller then do so now
  10434. if (!changes) {
  10435. changes = {};
  10436. onChangesQueue.push(triggerOnChangesHook);
  10437. }
  10438. // If the has been a change on this property already then we need to reuse the previous value
  10439. if (changes[key]) {
  10440. previousValue = changes[key].previousValue;
  10441. }
  10442. // Store this change
  10443. changes[key] = new SimpleChange(previousValue, currentValue);
  10444. }
  10445. }
  10446. function triggerOnChangesHook() {
  10447. destination.$onChanges(changes);
  10448. // Now clear the changes so that we schedule onChanges when more changes arrive
  10449. changes = undefined;
  10450. }
  10451. return {
  10452. initialChanges: initialChanges,
  10453. removeWatches: removeWatchCollection.length && function removeWatches() {
  10454. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  10455. removeWatchCollection[i]();
  10456. }
  10457. }
  10458. };
  10459. }
  10460. }];
  10461. }
  10462. function SimpleChange(previous, current) {
  10463. this.previousValue = previous;
  10464. this.currentValue = current;
  10465. }
  10466. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  10467. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  10468. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  10469. /**
  10470. * Converts all accepted directives format into proper directive name.
  10471. * @param name Name to normalize
  10472. */
  10473. function directiveNormalize(name) {
  10474. return name
  10475. .replace(PREFIX_REGEXP, '')
  10476. .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) {
  10477. return offset ? letter.toUpperCase() : letter;
  10478. });
  10479. }
  10480. /**
  10481. * @ngdoc type
  10482. * @name $compile.directive.Attributes
  10483. *
  10484. * @description
  10485. * A shared object between directive compile / linking functions which contains normalized DOM
  10486. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  10487. * needed since all of these are treated as equivalent in AngularJS:
  10488. *
  10489. * ```
  10490. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  10491. * ```
  10492. */
  10493. /**
  10494. * @ngdoc property
  10495. * @name $compile.directive.Attributes#$attr
  10496. *
  10497. * @description
  10498. * A map of DOM element attribute names to the normalized name. This is
  10499. * needed to do reverse lookup from normalized name back to actual name.
  10500. */
  10501. /**
  10502. * @ngdoc method
  10503. * @name $compile.directive.Attributes#$set
  10504. * @kind function
  10505. *
  10506. * @description
  10507. * Set DOM element attribute value.
  10508. *
  10509. *
  10510. * @param {string} name Normalized element attribute name of the property to modify. The name is
  10511. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  10512. * property to the original name.
  10513. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  10514. */
  10515. /**
  10516. * Closure compiler type information
  10517. */
  10518. function nodesetLinkingFn(
  10519. /* angular.Scope */ scope,
  10520. /* NodeList */ nodeList,
  10521. /* Element */ rootElement,
  10522. /* function(Function) */ boundTranscludeFn
  10523. ) {}
  10524. function directiveLinkingFn(
  10525. /* nodesetLinkingFn */ nodesetLinkingFn,
  10526. /* angular.Scope */ scope,
  10527. /* Node */ node,
  10528. /* Element */ rootElement,
  10529. /* function(Function) */ boundTranscludeFn
  10530. ) {}
  10531. function tokenDifference(str1, str2) {
  10532. var values = '',
  10533. tokens1 = str1.split(/\s+/),
  10534. tokens2 = str2.split(/\s+/);
  10535. outer:
  10536. for (var i = 0; i < tokens1.length; i++) {
  10537. var token = tokens1[i];
  10538. for (var j = 0; j < tokens2.length; j++) {
  10539. if (token === tokens2[j]) continue outer;
  10540. }
  10541. values += (values.length > 0 ? ' ' : '') + token;
  10542. }
  10543. return values;
  10544. }
  10545. function removeComments(jqNodes) {
  10546. jqNodes = jqLite(jqNodes);
  10547. var i = jqNodes.length;
  10548. if (i <= 1) {
  10549. return jqNodes;
  10550. }
  10551. while (i--) {
  10552. var node = jqNodes[i];
  10553. if (node.nodeType === NODE_TYPE_COMMENT ||
  10554. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  10555. splice.call(jqNodes, i, 1);
  10556. }
  10557. }
  10558. return jqNodes;
  10559. }
  10560. var $controllerMinErr = minErr('$controller');
  10561. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  10562. function identifierForController(controller, ident) {
  10563. if (ident && isString(ident)) return ident;
  10564. if (isString(controller)) {
  10565. var match = CNTRL_REG.exec(controller);
  10566. if (match) return match[3];
  10567. }
  10568. }
  10569. /**
  10570. * @ngdoc provider
  10571. * @name $controllerProvider
  10572. * @this
  10573. *
  10574. * @description
  10575. * The {@link ng.$controller $controller service} is used by AngularJS to create new
  10576. * controllers.
  10577. *
  10578. * This provider allows controller registration via the
  10579. * {@link ng.$controllerProvider#register register} method.
  10580. */
  10581. function $ControllerProvider() {
  10582. var controllers = {};
  10583. /**
  10584. * @ngdoc method
  10585. * @name $controllerProvider#has
  10586. * @param {string} name Controller name to check.
  10587. */
  10588. this.has = function(name) {
  10589. return controllers.hasOwnProperty(name);
  10590. };
  10591. /**
  10592. * @ngdoc method
  10593. * @name $controllerProvider#register
  10594. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  10595. * the names and the values are the constructors.
  10596. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  10597. * annotations in the array notation).
  10598. */
  10599. this.register = function(name, constructor) {
  10600. assertNotHasOwnProperty(name, 'controller');
  10601. if (isObject(name)) {
  10602. extend(controllers, name);
  10603. } else {
  10604. controllers[name] = constructor;
  10605. }
  10606. };
  10607. this.$get = ['$injector', function($injector) {
  10608. /**
  10609. * @ngdoc service
  10610. * @name $controller
  10611. * @requires $injector
  10612. *
  10613. * @param {Function|string} constructor If called with a function then it's considered to be the
  10614. * controller constructor function. Otherwise it's considered to be a string which is used
  10615. * to retrieve the controller constructor using the following steps:
  10616. *
  10617. * * check if a controller with given name is registered via `$controllerProvider`
  10618. * * check if evaluating the string on the current scope returns a constructor
  10619. *
  10620. * The string can use the `controller as property` syntax, where the controller instance is published
  10621. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  10622. * to work correctly.
  10623. *
  10624. * @param {Object} locals Injection locals for Controller.
  10625. * @return {Object} Instance of given controller.
  10626. *
  10627. * @description
  10628. * `$controller` service is responsible for instantiating controllers.
  10629. *
  10630. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  10631. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  10632. */
  10633. return function $controller(expression, locals, later, ident) {
  10634. // PRIVATE API:
  10635. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  10636. // If true, $controller will allocate the object with the correct
  10637. // prototype chain, but will not invoke the controller until a returned
  10638. // callback is invoked.
  10639. // param `ident` --- An optional label which overrides the label parsed from the controller
  10640. // expression, if any.
  10641. var instance, match, constructor, identifier;
  10642. later = later === true;
  10643. if (ident && isString(ident)) {
  10644. identifier = ident;
  10645. }
  10646. if (isString(expression)) {
  10647. match = expression.match(CNTRL_REG);
  10648. if (!match) {
  10649. throw $controllerMinErr('ctrlfmt',
  10650. 'Badly formed controller string \'{0}\'. ' +
  10651. 'Must match `__name__ as __id__` or `__name__`.', expression);
  10652. }
  10653. constructor = match[1];
  10654. identifier = identifier || match[3];
  10655. expression = controllers.hasOwnProperty(constructor)
  10656. ? controllers[constructor]
  10657. : getter(locals.$scope, constructor, true);
  10658. if (!expression) {
  10659. throw $controllerMinErr('ctrlreg',
  10660. 'The controller with the name \'{0}\' is not registered.', constructor);
  10661. }
  10662. assertArgFn(expression, constructor, true);
  10663. }
  10664. if (later) {
  10665. // Instantiate controller later:
  10666. // This machinery is used to create an instance of the object before calling the
  10667. // controller's constructor itself.
  10668. //
  10669. // This allows properties to be added to the controller before the constructor is
  10670. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  10671. //
  10672. // This feature is not intended for use by applications, and is thus not documented
  10673. // publicly.
  10674. // Object creation: http://jsperf.com/create-constructor/2
  10675. var controllerPrototype = (isArray(expression) ?
  10676. expression[expression.length - 1] : expression).prototype;
  10677. instance = Object.create(controllerPrototype || null);
  10678. if (identifier) {
  10679. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10680. }
  10681. return extend(function $controllerInit() {
  10682. var result = $injector.invoke(expression, instance, locals, constructor);
  10683. if (result !== instance && (isObject(result) || isFunction(result))) {
  10684. instance = result;
  10685. if (identifier) {
  10686. // If result changed, re-assign controllerAs value to scope.
  10687. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10688. }
  10689. }
  10690. return instance;
  10691. }, {
  10692. instance: instance,
  10693. identifier: identifier
  10694. });
  10695. }
  10696. instance = $injector.instantiate(expression, locals, constructor);
  10697. if (identifier) {
  10698. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10699. }
  10700. return instance;
  10701. };
  10702. function addIdentifier(locals, identifier, instance, name) {
  10703. if (!(locals && isObject(locals.$scope))) {
  10704. throw minErr('$controller')('noscp',
  10705. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  10706. name, identifier);
  10707. }
  10708. locals.$scope[identifier] = instance;
  10709. }
  10710. }];
  10711. }
  10712. /**
  10713. * @ngdoc service
  10714. * @name $document
  10715. * @requires $window
  10716. * @this
  10717. *
  10718. * @description
  10719. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  10720. *
  10721. * @example
  10722. <example module="documentExample" name="document">
  10723. <file name="index.html">
  10724. <div ng-controller="ExampleController">
  10725. <p>$document title: <b ng-bind="title"></b></p>
  10726. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  10727. </div>
  10728. </file>
  10729. <file name="script.js">
  10730. angular.module('documentExample', [])
  10731. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  10732. $scope.title = $document[0].title;
  10733. $scope.windowTitle = angular.element(window.document)[0].title;
  10734. }]);
  10735. </file>
  10736. </example>
  10737. */
  10738. function $DocumentProvider() {
  10739. this.$get = ['$window', function(window) {
  10740. return jqLite(window.document);
  10741. }];
  10742. }
  10743. /**
  10744. * @private
  10745. * @this
  10746. * Listens for document visibility change and makes the current status accessible.
  10747. */
  10748. function $$IsDocumentHiddenProvider() {
  10749. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  10750. var doc = $document[0];
  10751. var hidden = doc && doc.hidden;
  10752. $document.on('visibilitychange', changeListener);
  10753. $rootScope.$on('$destroy', function() {
  10754. $document.off('visibilitychange', changeListener);
  10755. });
  10756. function changeListener() {
  10757. hidden = doc.hidden;
  10758. }
  10759. return function() {
  10760. return hidden;
  10761. };
  10762. }];
  10763. }
  10764. /**
  10765. * @ngdoc service
  10766. * @name $exceptionHandler
  10767. * @requires ng.$log
  10768. * @this
  10769. *
  10770. * @description
  10771. * Any uncaught exception in AngularJS expressions is delegated to this service.
  10772. * The default implementation simply delegates to `$log.error` which logs it into
  10773. * the browser console.
  10774. *
  10775. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  10776. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  10777. *
  10778. * ## Example:
  10779. *
  10780. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  10781. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  10782. * of `$log.error()`.
  10783. *
  10784. * ```js
  10785. * angular.
  10786. * module('exceptionOverwrite', []).
  10787. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  10788. * return function myExceptionHandler(exception, cause) {
  10789. * logErrorsToBackend(exception, cause);
  10790. * $log.warn(exception, cause);
  10791. * };
  10792. * }]);
  10793. * ```
  10794. *
  10795. * <hr />
  10796. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  10797. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  10798. * (unless executed during a digest).
  10799. *
  10800. * If you wish, you can manually delegate exceptions, e.g.
  10801. * `try { ... } catch(e) { $exceptionHandler(e); }`
  10802. *
  10803. * @param {Error} exception Exception associated with the error.
  10804. * @param {string=} cause Optional information about the context in which
  10805. * the error was thrown.
  10806. *
  10807. */
  10808. function $ExceptionHandlerProvider() {
  10809. this.$get = ['$log', function($log) {
  10810. return function(exception, cause) {
  10811. $log.error.apply($log, arguments);
  10812. };
  10813. }];
  10814. }
  10815. var $$ForceReflowProvider = /** @this */ function() {
  10816. this.$get = ['$document', function($document) {
  10817. return function(domNode) {
  10818. //the line below will force the browser to perform a repaint so
  10819. //that all the animated elements within the animation frame will
  10820. //be properly updated and drawn on screen. This is required to
  10821. //ensure that the preparation animation is properly flushed so that
  10822. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  10823. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  10824. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  10825. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  10826. if (domNode) {
  10827. if (!domNode.nodeType && domNode instanceof jqLite) {
  10828. domNode = domNode[0];
  10829. }
  10830. } else {
  10831. domNode = $document[0].body;
  10832. }
  10833. return domNode.offsetWidth + 1;
  10834. };
  10835. }];
  10836. };
  10837. var APPLICATION_JSON = 'application/json';
  10838. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  10839. var JSON_START = /^\[|^\{(?!\{)/;
  10840. var JSON_ENDS = {
  10841. '[': /]$/,
  10842. '{': /}$/
  10843. };
  10844. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  10845. var $httpMinErr = minErr('$http');
  10846. function serializeValue(v) {
  10847. if (isObject(v)) {
  10848. return isDate(v) ? v.toISOString() : toJson(v);
  10849. }
  10850. return v;
  10851. }
  10852. /** @this */
  10853. function $HttpParamSerializerProvider() {
  10854. /**
  10855. * @ngdoc service
  10856. * @name $httpParamSerializer
  10857. * @description
  10858. *
  10859. * Default {@link $http `$http`} params serializer that converts objects to strings
  10860. * according to the following rules:
  10861. *
  10862. * * `{'foo': 'bar'}` results in `foo=bar`
  10863. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  10864. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  10865. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  10866. *
  10867. * Note that serializer will sort the request parameters alphabetically.
  10868. */
  10869. this.$get = function() {
  10870. return function ngParamSerializer(params) {
  10871. if (!params) return '';
  10872. var parts = [];
  10873. forEachSorted(params, function(value, key) {
  10874. if (value === null || isUndefined(value) || isFunction(value)) return;
  10875. if (isArray(value)) {
  10876. forEach(value, function(v) {
  10877. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  10878. });
  10879. } else {
  10880. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  10881. }
  10882. });
  10883. return parts.join('&');
  10884. };
  10885. };
  10886. }
  10887. /** @this */
  10888. function $HttpParamSerializerJQLikeProvider() {
  10889. /**
  10890. * @ngdoc service
  10891. * @name $httpParamSerializerJQLike
  10892. *
  10893. * @description
  10894. *
  10895. * Alternative {@link $http `$http`} params serializer that follows
  10896. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10897. * The serializer will also sort the params alphabetically.
  10898. *
  10899. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10900. *
  10901. * ```js
  10902. * $http({
  10903. * url: myUrl,
  10904. * method: 'GET',
  10905. * params: myParams,
  10906. * paramSerializer: '$httpParamSerializerJQLike'
  10907. * });
  10908. * ```
  10909. *
  10910. * It is also possible to set it as the default `paramSerializer` in the
  10911. * {@link $httpProvider#defaults `$httpProvider`}.
  10912. *
  10913. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10914. * form data for submission:
  10915. *
  10916. * ```js
  10917. * .controller(function($http, $httpParamSerializerJQLike) {
  10918. * //...
  10919. *
  10920. * $http({
  10921. * url: myUrl,
  10922. * method: 'POST',
  10923. * data: $httpParamSerializerJQLike(myData),
  10924. * headers: {
  10925. * 'Content-Type': 'application/x-www-form-urlencoded'
  10926. * }
  10927. * });
  10928. *
  10929. * });
  10930. * ```
  10931. *
  10932. */
  10933. this.$get = function() {
  10934. return function jQueryLikeParamSerializer(params) {
  10935. if (!params) return '';
  10936. var parts = [];
  10937. serialize(params, '', true);
  10938. return parts.join('&');
  10939. function serialize(toSerialize, prefix, topLevel) {
  10940. if (isArray(toSerialize)) {
  10941. forEach(toSerialize, function(value, index) {
  10942. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10943. });
  10944. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10945. forEachSorted(toSerialize, function(value, key) {
  10946. serialize(value, prefix +
  10947. (topLevel ? '' : '[') +
  10948. key +
  10949. (topLevel ? '' : ']'));
  10950. });
  10951. } else {
  10952. if (isFunction(toSerialize)) {
  10953. toSerialize = toSerialize();
  10954. }
  10955. parts.push(encodeUriQuery(prefix) + '=' +
  10956. (toSerialize == null ? '' : encodeUriQuery(serializeValue(toSerialize))));
  10957. }
  10958. }
  10959. };
  10960. };
  10961. }
  10962. function defaultHttpResponseTransform(data, headers) {
  10963. if (isString(data)) {
  10964. // Strip json vulnerability protection prefix and trim whitespace
  10965. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10966. if (tempData) {
  10967. var contentType = headers('Content-Type');
  10968. var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);
  10969. if (hasJsonContentType || isJsonLike(tempData)) {
  10970. try {
  10971. data = fromJson(tempData);
  10972. } catch (e) {
  10973. if (!hasJsonContentType) {
  10974. return data;
  10975. }
  10976. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10977. 'Parse error: "{1}"', data, e);
  10978. }
  10979. }
  10980. }
  10981. }
  10982. return data;
  10983. }
  10984. function isJsonLike(str) {
  10985. var jsonStart = str.match(JSON_START);
  10986. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10987. }
  10988. /**
  10989. * Parse headers into key value object
  10990. *
  10991. * @param {string} headers Raw headers as a string
  10992. * @returns {Object} Parsed headers as key value object
  10993. */
  10994. function parseHeaders(headers) {
  10995. var parsed = createMap(), i;
  10996. function fillInParsed(key, val) {
  10997. if (key) {
  10998. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10999. }
  11000. }
  11001. if (isString(headers)) {
  11002. forEach(headers.split('\n'), function(line) {
  11003. i = line.indexOf(':');
  11004. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  11005. });
  11006. } else if (isObject(headers)) {
  11007. forEach(headers, function(headerVal, headerKey) {
  11008. fillInParsed(lowercase(headerKey), trim(headerVal));
  11009. });
  11010. }
  11011. return parsed;
  11012. }
  11013. /**
  11014. * Returns a function that provides access to parsed headers.
  11015. *
  11016. * Headers are lazy parsed when first requested.
  11017. * @see parseHeaders
  11018. *
  11019. * @param {(string|Object)} headers Headers to provide access to.
  11020. * @returns {function(string=)} Returns a getter function which if called with:
  11021. *
  11022. * - if called with an argument returns a single header value or null
  11023. * - if called with no arguments returns an object containing all headers.
  11024. */
  11025. function headersGetter(headers) {
  11026. var headersObj;
  11027. return function(name) {
  11028. if (!headersObj) headersObj = parseHeaders(headers);
  11029. if (name) {
  11030. var value = headersObj[lowercase(name)];
  11031. if (value === undefined) {
  11032. value = null;
  11033. }
  11034. return value;
  11035. }
  11036. return headersObj;
  11037. };
  11038. }
  11039. /**
  11040. * Chain all given functions
  11041. *
  11042. * This function is used for both request and response transforming
  11043. *
  11044. * @param {*} data Data to transform.
  11045. * @param {function(string=)} headers HTTP headers getter fn.
  11046. * @param {number} status HTTP status code of the response.
  11047. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  11048. * @returns {*} Transformed data.
  11049. */
  11050. function transformData(data, headers, status, fns) {
  11051. if (isFunction(fns)) {
  11052. return fns(data, headers, status);
  11053. }
  11054. forEach(fns, function(fn) {
  11055. data = fn(data, headers, status);
  11056. });
  11057. return data;
  11058. }
  11059. function isSuccess(status) {
  11060. return 200 <= status && status < 300;
  11061. }
  11062. /**
  11063. * @ngdoc provider
  11064. * @name $httpProvider
  11065. * @this
  11066. *
  11067. * @description
  11068. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  11069. */
  11070. function $HttpProvider() {
  11071. /**
  11072. * @ngdoc property
  11073. * @name $httpProvider#defaults
  11074. * @description
  11075. *
  11076. * Object containing default values for all {@link ng.$http $http} requests.
  11077. *
  11078. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  11079. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  11080. * by default. See {@link $http#caching $http Caching} for more information.
  11081. *
  11082. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  11083. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  11084. * setting default headers.
  11085. * - **`defaults.headers.common`**
  11086. * - **`defaults.headers.post`**
  11087. * - **`defaults.headers.put`**
  11088. * - **`defaults.headers.patch`**
  11089. *
  11090. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  11091. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  11092. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  11093. *
  11094. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  11095. * used to the prepare string representation of request parameters (specified as an object).
  11096. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  11097. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  11098. *
  11099. * - **`defaults.transformRequest`** -
  11100. * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` -
  11101. * An array of functions (or a single function) which are applied to the request data.
  11102. * By default, this is an array with one request transformation function:
  11103. *
  11104. * - If the `data` property of the request configuration object contains an object, serialize it
  11105. * into JSON format.
  11106. *
  11107. * - **`defaults.transformResponse`** -
  11108. * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` -
  11109. * An array of functions (or a single function) which are applied to the response data. By default,
  11110. * this is an array which applies one response transformation function that does two things:
  11111. *
  11112. * - If XSRF prefix is detected, strip it
  11113. * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).
  11114. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  11115. * deserialize it using a JSON parser.
  11116. *
  11117. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  11118. * Defaults value is `'XSRF-TOKEN'`.
  11119. *
  11120. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  11121. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  11122. *
  11123. */
  11124. var defaults = this.defaults = {
  11125. // transform incoming response data
  11126. transformResponse: [defaultHttpResponseTransform],
  11127. // transform outgoing request data
  11128. transformRequest: [function(d) {
  11129. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  11130. }],
  11131. // default headers
  11132. headers: {
  11133. common: {
  11134. 'Accept': 'application/json, text/plain, */*'
  11135. },
  11136. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  11137. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  11138. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  11139. },
  11140. xsrfCookieName: 'XSRF-TOKEN',
  11141. xsrfHeaderName: 'X-XSRF-TOKEN',
  11142. paramSerializer: '$httpParamSerializer',
  11143. jsonpCallbackParam: 'callback'
  11144. };
  11145. var useApplyAsync = false;
  11146. /**
  11147. * @ngdoc method
  11148. * @name $httpProvider#useApplyAsync
  11149. * @description
  11150. *
  11151. * Configure $http service to combine processing of multiple http responses received at around
  11152. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  11153. * significant performance improvement for bigger applications that make many HTTP requests
  11154. * concurrently (common during application bootstrap).
  11155. *
  11156. * Defaults to false. If no value is specified, returns the current configured value.
  11157. *
  11158. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  11159. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  11160. * to load and share the same digest cycle.
  11161. *
  11162. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  11163. * otherwise, returns the current configured value.
  11164. */
  11165. this.useApplyAsync = function(value) {
  11166. if (isDefined(value)) {
  11167. useApplyAsync = !!value;
  11168. return this;
  11169. }
  11170. return useApplyAsync;
  11171. };
  11172. /**
  11173. * @ngdoc property
  11174. * @name $httpProvider#interceptors
  11175. * @description
  11176. *
  11177. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  11178. * pre-processing of request or postprocessing of responses.
  11179. *
  11180. * These service factories are ordered by request, i.e. they are applied in the same order as the
  11181. * array, on request, but reverse order, on response.
  11182. *
  11183. * {@link ng.$http#interceptors Interceptors detailed info}
  11184. */
  11185. var interceptorFactories = this.interceptors = [];
  11186. /**
  11187. * @ngdoc property
  11188. * @name $httpProvider#xsrfTrustedOrigins
  11189. * @description
  11190. *
  11191. * Array containing URLs whose origins are trusted to receive the XSRF token. See the
  11192. * {@link ng.$http#security-considerations Security Considerations} sections for more details on
  11193. * XSRF.
  11194. *
  11195. * **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme),
  11196. * the [hostname](https://en.wikipedia.org/wiki/Hostname) and the
  11197. * [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and
  11198. * `https:`, the port number can be omitted if using th default ports (80 and 443 respectively).
  11199. * Examples: `http://example.com`, `https://api.example.com:9876`
  11200. *
  11201. * <div class="alert alert-warning">
  11202. * It is not possible to trust specific URLs/paths. The `path`, `query` and `fragment` parts
  11203. * of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be
  11204. * treated as `https://foo.com`, meaning that **all** requests to URLs starting with
  11205. * `https://foo.com/` will include the XSRF token.
  11206. * </div>
  11207. *
  11208. * @example
  11209. *
  11210. * ```js
  11211. * // App served from `https://example.com/`.
  11212. * angular.
  11213. * module('xsrfTrustedOriginsExample', []).
  11214. * config(['$httpProvider', function($httpProvider) {
  11215. * $httpProvider.xsrfTrustedOrigins.push('https://api.example.com');
  11216. * }]).
  11217. * run(['$http', function($http) {
  11218. * // The XSRF token will be sent.
  11219. * $http.get('https://api.example.com/preferences').then(...);
  11220. *
  11221. * // The XSRF token will NOT be sent.
  11222. * $http.get('https://stats.example.com/activity').then(...);
  11223. * }]);
  11224. * ```
  11225. */
  11226. var xsrfTrustedOrigins = this.xsrfTrustedOrigins = [];
  11227. /**
  11228. * @ngdoc property
  11229. * @name $httpProvider#xsrfWhitelistedOrigins
  11230. * @description
  11231. *
  11232. * @deprecated
  11233. * sinceVersion="1.8.1"
  11234. *
  11235. * This property is deprecated. Use {@link $httpProvider#xsrfTrustedOrigins xsrfTrustedOrigins}
  11236. * instead.
  11237. */
  11238. Object.defineProperty(this, 'xsrfWhitelistedOrigins', {
  11239. get: function() {
  11240. return this.xsrfTrustedOrigins;
  11241. },
  11242. set: function(origins) {
  11243. this.xsrfTrustedOrigins = origins;
  11244. }
  11245. });
  11246. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  11247. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  11248. var defaultCache = $cacheFactory('$http');
  11249. /**
  11250. * Make sure that default param serializer is exposed as a function
  11251. */
  11252. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  11253. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  11254. /**
  11255. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  11256. * The reversal is needed so that we can build up the interception chain around the
  11257. * server request.
  11258. */
  11259. var reversedInterceptors = [];
  11260. forEach(interceptorFactories, function(interceptorFactory) {
  11261. reversedInterceptors.unshift(isString(interceptorFactory)
  11262. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  11263. });
  11264. /**
  11265. * A function to check request URLs against a list of allowed origins.
  11266. */
  11267. var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfTrustedOrigins);
  11268. /**
  11269. * @ngdoc service
  11270. * @kind function
  11271. * @name $http
  11272. * @requires ng.$httpBackend
  11273. * @requires $cacheFactory
  11274. * @requires $rootScope
  11275. * @requires $q
  11276. * @requires $injector
  11277. *
  11278. * @description
  11279. * The `$http` service is a core AngularJS service that facilitates communication with the remote
  11280. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  11281. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  11282. *
  11283. * For unit testing applications that use `$http` service, see
  11284. * {@link ngMock.$httpBackend $httpBackend mock}.
  11285. *
  11286. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  11287. * $resource} service.
  11288. *
  11289. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  11290. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  11291. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  11292. *
  11293. *
  11294. * ## General usage
  11295. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  11296. * that is used to generate an HTTP request and returns a {@link ng.$q promise} that is
  11297. * resolved (request success) or rejected (request failure) with a
  11298. * {@link ng.$http#$http-returns response} object.
  11299. *
  11300. * ```js
  11301. * // Simple GET request example:
  11302. * $http({
  11303. * method: 'GET',
  11304. * url: '/someUrl'
  11305. * }).then(function successCallback(response) {
  11306. * // this callback will be called asynchronously
  11307. * // when the response is available
  11308. * }, function errorCallback(response) {
  11309. * // called asynchronously if an error occurs
  11310. * // or server returns response with an error status.
  11311. * });
  11312. * ```
  11313. *
  11314. *
  11315. * ## Shortcut methods
  11316. *
  11317. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  11318. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  11319. * last argument.
  11320. *
  11321. * ```js
  11322. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  11323. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  11324. * ```
  11325. *
  11326. * Complete list of shortcut methods:
  11327. *
  11328. * - {@link ng.$http#get $http.get}
  11329. * - {@link ng.$http#head $http.head}
  11330. * - {@link ng.$http#post $http.post}
  11331. * - {@link ng.$http#put $http.put}
  11332. * - {@link ng.$http#delete $http.delete}
  11333. * - {@link ng.$http#jsonp $http.jsonp}
  11334. * - {@link ng.$http#patch $http.patch}
  11335. *
  11336. *
  11337. * ## Writing Unit Tests that use $http
  11338. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  11339. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  11340. * request using trained responses.
  11341. *
  11342. * ```
  11343. * $httpBackend.expectGET(...);
  11344. * $http.get(...);
  11345. * $httpBackend.flush();
  11346. * ```
  11347. *
  11348. * ## Setting HTTP Headers
  11349. *
  11350. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  11351. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  11352. * object, which currently contains this default configuration:
  11353. *
  11354. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  11355. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  11356. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  11357. * - `Content-Type: application/json`
  11358. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  11359. * - `Content-Type: application/json`
  11360. *
  11361. * To add or overwrite these defaults, simply add or remove a property from these configuration
  11362. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  11363. * with the lowercased HTTP method name as the key, e.g.
  11364. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  11365. *
  11366. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  11367. * fashion. For example:
  11368. *
  11369. * ```
  11370. * module.run(function($http) {
  11371. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  11372. * });
  11373. * ```
  11374. *
  11375. * In addition, you can supply a `headers` property in the config object passed when
  11376. * calling `$http(config)`, which overrides the defaults without changing them globally.
  11377. *
  11378. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  11379. * Use the `headers` property, setting the desired header to `undefined`. For example:
  11380. *
  11381. * ```js
  11382. * var req = {
  11383. * method: 'POST',
  11384. * url: 'http://example.com',
  11385. * headers: {
  11386. * 'Content-Type': undefined
  11387. * },
  11388. * data: { test: 'test' }
  11389. * }
  11390. *
  11391. * $http(req).then(function(){...}, function(){...});
  11392. * ```
  11393. *
  11394. * ## Transforming Requests and Responses
  11395. *
  11396. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  11397. * and `transformResponse`. These properties can be a single function that returns
  11398. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  11399. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  11400. *
  11401. * <div class="alert alert-warning">
  11402. * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  11403. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  11404. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  11405. * function will be reflected on the scope and in any templates where the object is data-bound.
  11406. * To prevent this, transform functions should have no side-effects.
  11407. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  11408. * </div>
  11409. *
  11410. * ### Default Transformations
  11411. *
  11412. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  11413. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  11414. * then these will be applied.
  11415. *
  11416. * You can augment or replace the default transformations by modifying these properties by adding to or
  11417. * replacing the array.
  11418. *
  11419. * AngularJS provides the following default transformations:
  11420. *
  11421. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is
  11422. * an array with one function that does the following:
  11423. *
  11424. * - If the `data` property of the request configuration object contains an object, serialize it
  11425. * into JSON format.
  11426. *
  11427. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is
  11428. * an array with one function that does the following:
  11429. *
  11430. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  11431. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  11432. * deserialize it using a JSON parser.
  11433. *
  11434. *
  11435. * ### Overriding the Default Transformations Per Request
  11436. *
  11437. * If you wish to override the request/response transformations only for a single request then provide
  11438. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  11439. * into `$http`.
  11440. *
  11441. * Note that if you provide these properties on the config object the default transformations will be
  11442. * overwritten. If you wish to augment the default transformations then you must include them in your
  11443. * local transformation array.
  11444. *
  11445. * The following code demonstrates adding a new response transformation to be run after the default response
  11446. * transformations have been run.
  11447. *
  11448. * ```js
  11449. * function appendTransform(defaults, transform) {
  11450. *
  11451. * // We can't guarantee that the default transformation is an array
  11452. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  11453. *
  11454. * // Append the new transformation to the defaults
  11455. * return defaults.concat(transform);
  11456. * }
  11457. *
  11458. * $http({
  11459. * url: '...',
  11460. * method: 'GET',
  11461. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  11462. * return doTransform(value);
  11463. * })
  11464. * });
  11465. * ```
  11466. *
  11467. *
  11468. * ## Caching
  11469. *
  11470. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  11471. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  11472. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  11473. * precedence over the default cache value.
  11474. *
  11475. * In order to:
  11476. * * cache all responses - set the default cache value to TRUE or to a cache object
  11477. * * cache a specific response - set config.cache value to TRUE or to a cache object
  11478. *
  11479. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  11480. * then the default `$cacheFactory("$http")` object is used.
  11481. *
  11482. * The default cache value can be set by updating the
  11483. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  11484. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  11485. *
  11486. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  11487. * the relevant cache object. The next time the same request is made, the response is returned
  11488. * from the cache without sending a request to the server.
  11489. *
  11490. * Take note that:
  11491. *
  11492. * * Only GET and JSONP requests are cached.
  11493. * * The cache key is the request URL including search parameters; headers are not considered.
  11494. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  11495. * * If multiple identical requests are made using the same cache, which is not yet populated,
  11496. * one request will be made to the server and remaining requests will return the same response.
  11497. * * A cache-control header on the response does not affect if or how responses are cached.
  11498. *
  11499. *
  11500. * ## Interceptors
  11501. *
  11502. * Before you start creating interceptors, be sure to understand the
  11503. * {@link ng.$q $q and deferred/promise APIs}.
  11504. *
  11505. * For purposes of global error handling, authentication, or any kind of synchronous or
  11506. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  11507. * able to intercept requests before they are handed to the server and
  11508. * responses before they are handed over to the application code that
  11509. * initiated these requests. The interceptors leverage the {@link ng.$q
  11510. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  11511. *
  11512. * The interceptors are service factories that are registered with the `$httpProvider` by
  11513. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  11514. * injected with dependencies (if specified) and returns the interceptor.
  11515. *
  11516. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  11517. *
  11518. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  11519. * modify the `config` object or create a new one. The function needs to return the `config`
  11520. * object directly, or a promise containing the `config` or a new `config` object.
  11521. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  11522. * resolved with a rejection.
  11523. * * `response`: interceptors get called with http `response` object. The function is free to
  11524. * modify the `response` object or create a new one. The function needs to return the `response`
  11525. * object directly, or as a promise containing the `response` or a new `response` object.
  11526. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  11527. * resolved with a rejection.
  11528. *
  11529. *
  11530. * ```js
  11531. * // register the interceptor as a service
  11532. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  11533. * return {
  11534. * // optional method
  11535. * 'request': function(config) {
  11536. * // do something on success
  11537. * return config;
  11538. * },
  11539. *
  11540. * // optional method
  11541. * 'requestError': function(rejection) {
  11542. * // do something on error
  11543. * if (canRecover(rejection)) {
  11544. * return responseOrNewPromise
  11545. * }
  11546. * return $q.reject(rejection);
  11547. * },
  11548. *
  11549. *
  11550. *
  11551. * // optional method
  11552. * 'response': function(response) {
  11553. * // do something on success
  11554. * return response;
  11555. * },
  11556. *
  11557. * // optional method
  11558. * 'responseError': function(rejection) {
  11559. * // do something on error
  11560. * if (canRecover(rejection)) {
  11561. * return responseOrNewPromise
  11562. * }
  11563. * return $q.reject(rejection);
  11564. * }
  11565. * };
  11566. * });
  11567. *
  11568. * $httpProvider.interceptors.push('myHttpInterceptor');
  11569. *
  11570. *
  11571. * // alternatively, register the interceptor via an anonymous factory
  11572. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  11573. * return {
  11574. * 'request': function(config) {
  11575. * // same as above
  11576. * },
  11577. *
  11578. * 'response': function(response) {
  11579. * // same as above
  11580. * }
  11581. * };
  11582. * });
  11583. * ```
  11584. *
  11585. * ## Security Considerations
  11586. *
  11587. * When designing web applications, consider security threats from:
  11588. *
  11589. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  11590. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  11591. *
  11592. * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes
  11593. * pre-configured with strategies that address these issues, but for this to work backend server
  11594. * cooperation is required.
  11595. *
  11596. * ### JSON Vulnerability Protection
  11597. *
  11598. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  11599. * allows third party website to turn your JSON resource URL into
  11600. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  11601. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  11602. * AngularJS will automatically strip the prefix before processing it as JSON.
  11603. *
  11604. * For example if your server needs to return:
  11605. * ```js
  11606. * ['one','two']
  11607. * ```
  11608. *
  11609. * which is vulnerable to attack, your server can return:
  11610. * ```js
  11611. * )]}',
  11612. * ['one','two']
  11613. * ```
  11614. *
  11615. * AngularJS will strip the prefix, before processing the JSON.
  11616. *
  11617. *
  11618. * ### Cross Site Request Forgery (XSRF) Protection
  11619. *
  11620. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  11621. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  11622. * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the
  11623. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  11624. * header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read
  11625. * the cookie, your server can be assured that the XHR came from JavaScript running on your
  11626. * domain.
  11627. *
  11628. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  11629. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  11630. * server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be
  11631. * sure that only JavaScript running on your domain could have sent the request. The token must
  11632. * be unique for each user and must be verifiable by the server (to prevent the JavaScript from
  11633. * making up its own tokens). We recommend that the token is a digest of your site's
  11634. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  11635. * for added security.
  11636. *
  11637. * The header will &mdash; by default &mdash; **not** be set for cross-domain requests. This
  11638. * prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining
  11639. * access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you
  11640. * want to, you can trust additional origins to also receive the XSRF token, by adding them
  11641. * to {@link ng.$httpProvider#xsrfTrustedOrigins xsrfTrustedOrigins}. This might be
  11642. * useful, for example, if your application, served from `example.com`, needs to access your API
  11643. * at `api.example.com`.
  11644. * See {@link ng.$httpProvider#xsrfTrustedOrigins $httpProvider.xsrfTrustedOrigins} for
  11645. * more details.
  11646. *
  11647. * <div class="alert alert-danger">
  11648. * **Warning**<br />
  11649. * Only trusted origins that you have control over and make sure you understand the
  11650. * implications of doing so.
  11651. * </div>
  11652. *
  11653. * The name of the cookie and the header can be specified using the `xsrfCookieName` and
  11654. * `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time,
  11655. * `$http.defaults` at run-time, or the per-request config object.
  11656. *
  11657. * In order to prevent collisions in environments where multiple AngularJS apps share the
  11658. * same domain or subdomain, we recommend that each application uses a unique cookie name.
  11659. *
  11660. *
  11661. * @param {object} config Object describing the request to be made and how it should be
  11662. * processed. The object has following properties:
  11663. *
  11664. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  11665. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  11666. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11667. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  11668. * with the `paramSerializer` and appended as GET parameters.
  11669. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  11670. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  11671. * HTTP headers to send to the server. If the return value of a function is null, the
  11672. * header will not be sent. Functions accept a config object as an argument.
  11673. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  11674. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  11675. * The handler will be called in the context of a `$apply` block.
  11676. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  11677. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  11678. * The handler will be called in the context of a `$apply` block.
  11679. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  11680. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  11681. * - **transformRequest** –
  11682. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  11683. * transform function or an array of such functions. The transform function takes the http
  11684. * request body and headers and returns its transformed (typically serialized) version.
  11685. * See {@link ng.$http#overriding-the-default-transformations-per-request
  11686. * Overriding the Default Transformations}
  11687. * - **transformResponse** –
  11688. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  11689. * transform function or an array of such functions. The transform function takes the http
  11690. * response body, headers and status and returns its transformed (typically deserialized) version.
  11691. * See {@link ng.$http#overriding-the-default-transformations-per-request
  11692. * Overriding the Default Transformations}
  11693. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  11694. * prepare the string representation of request parameters (specified as an object).
  11695. * If specified as string, it is interpreted as function registered with the
  11696. * {@link $injector $injector}, which means you can create your own serializer
  11697. * by registering it as a {@link auto.$provide#service service}.
  11698. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  11699. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  11700. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  11701. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  11702. * See {@link $http#caching $http Caching} for more information.
  11703. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  11704. * that should abort the request when resolved.
  11705. *
  11706. * A numerical timeout or a promise returned from {@link ng.$timeout $timeout}, will set
  11707. * the `xhrStatus` in the {@link $http#$http-returns response} to "timeout", and any other
  11708. * resolved promise will set it to "abort", following standard XMLHttpRequest behavior.
  11709. *
  11710. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  11711. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  11712. * for more information.
  11713. * - **responseType** - `{string}` - see
  11714. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  11715. *
  11716. * @returns {HttpPromise} A {@link ng.$q `Promise}` that will be resolved (request success)
  11717. * or rejected (request failure) with a response object.
  11718. *
  11719. * The response object has these properties:
  11720. *
  11721. * - **data** – `{string|Object}` – The response body transformed with
  11722. * the transform functions.
  11723. * - **status** – `{number}` – HTTP status code of the response.
  11724. * - **headers** – `{function([headerName])}` – Header getter function.
  11725. * - **config** – `{Object}` – The configuration object that was used
  11726. * to generate the request.
  11727. * - **statusText** – `{string}` – HTTP status text of the response.
  11728. * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest
  11729. * (`complete`, `error`, `timeout` or `abort`).
  11730. *
  11731. *
  11732. * A response status code between 200 and 299 is considered a success status
  11733. * and will result in the success callback being called. Any response status
  11734. * code outside of that range is considered an error status and will result
  11735. * in the error callback being called.
  11736. * Also, status codes less than -1 are normalized to zero. -1 usually means
  11737. * the request was aborted, e.g. using a `config.timeout`. More information
  11738. * about the status might be available in the `xhrStatus` property.
  11739. *
  11740. * Note that if the response is a redirect, XMLHttpRequest will transparently
  11741. * follow it, meaning that the outcome (success or error) will be determined
  11742. * by the final response status code.
  11743. *
  11744. *
  11745. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  11746. * requests. This is primarily meant to be used for debugging purposes.
  11747. *
  11748. *
  11749. * @example
  11750. <example module="httpExample" name="http-service">
  11751. <file name="index.html">
  11752. <div ng-controller="FetchController">
  11753. <select ng-model="method" aria-label="Request method">
  11754. <option>GET</option>
  11755. <option>JSONP</option>
  11756. </select>
  11757. <input type="text" ng-model="url" size="80" aria-label="URL" />
  11758. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  11759. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  11760. <button id="samplejsonpbtn"
  11761. ng-click="updateModel('JSONP',
  11762. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  11763. Sample JSONP
  11764. </button>
  11765. <button id="invalidjsonpbtn"
  11766. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  11767. Invalid JSONP
  11768. </button>
  11769. <pre>http status code: {{status}}</pre>
  11770. <pre>http response data: {{data}}</pre>
  11771. </div>
  11772. </file>
  11773. <file name="script.js">
  11774. angular.module('httpExample', [])
  11775. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  11776. // We must add the JSONP endpoint that we are using to the trusted list to show that we trust it
  11777. $sceDelegateProvider.trustedResourceUrlList([
  11778. 'self',
  11779. 'https://angularjs.org/**'
  11780. ]);
  11781. }])
  11782. .controller('FetchController', ['$scope', '$http', '$templateCache',
  11783. function($scope, $http, $templateCache) {
  11784. $scope.method = 'GET';
  11785. $scope.url = 'http-hello.html';
  11786. $scope.fetch = function() {
  11787. $scope.code = null;
  11788. $scope.response = null;
  11789. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  11790. then(function(response) {
  11791. $scope.status = response.status;
  11792. $scope.data = response.data;
  11793. }, function(response) {
  11794. $scope.data = response.data || 'Request failed';
  11795. $scope.status = response.status;
  11796. });
  11797. };
  11798. $scope.updateModel = function(method, url) {
  11799. $scope.method = method;
  11800. $scope.url = url;
  11801. };
  11802. }]);
  11803. </file>
  11804. <file name="http-hello.html">
  11805. Hello, $http!
  11806. </file>
  11807. <file name="protractor.js" type="protractor">
  11808. var status = element(by.binding('status'));
  11809. var data = element(by.binding('data'));
  11810. var fetchBtn = element(by.id('fetchbtn'));
  11811. var sampleGetBtn = element(by.id('samplegetbtn'));
  11812. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  11813. it('should make an xhr GET request', function() {
  11814. sampleGetBtn.click();
  11815. fetchBtn.click();
  11816. expect(status.getText()).toMatch('200');
  11817. expect(data.getText()).toMatch(/Hello, \$http!/);
  11818. });
  11819. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  11820. // it('should make a JSONP request to angularjs.org', function() {
  11821. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  11822. // sampleJsonpBtn.click();
  11823. // fetchBtn.click();
  11824. // expect(status.getText()).toMatch('200');
  11825. // expect(data.getText()).toMatch(/Super Hero!/);
  11826. // });
  11827. it('should make JSONP request to invalid URL and invoke the error handler',
  11828. function() {
  11829. invalidJsonpBtn.click();
  11830. fetchBtn.click();
  11831. expect(status.getText()).toMatch('0');
  11832. expect(data.getText()).toMatch('Request failed');
  11833. });
  11834. </file>
  11835. </example>
  11836. */
  11837. function $http(requestConfig) {
  11838. if (!isObject(requestConfig)) {
  11839. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  11840. }
  11841. if (!isString($sce.valueOf(requestConfig.url))) {
  11842. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  11843. }
  11844. var config = extend({
  11845. method: 'get',
  11846. transformRequest: defaults.transformRequest,
  11847. transformResponse: defaults.transformResponse,
  11848. paramSerializer: defaults.paramSerializer,
  11849. jsonpCallbackParam: defaults.jsonpCallbackParam
  11850. }, requestConfig);
  11851. config.headers = mergeHeaders(requestConfig);
  11852. config.method = uppercase(config.method);
  11853. config.paramSerializer = isString(config.paramSerializer) ?
  11854. $injector.get(config.paramSerializer) : config.paramSerializer;
  11855. $browser.$$incOutstandingRequestCount('$http');
  11856. var requestInterceptors = [];
  11857. var responseInterceptors = [];
  11858. var promise = $q.resolve(config);
  11859. // apply interceptors
  11860. forEach(reversedInterceptors, function(interceptor) {
  11861. if (interceptor.request || interceptor.requestError) {
  11862. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  11863. }
  11864. if (interceptor.response || interceptor.responseError) {
  11865. responseInterceptors.push(interceptor.response, interceptor.responseError);
  11866. }
  11867. });
  11868. promise = chainInterceptors(promise, requestInterceptors);
  11869. promise = promise.then(serverRequest);
  11870. promise = chainInterceptors(promise, responseInterceptors);
  11871. promise = promise.finally(completeOutstandingRequest);
  11872. return promise;
  11873. function chainInterceptors(promise, interceptors) {
  11874. for (var i = 0, ii = interceptors.length; i < ii;) {
  11875. var thenFn = interceptors[i++];
  11876. var rejectFn = interceptors[i++];
  11877. promise = promise.then(thenFn, rejectFn);
  11878. }
  11879. interceptors.length = 0;
  11880. return promise;
  11881. }
  11882. function completeOutstandingRequest() {
  11883. $browser.$$completeOutstandingRequest(noop, '$http');
  11884. }
  11885. function executeHeaderFns(headers, config) {
  11886. var headerContent, processedHeaders = {};
  11887. forEach(headers, function(headerFn, header) {
  11888. if (isFunction(headerFn)) {
  11889. headerContent = headerFn(config);
  11890. if (headerContent != null) {
  11891. processedHeaders[header] = headerContent;
  11892. }
  11893. } else {
  11894. processedHeaders[header] = headerFn;
  11895. }
  11896. });
  11897. return processedHeaders;
  11898. }
  11899. function mergeHeaders(config) {
  11900. var defHeaders = defaults.headers,
  11901. reqHeaders = extend({}, config.headers),
  11902. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  11903. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  11904. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  11905. defaultHeadersIteration:
  11906. for (defHeaderName in defHeaders) {
  11907. lowercaseDefHeaderName = lowercase(defHeaderName);
  11908. for (reqHeaderName in reqHeaders) {
  11909. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  11910. continue defaultHeadersIteration;
  11911. }
  11912. }
  11913. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  11914. }
  11915. // execute if header value is a function for merged headers
  11916. return executeHeaderFns(reqHeaders, shallowCopy(config));
  11917. }
  11918. function serverRequest(config) {
  11919. var headers = config.headers;
  11920. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  11921. // strip content-type if data is undefined
  11922. if (isUndefined(reqData)) {
  11923. forEach(headers, function(value, header) {
  11924. if (lowercase(header) === 'content-type') {
  11925. delete headers[header];
  11926. }
  11927. });
  11928. }
  11929. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  11930. config.withCredentials = defaults.withCredentials;
  11931. }
  11932. // send request
  11933. return sendReq(config, reqData).then(transformResponse, transformResponse);
  11934. }
  11935. function transformResponse(response) {
  11936. // make a copy since the response must be cacheable
  11937. var resp = extend({}, response);
  11938. resp.data = transformData(response.data, response.headers, response.status,
  11939. config.transformResponse);
  11940. return (isSuccess(response.status))
  11941. ? resp
  11942. : $q.reject(resp);
  11943. }
  11944. }
  11945. $http.pendingRequests = [];
  11946. /**
  11947. * @ngdoc method
  11948. * @name $http#get
  11949. *
  11950. * @description
  11951. * Shortcut method to perform `GET` request.
  11952. *
  11953. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11954. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11955. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11956. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11957. * See {@link ng.$http#$http-returns `$http()` return value}.
  11958. */
  11959. /**
  11960. * @ngdoc method
  11961. * @name $http#delete
  11962. *
  11963. * @description
  11964. * Shortcut method to perform `DELETE` request.
  11965. *
  11966. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11967. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11968. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11969. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11970. * See {@link ng.$http#$http-returns `$http()` return value}.
  11971. */
  11972. /**
  11973. * @ngdoc method
  11974. * @name $http#head
  11975. *
  11976. * @description
  11977. * Shortcut method to perform `HEAD` request.
  11978. *
  11979. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11980. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11981. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11982. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11983. * See {@link ng.$http#$http-returns `$http()` return value}.
  11984. */
  11985. /**
  11986. * @ngdoc method
  11987. * @name $http#jsonp
  11988. *
  11989. * @description
  11990. * Shortcut method to perform `JSONP` request.
  11991. *
  11992. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  11993. * the url must be declared, via {@link $sce} as a trusted resource URL.
  11994. * You can trust a URL by adding it to the trusted resource URL list via
  11995. * {@link $sceDelegateProvider#trustedResourceUrlList `$sceDelegateProvider.trustedResourceUrlList`} or
  11996. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  11997. *
  11998. * You should avoid generating the URL for the JSONP request from user provided data.
  11999. * Provide additional query parameters via `params` property of the `config` parameter, rather than
  12000. * modifying the URL itself.
  12001. *
  12002. * JSONP requests must specify a callback to be used in the response from the server. This callback
  12003. * is passed as a query parameter in the request. You must specify the name of this parameter by
  12004. * setting the `jsonpCallbackParam` property on the request config object.
  12005. *
  12006. * ```
  12007. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  12008. * ```
  12009. *
  12010. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  12011. * Initially this is set to `'callback'`.
  12012. *
  12013. * <div class="alert alert-danger">
  12014. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  12015. * parameter value should go.
  12016. * </div>
  12017. *
  12018. * If you would like to customise where and how the callbacks are stored then try overriding
  12019. * or decorating the {@link $jsonpCallbacks} service.
  12020. *
  12021. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  12022. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  12023. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  12024. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  12025. * See {@link ng.$http#$http-returns `$http()` return value}.
  12026. */
  12027. createShortMethods('get', 'delete', 'head', 'jsonp');
  12028. /**
  12029. * @ngdoc method
  12030. * @name $http#post
  12031. *
  12032. * @description
  12033. * Shortcut method to perform `POST` request.
  12034. *
  12035. * @param {string} url Relative or absolute URL specifying the destination of the request
  12036. * @param {*} data Request content
  12037. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  12038. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  12039. * See {@link ng.$http#$http-returns `$http()` return value}.
  12040. */
  12041. /**
  12042. * @ngdoc method
  12043. * @name $http#put
  12044. *
  12045. * @description
  12046. * Shortcut method to perform `PUT` request.
  12047. *
  12048. * @param {string} url Relative or absolute URL specifying the destination of the request
  12049. * @param {*} data Request content
  12050. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  12051. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  12052. * See {@link ng.$http#$http-returns `$http()` return value}.
  12053. */
  12054. /**
  12055. * @ngdoc method
  12056. * @name $http#patch
  12057. *
  12058. * @description
  12059. * Shortcut method to perform `PATCH` request.
  12060. *
  12061. * @param {string} url Relative or absolute URL specifying the destination of the request
  12062. * @param {*} data Request content
  12063. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  12064. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  12065. * See {@link ng.$http#$http-returns `$http()` return value}.
  12066. */
  12067. createShortMethodsWithData('post', 'put', 'patch');
  12068. /**
  12069. * @ngdoc property
  12070. * @name $http#defaults
  12071. *
  12072. * @description
  12073. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  12074. * default headers, withCredentials as well as request and response transformations.
  12075. *
  12076. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  12077. */
  12078. $http.defaults = defaults;
  12079. return $http;
  12080. function createShortMethods(names) {
  12081. forEach(arguments, function(name) {
  12082. $http[name] = function(url, config) {
  12083. return $http(extend({}, config || {}, {
  12084. method: name,
  12085. url: url
  12086. }));
  12087. };
  12088. });
  12089. }
  12090. function createShortMethodsWithData(name) {
  12091. forEach(arguments, function(name) {
  12092. $http[name] = function(url, data, config) {
  12093. return $http(extend({}, config || {}, {
  12094. method: name,
  12095. url: url,
  12096. data: data
  12097. }));
  12098. };
  12099. });
  12100. }
  12101. /**
  12102. * Makes the request.
  12103. *
  12104. * !!! ACCESSES CLOSURE VARS:
  12105. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  12106. */
  12107. function sendReq(config, reqData) {
  12108. var deferred = $q.defer(),
  12109. promise = deferred.promise,
  12110. cache,
  12111. cachedResp,
  12112. reqHeaders = config.headers,
  12113. isJsonp = lowercase(config.method) === 'jsonp',
  12114. url = config.url;
  12115. if (isJsonp) {
  12116. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  12117. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  12118. url = $sce.getTrustedResourceUrl(url);
  12119. } else if (!isString(url)) {
  12120. // If it is not a string then the URL must be a $sce trusted object
  12121. url = $sce.valueOf(url);
  12122. }
  12123. url = buildUrl(url, config.paramSerializer(config.params));
  12124. if (isJsonp) {
  12125. // Check the url and add the JSONP callback placeholder
  12126. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  12127. }
  12128. $http.pendingRequests.push(config);
  12129. promise.then(removePendingReq, removePendingReq);
  12130. if ((config.cache || defaults.cache) && config.cache !== false &&
  12131. (config.method === 'GET' || config.method === 'JSONP')) {
  12132. cache = isObject(config.cache) ? config.cache
  12133. : isObject(/** @type {?} */ (defaults).cache)
  12134. ? /** @type {?} */ (defaults).cache
  12135. : defaultCache;
  12136. }
  12137. if (cache) {
  12138. cachedResp = cache.get(url);
  12139. if (isDefined(cachedResp)) {
  12140. if (isPromiseLike(cachedResp)) {
  12141. // cached request has already been sent, but there is no response yet
  12142. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  12143. } else {
  12144. // serving from cache
  12145. if (isArray(cachedResp)) {
  12146. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);
  12147. } else {
  12148. resolvePromise(cachedResp, 200, {}, 'OK', 'complete');
  12149. }
  12150. }
  12151. } else {
  12152. // put the promise for the non-transformed response into cache as a placeholder
  12153. cache.put(url, promise);
  12154. }
  12155. }
  12156. // if we won't have the response in cache, set the xsrf headers and
  12157. // send the request to the backend
  12158. if (isUndefined(cachedResp)) {
  12159. var xsrfValue = urlIsAllowedOrigin(config.url)
  12160. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  12161. : undefined;
  12162. if (xsrfValue) {
  12163. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  12164. }
  12165. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  12166. config.withCredentials, config.responseType,
  12167. createApplyHandlers(config.eventHandlers),
  12168. createApplyHandlers(config.uploadEventHandlers));
  12169. }
  12170. return promise;
  12171. function createApplyHandlers(eventHandlers) {
  12172. if (eventHandlers) {
  12173. var applyHandlers = {};
  12174. forEach(eventHandlers, function(eventHandler, key) {
  12175. applyHandlers[key] = function(event) {
  12176. if (useApplyAsync) {
  12177. $rootScope.$applyAsync(callEventHandler);
  12178. } else if ($rootScope.$$phase) {
  12179. callEventHandler();
  12180. } else {
  12181. $rootScope.$apply(callEventHandler);
  12182. }
  12183. function callEventHandler() {
  12184. eventHandler(event);
  12185. }
  12186. };
  12187. });
  12188. return applyHandlers;
  12189. }
  12190. }
  12191. /**
  12192. * Callback registered to $httpBackend():
  12193. * - caches the response if desired
  12194. * - resolves the raw $http promise
  12195. * - calls $apply
  12196. */
  12197. function done(status, response, headersString, statusText, xhrStatus) {
  12198. if (cache) {
  12199. if (isSuccess(status)) {
  12200. cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);
  12201. } else {
  12202. // remove promise from the cache
  12203. cache.remove(url);
  12204. }
  12205. }
  12206. function resolveHttpPromise() {
  12207. resolvePromise(response, status, headersString, statusText, xhrStatus);
  12208. }
  12209. if (useApplyAsync) {
  12210. $rootScope.$applyAsync(resolveHttpPromise);
  12211. } else {
  12212. resolveHttpPromise();
  12213. if (!$rootScope.$$phase) $rootScope.$apply();
  12214. }
  12215. }
  12216. /**
  12217. * Resolves the raw $http promise.
  12218. */
  12219. function resolvePromise(response, status, headers, statusText, xhrStatus) {
  12220. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  12221. status = status >= -1 ? status : 0;
  12222. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  12223. data: response,
  12224. status: status,
  12225. headers: headersGetter(headers),
  12226. config: config,
  12227. statusText: statusText,
  12228. xhrStatus: xhrStatus
  12229. });
  12230. }
  12231. function resolvePromiseWithResult(result) {
  12232. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);
  12233. }
  12234. function removePendingReq() {
  12235. var idx = $http.pendingRequests.indexOf(config);
  12236. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  12237. }
  12238. }
  12239. function buildUrl(url, serializedParams) {
  12240. if (serializedParams.length > 0) {
  12241. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  12242. }
  12243. return url;
  12244. }
  12245. function sanitizeJsonpCallbackParam(url, cbKey) {
  12246. var parts = url.split('?');
  12247. if (parts.length > 2) {
  12248. // Throw if the url contains more than one `?` query indicator
  12249. throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url);
  12250. }
  12251. var params = parseKeyValue(parts[1]);
  12252. forEach(params, function(value, key) {
  12253. if (value === 'JSON_CALLBACK') {
  12254. // Throw if the url already contains a reference to JSON_CALLBACK
  12255. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  12256. }
  12257. if (key === cbKey) {
  12258. // Throw if the callback param was already provided
  12259. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url);
  12260. }
  12261. });
  12262. // Add in the JSON_CALLBACK callback param value
  12263. url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK';
  12264. return url;
  12265. }
  12266. }];
  12267. }
  12268. /**
  12269. * @ngdoc service
  12270. * @name $xhrFactory
  12271. * @this
  12272. *
  12273. * @description
  12274. * Factory function used to create XMLHttpRequest objects.
  12275. *
  12276. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  12277. *
  12278. * ```
  12279. * angular.module('myApp', [])
  12280. * .factory('$xhrFactory', function() {
  12281. * return function createXhr(method, url) {
  12282. * return new window.XMLHttpRequest({mozSystem: true});
  12283. * };
  12284. * });
  12285. * ```
  12286. *
  12287. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  12288. * @param {string} url URL of the request.
  12289. */
  12290. function $xhrFactoryProvider() {
  12291. this.$get = function() {
  12292. return function createXhr() {
  12293. return new window.XMLHttpRequest();
  12294. };
  12295. };
  12296. }
  12297. /**
  12298. * @ngdoc service
  12299. * @name $httpBackend
  12300. * @requires $jsonpCallbacks
  12301. * @requires $document
  12302. * @requires $xhrFactory
  12303. * @this
  12304. *
  12305. * @description
  12306. * HTTP backend used by the {@link ng.$http service} that delegates to
  12307. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  12308. *
  12309. * You should never need to use this service directly, instead use the higher-level abstractions:
  12310. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  12311. *
  12312. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  12313. * $httpBackend} which can be trained with responses.
  12314. */
  12315. function $HttpBackendProvider() {
  12316. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  12317. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  12318. }];
  12319. }
  12320. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  12321. // TODO(vojta): fix the signature
  12322. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  12323. url = url || $browser.url();
  12324. if (lowercase(method) === 'jsonp') {
  12325. var callbackPath = callbacks.createCallback(url);
  12326. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  12327. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  12328. var response = (status === 200) && callbacks.getResponse(callbackPath);
  12329. completeRequest(callback, status, response, '', text, 'complete');
  12330. callbacks.removeCallback(callbackPath);
  12331. });
  12332. } else {
  12333. var xhr = createXhr(method, url);
  12334. var abortedByTimeout = false;
  12335. xhr.open(method, url, true);
  12336. forEach(headers, function(value, key) {
  12337. if (isDefined(value)) {
  12338. xhr.setRequestHeader(key, value);
  12339. }
  12340. });
  12341. xhr.onload = function requestLoaded() {
  12342. var statusText = xhr.statusText || '';
  12343. // responseText is the old-school way of retrieving response (supported by IE9)
  12344. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  12345. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  12346. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  12347. var status = xhr.status === 1223 ? 204 : xhr.status;
  12348. // fix status code when it is 0 (0 status is undocumented).
  12349. // Occurs when accessing file resources or on Android 4.1 stock browser
  12350. // while retrieving files from application cache.
  12351. if (status === 0) {
  12352. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  12353. }
  12354. completeRequest(callback,
  12355. status,
  12356. response,
  12357. xhr.getAllResponseHeaders(),
  12358. statusText,
  12359. 'complete');
  12360. };
  12361. var requestError = function() {
  12362. // The response is always empty
  12363. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  12364. completeRequest(callback, -1, null, null, '', 'error');
  12365. };
  12366. var requestAborted = function() {
  12367. completeRequest(callback, -1, null, null, '', abortedByTimeout ? 'timeout' : 'abort');
  12368. };
  12369. var requestTimeout = function() {
  12370. // The response is always empty
  12371. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  12372. completeRequest(callback, -1, null, null, '', 'timeout');
  12373. };
  12374. xhr.onerror = requestError;
  12375. xhr.ontimeout = requestTimeout;
  12376. xhr.onabort = requestAborted;
  12377. forEach(eventHandlers, function(value, key) {
  12378. xhr.addEventListener(key, value);
  12379. });
  12380. forEach(uploadEventHandlers, function(value, key) {
  12381. xhr.upload.addEventListener(key, value);
  12382. });
  12383. if (withCredentials) {
  12384. xhr.withCredentials = true;
  12385. }
  12386. if (responseType) {
  12387. try {
  12388. xhr.responseType = responseType;
  12389. } catch (e) {
  12390. // WebKit added support for the json responseType value on 09/03/2013
  12391. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  12392. // known to throw when setting the value "json" as the response type. Other older
  12393. // browsers implementing the responseType
  12394. //
  12395. // The json response type can be ignored if not supported, because JSON payloads are
  12396. // parsed on the client-side regardless.
  12397. if (responseType !== 'json') {
  12398. throw e;
  12399. }
  12400. }
  12401. }
  12402. xhr.send(isUndefined(post) ? null : post);
  12403. }
  12404. // Since we are using xhr.abort() when a request times out, we have to set a flag that
  12405. // indicates to requestAborted if the request timed out or was aborted.
  12406. //
  12407. // http.timeout = numerical timeout timeout
  12408. // http.timeout = $timeout timeout
  12409. // http.timeout = promise abort
  12410. // xhr.abort() abort (The xhr object is normally inaccessible, but
  12411. // can be exposed with the xhrFactory)
  12412. if (timeout > 0) {
  12413. var timeoutId = $browserDefer(function() {
  12414. timeoutRequest('timeout');
  12415. }, timeout);
  12416. } else if (isPromiseLike(timeout)) {
  12417. timeout.then(function() {
  12418. timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort');
  12419. });
  12420. }
  12421. function timeoutRequest(reason) {
  12422. abortedByTimeout = reason === 'timeout';
  12423. if (jsonpDone) {
  12424. jsonpDone();
  12425. }
  12426. if (xhr) {
  12427. xhr.abort();
  12428. }
  12429. }
  12430. function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {
  12431. // cancel timeout and subsequent timeout promise resolution
  12432. if (isDefined(timeoutId)) {
  12433. $browserDefer.cancel(timeoutId);
  12434. }
  12435. jsonpDone = xhr = null;
  12436. callback(status, response, headersString, statusText, xhrStatus);
  12437. }
  12438. };
  12439. function jsonpReq(url, callbackPath, done) {
  12440. url = url.replace('JSON_CALLBACK', callbackPath);
  12441. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  12442. // - fetches local scripts via XHR and evals them
  12443. // - adds and immediately removes script elements from the document
  12444. var script = rawDocument.createElement('script'), callback = null;
  12445. script.type = 'text/javascript';
  12446. script.src = url;
  12447. script.async = true;
  12448. callback = function(event) {
  12449. script.removeEventListener('load', callback);
  12450. script.removeEventListener('error', callback);
  12451. rawDocument.body.removeChild(script);
  12452. script = null;
  12453. var status = -1;
  12454. var text = 'unknown';
  12455. if (event) {
  12456. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  12457. event = { type: 'error' };
  12458. }
  12459. text = event.type;
  12460. status = event.type === 'error' ? 404 : 200;
  12461. }
  12462. if (done) {
  12463. done(status, text);
  12464. }
  12465. };
  12466. script.addEventListener('load', callback);
  12467. script.addEventListener('error', callback);
  12468. rawDocument.body.appendChild(script);
  12469. return callback;
  12470. }
  12471. }
  12472. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  12473. $interpolateMinErr.throwNoconcat = function(text) {
  12474. throw $interpolateMinErr('noconcat',
  12475. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  12476. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  12477. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  12478. };
  12479. $interpolateMinErr.interr = function(text, err) {
  12480. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  12481. };
  12482. /**
  12483. * @ngdoc provider
  12484. * @name $interpolateProvider
  12485. * @this
  12486. *
  12487. * @description
  12488. *
  12489. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  12490. *
  12491. * <div class="alert alert-danger">
  12492. * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS
  12493. * template within a Python Jinja template (or any other template language). Mixing templating
  12494. * languages is **very dangerous**. The embedding template language will not safely escape AngularJS
  12495. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  12496. * security bugs!
  12497. * </div>
  12498. *
  12499. * @example
  12500. <example name="custom-interpolation-markup" module="customInterpolationApp">
  12501. <file name="index.html">
  12502. <script>
  12503. var customInterpolationApp = angular.module('customInterpolationApp', []);
  12504. customInterpolationApp.config(function($interpolateProvider) {
  12505. $interpolateProvider.startSymbol('//');
  12506. $interpolateProvider.endSymbol('//');
  12507. });
  12508. customInterpolationApp.controller('DemoController', function() {
  12509. this.label = "This binding is brought you by // interpolation symbols.";
  12510. });
  12511. </script>
  12512. <div ng-controller="DemoController as demo">
  12513. //demo.label//
  12514. </div>
  12515. </file>
  12516. <file name="protractor.js" type="protractor">
  12517. it('should interpolate binding with custom symbols', function() {
  12518. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  12519. });
  12520. </file>
  12521. </example>
  12522. */
  12523. function $InterpolateProvider() {
  12524. var startSymbol = '{{';
  12525. var endSymbol = '}}';
  12526. /**
  12527. * @ngdoc method
  12528. * @name $interpolateProvider#startSymbol
  12529. * @description
  12530. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  12531. *
  12532. * @param {string=} value new value to set the starting symbol to.
  12533. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  12534. */
  12535. this.startSymbol = function(value) {
  12536. if (value) {
  12537. startSymbol = value;
  12538. return this;
  12539. }
  12540. return startSymbol;
  12541. };
  12542. /**
  12543. * @ngdoc method
  12544. * @name $interpolateProvider#endSymbol
  12545. * @description
  12546. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12547. *
  12548. * @param {string=} value new value to set the ending symbol to.
  12549. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  12550. */
  12551. this.endSymbol = function(value) {
  12552. if (value) {
  12553. endSymbol = value;
  12554. return this;
  12555. }
  12556. return endSymbol;
  12557. };
  12558. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  12559. var startSymbolLength = startSymbol.length,
  12560. endSymbolLength = endSymbol.length,
  12561. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  12562. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  12563. function escape(ch) {
  12564. return '\\\\\\' + ch;
  12565. }
  12566. function unescapeText(text) {
  12567. return text.replace(escapedStartRegexp, startSymbol).
  12568. replace(escapedEndRegexp, endSymbol);
  12569. }
  12570. // TODO: this is the same as the constantWatchDelegate in parse.js
  12571. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  12572. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  12573. unwatch();
  12574. return constantInterp(scope);
  12575. }, listener, objectEquality);
  12576. return unwatch;
  12577. }
  12578. /**
  12579. * @ngdoc service
  12580. * @name $interpolate
  12581. * @kind function
  12582. *
  12583. * @requires $parse
  12584. * @requires $sce
  12585. *
  12586. * @description
  12587. *
  12588. * Compiles a string with markup into an interpolation function. This service is used by the
  12589. * HTML {@link ng.$compile $compile} service for data binding. See
  12590. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  12591. * interpolation markup.
  12592. *
  12593. *
  12594. * ```js
  12595. * var $interpolate = ...; // injected
  12596. * var exp = $interpolate('Hello {{name | uppercase}}!');
  12597. * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULARJS!');
  12598. * ```
  12599. *
  12600. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  12601. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  12602. * evaluate to a value other than `undefined`.
  12603. *
  12604. * ```js
  12605. * var $interpolate = ...; // injected
  12606. * var context = {greeting: 'Hello', name: undefined };
  12607. *
  12608. * // default "forgiving" mode
  12609. * var exp = $interpolate('{{greeting}} {{name}}!');
  12610. * expect(exp(context)).toEqual('Hello !');
  12611. *
  12612. * // "allOrNothing" mode
  12613. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  12614. * expect(exp(context)).toBeUndefined();
  12615. * context.name = 'AngularJS';
  12616. * expect(exp(context)).toEqual('Hello AngularJS!');
  12617. * ```
  12618. *
  12619. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  12620. *
  12621. * #### Escaped Interpolation
  12622. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  12623. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  12624. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  12625. * or binding.
  12626. *
  12627. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  12628. * degree, while also enabling code examples to work without relying on the
  12629. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  12630. *
  12631. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  12632. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  12633. * interpolation start/end markers with their escaped counterparts.**
  12634. *
  12635. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  12636. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  12637. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  12638. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  12639. * this is typically useful only when user-data is used in rendering a template from the server, or
  12640. * when otherwise untrusted data is used by a directive.
  12641. *
  12642. * <example name="interpolation">
  12643. * <file name="index.html">
  12644. * <div ng-init="username='A user'">
  12645. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  12646. * </p>
  12647. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  12648. * application, but fails to accomplish their task, because the server has correctly
  12649. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  12650. * characters.</p>
  12651. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  12652. * from the database by an administrator.</p>
  12653. * </div>
  12654. * </file>
  12655. * </example>
  12656. *
  12657. * @knownIssue
  12658. * It is currently not possible for an interpolated expression to contain the interpolation end
  12659. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  12660. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  12661. *
  12662. * @knownIssue
  12663. * All directives and components must use the standard `{{` `}}` interpolation symbols
  12664. * in their templates. If you change the application interpolation symbols the {@link $compile}
  12665. * service will attempt to denormalize the standard symbols to the custom symbols.
  12666. * The denormalization process is not clever enough to know not to replace instances of the standard
  12667. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  12668. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  12669. *
  12670. * ```
  12671. * <div data-context='{"context":{"id":3,"type":"page"}}">
  12672. * ```
  12673. *
  12674. * The workaround is to ensure that such instances are separated by whitespace:
  12675. * ```
  12676. * <div data-context='{"context":{"id":3,"type":"page"} }">
  12677. * ```
  12678. *
  12679. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  12680. *
  12681. * @param {string} text The text with markup to interpolate.
  12682. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  12683. * embedded expression in order to return an interpolation function. Strings with no
  12684. * embedded expression will return null for the interpolation function.
  12685. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  12686. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  12687. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  12688. * provides Strict Contextual Escaping for details.
  12689. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  12690. * unless all embedded expressions evaluate to a value other than `undefined`.
  12691. * @returns {function(context)} an interpolation function which is used to compute the
  12692. * interpolated string. The function has these parameters:
  12693. *
  12694. * - `context`: evaluation context for all expressions embedded in the interpolated text
  12695. */
  12696. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  12697. var contextAllowsConcatenation = trustedContext === $sce.URL || trustedContext === $sce.MEDIA_URL;
  12698. // Provide a quick exit and simplified result function for text with no interpolation
  12699. if (!text.length || text.indexOf(startSymbol) === -1) {
  12700. if (mustHaveExpression) return;
  12701. var unescapedText = unescapeText(text);
  12702. if (contextAllowsConcatenation) {
  12703. unescapedText = $sce.getTrusted(trustedContext, unescapedText);
  12704. }
  12705. var constantInterp = valueFn(unescapedText);
  12706. constantInterp.exp = text;
  12707. constantInterp.expressions = [];
  12708. constantInterp.$$watchDelegate = constantWatchDelegate;
  12709. return constantInterp;
  12710. }
  12711. allOrNothing = !!allOrNothing;
  12712. var startIndex,
  12713. endIndex,
  12714. index = 0,
  12715. expressions = [],
  12716. parseFns,
  12717. textLength = text.length,
  12718. exp,
  12719. concat = [],
  12720. expressionPositions = [],
  12721. singleExpression;
  12722. while (index < textLength) {
  12723. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  12724. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  12725. if (index !== startIndex) {
  12726. concat.push(unescapeText(text.substring(index, startIndex)));
  12727. }
  12728. exp = text.substring(startIndex + startSymbolLength, endIndex);
  12729. expressions.push(exp);
  12730. index = endIndex + endSymbolLength;
  12731. expressionPositions.push(concat.length);
  12732. concat.push(''); // Placeholder that will get replaced with the evaluated expression.
  12733. } else {
  12734. // we did not find an interpolation, so we have to add the remainder to the separators array
  12735. if (index !== textLength) {
  12736. concat.push(unescapeText(text.substring(index)));
  12737. }
  12738. break;
  12739. }
  12740. }
  12741. singleExpression = concat.length === 1 && expressionPositions.length === 1;
  12742. // Intercept expression if we need to stringify concatenated inputs, which may be SCE trusted
  12743. // objects rather than simple strings
  12744. // (we don't modify the expression if the input consists of only a single trusted input)
  12745. var interceptor = contextAllowsConcatenation && singleExpression ? undefined : parseStringifyInterceptor;
  12746. parseFns = expressions.map(function(exp) { return $parse(exp, interceptor); });
  12747. // Concatenating expressions makes it hard to reason about whether some combination of
  12748. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  12749. // single expression be used for some $sce-managed secure contexts (RESOURCE_URLs mostly),
  12750. // we ensure that the value that's used is assigned or constructed by some JS code somewhere
  12751. // that is more testable or make it obvious that you bound the value to some user controlled
  12752. // value. This helps reduce the load when auditing for XSS issues.
  12753. // Note that URL and MEDIA_URL $sce contexts do not need this, since `$sce` can sanitize the values
  12754. // passed to it. In that case, `$sce.getTrusted` will be called on either the single expression
  12755. // or on the overall concatenated string (losing trusted types used in the mix, by design).
  12756. // Both these methods will sanitize plain strings. Also, HTML could be included, but since it's
  12757. // only used in srcdoc attributes, this would not be very useful.
  12758. if (!mustHaveExpression || expressions.length) {
  12759. var compute = function(values) {
  12760. for (var i = 0, ii = expressions.length; i < ii; i++) {
  12761. if (allOrNothing && isUndefined(values[i])) return;
  12762. concat[expressionPositions[i]] = values[i];
  12763. }
  12764. if (contextAllowsConcatenation) {
  12765. // If `singleExpression` then `concat[0]` might be a "trusted" value or `null`, rather than a string
  12766. return $sce.getTrusted(trustedContext, singleExpression ? concat[0] : concat.join(''));
  12767. } else if (trustedContext && concat.length > 1) {
  12768. // This context does not allow more than one part, e.g. expr + string or exp + exp.
  12769. $interpolateMinErr.throwNoconcat(text);
  12770. }
  12771. // In an unprivileged context or only one part: just concatenate and return.
  12772. return concat.join('');
  12773. };
  12774. return extend(function interpolationFn(context) {
  12775. var i = 0;
  12776. var ii = expressions.length;
  12777. var values = new Array(ii);
  12778. try {
  12779. for (; i < ii; i++) {
  12780. values[i] = parseFns[i](context);
  12781. }
  12782. return compute(values);
  12783. } catch (err) {
  12784. $exceptionHandler($interpolateMinErr.interr(text, err));
  12785. }
  12786. }, {
  12787. // all of these properties are undocumented for now
  12788. exp: text, //just for compatibility with regular watchers created via $watch
  12789. expressions: expressions,
  12790. $$watchDelegate: function(scope, listener) {
  12791. var lastValue;
  12792. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  12793. var currValue = compute(values);
  12794. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  12795. lastValue = currValue;
  12796. });
  12797. }
  12798. });
  12799. }
  12800. function parseStringifyInterceptor(value) {
  12801. try {
  12802. // In concatenable contexts, getTrusted comes at the end, to avoid sanitizing individual
  12803. // parts of a full URL. We don't care about losing the trustedness here.
  12804. // In non-concatenable contexts, where there is only one expression, this interceptor is
  12805. // not applied to the expression.
  12806. value = (trustedContext && !contextAllowsConcatenation) ?
  12807. $sce.getTrusted(trustedContext, value) :
  12808. $sce.valueOf(value);
  12809. return allOrNothing && !isDefined(value) ? value : stringify(value);
  12810. } catch (err) {
  12811. $exceptionHandler($interpolateMinErr.interr(text, err));
  12812. }
  12813. }
  12814. }
  12815. /**
  12816. * @ngdoc method
  12817. * @name $interpolate#startSymbol
  12818. * @description
  12819. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  12820. *
  12821. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  12822. * the symbol.
  12823. *
  12824. * @returns {string} start symbol.
  12825. */
  12826. $interpolate.startSymbol = function() {
  12827. return startSymbol;
  12828. };
  12829. /**
  12830. * @ngdoc method
  12831. * @name $interpolate#endSymbol
  12832. * @description
  12833. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12834. *
  12835. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  12836. * the symbol.
  12837. *
  12838. * @returns {string} end symbol.
  12839. */
  12840. $interpolate.endSymbol = function() {
  12841. return endSymbol;
  12842. };
  12843. return $interpolate;
  12844. }];
  12845. }
  12846. var $intervalMinErr = minErr('$interval');
  12847. /** @this */
  12848. function $IntervalProvider() {
  12849. this.$get = ['$$intervalFactory', '$window',
  12850. function($$intervalFactory, $window) {
  12851. var intervals = {};
  12852. var setIntervalFn = function(tick, delay, deferred) {
  12853. var id = $window.setInterval(tick, delay);
  12854. intervals[id] = deferred;
  12855. return id;
  12856. };
  12857. var clearIntervalFn = function(id) {
  12858. $window.clearInterval(id);
  12859. delete intervals[id];
  12860. };
  12861. /**
  12862. * @ngdoc service
  12863. * @name $interval
  12864. *
  12865. * @description
  12866. * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  12867. * milliseconds.
  12868. *
  12869. * The return value of registering an interval function is a promise. This promise will be
  12870. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  12871. * run indefinitely if `count` is not defined. The value of the notification will be the
  12872. * number of iterations that have run.
  12873. * To cancel an interval, call `$interval.cancel(promise)`.
  12874. *
  12875. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  12876. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  12877. * time.
  12878. *
  12879. * <div class="alert alert-warning">
  12880. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  12881. * with them. In particular they are not automatically destroyed when a controller's scope or a
  12882. * directive's element are destroyed.
  12883. * You should take this into consideration and make sure to always cancel the interval at the
  12884. * appropriate moment. See the example below for more details on how and when to do this.
  12885. * </div>
  12886. *
  12887. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  12888. * are passed (see below), the function is called with the current iteration count.
  12889. * @param {number} delay Number of milliseconds between each function call.
  12890. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  12891. * indefinitely.
  12892. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12893. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12894. * @param {...*=} Pass additional parameters to the executed function.
  12895. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  12896. *
  12897. * @example
  12898. * <example module="intervalExample" name="interval-service">
  12899. * <file name="index.html">
  12900. * <script>
  12901. * angular.module('intervalExample', [])
  12902. * .controller('ExampleController', ['$scope', '$interval',
  12903. * function($scope, $interval) {
  12904. * $scope.format = 'M/d/yy h:mm:ss a';
  12905. * $scope.blood_1 = 100;
  12906. * $scope.blood_2 = 120;
  12907. *
  12908. * var stop;
  12909. * $scope.fight = function() {
  12910. * // Don't start a new fight if we are already fighting
  12911. * if ( angular.isDefined(stop) ) return;
  12912. *
  12913. * stop = $interval(function() {
  12914. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12915. * $scope.blood_1 = $scope.blood_1 - 3;
  12916. * $scope.blood_2 = $scope.blood_2 - 4;
  12917. * } else {
  12918. * $scope.stopFight();
  12919. * }
  12920. * }, 100);
  12921. * };
  12922. *
  12923. * $scope.stopFight = function() {
  12924. * if (angular.isDefined(stop)) {
  12925. * $interval.cancel(stop);
  12926. * stop = undefined;
  12927. * }
  12928. * };
  12929. *
  12930. * $scope.resetFight = function() {
  12931. * $scope.blood_1 = 100;
  12932. * $scope.blood_2 = 120;
  12933. * };
  12934. *
  12935. * $scope.$on('$destroy', function() {
  12936. * // Make sure that the interval is destroyed too
  12937. * $scope.stopFight();
  12938. * });
  12939. * }])
  12940. * // Register the 'myCurrentTime' directive factory method.
  12941. * // We inject $interval and dateFilter service since the factory method is DI.
  12942. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  12943. * function($interval, dateFilter) {
  12944. * // return the directive link function. (compile function not needed)
  12945. * return function(scope, element, attrs) {
  12946. * var format, // date format
  12947. * stopTime; // so that we can cancel the time updates
  12948. *
  12949. * // used to update the UI
  12950. * function updateTime() {
  12951. * element.text(dateFilter(new Date(), format));
  12952. * }
  12953. *
  12954. * // watch the expression, and update the UI on change.
  12955. * scope.$watch(attrs.myCurrentTime, function(value) {
  12956. * format = value;
  12957. * updateTime();
  12958. * });
  12959. *
  12960. * stopTime = $interval(updateTime, 1000);
  12961. *
  12962. * // listen on DOM destroy (removal) event, and cancel the next UI update
  12963. * // to prevent updating time after the DOM element was removed.
  12964. * element.on('$destroy', function() {
  12965. * $interval.cancel(stopTime);
  12966. * });
  12967. * }
  12968. * }]);
  12969. * </script>
  12970. *
  12971. * <div>
  12972. * <div ng-controller="ExampleController">
  12973. * <label>Date format: <input ng-model="format"></label> <hr/>
  12974. * Current time is: <span my-current-time="format"></span>
  12975. * <hr/>
  12976. * Blood 1 : <font color='red'>{{blood_1}}</font>
  12977. * Blood 2 : <font color='red'>{{blood_2}}</font>
  12978. * <button type="button" data-ng-click="fight()">Fight</button>
  12979. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  12980. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  12981. * </div>
  12982. * </div>
  12983. *
  12984. * </file>
  12985. * </example>
  12986. */
  12987. var interval = $$intervalFactory(setIntervalFn, clearIntervalFn);
  12988. /**
  12989. * @ngdoc method
  12990. * @name $interval#cancel
  12991. *
  12992. * @description
  12993. * Cancels a task associated with the `promise`.
  12994. *
  12995. * @param {Promise=} promise returned by the `$interval` function.
  12996. * @returns {boolean} Returns `true` if the task was successfully canceled.
  12997. */
  12998. interval.cancel = function(promise) {
  12999. if (!promise) return false;
  13000. if (!promise.hasOwnProperty('$$intervalId')) {
  13001. throw $intervalMinErr('badprom',
  13002. '`$interval.cancel()` called with a promise that was not generated by `$interval()`.');
  13003. }
  13004. if (!intervals.hasOwnProperty(promise.$$intervalId)) return false;
  13005. var id = promise.$$intervalId;
  13006. var deferred = intervals[id];
  13007. // Interval cancels should not report an unhandled promise.
  13008. markQExceptionHandled(deferred.promise);
  13009. deferred.reject('canceled');
  13010. clearIntervalFn(id);
  13011. return true;
  13012. };
  13013. return interval;
  13014. }];
  13015. }
  13016. /** @this */
  13017. function $$IntervalFactoryProvider() {
  13018. this.$get = ['$browser', '$q', '$$q', '$rootScope',
  13019. function($browser, $q, $$q, $rootScope) {
  13020. return function intervalFactory(setIntervalFn, clearIntervalFn) {
  13021. return function intervalFn(fn, delay, count, invokeApply) {
  13022. var hasParams = arguments.length > 4,
  13023. args = hasParams ? sliceArgs(arguments, 4) : [],
  13024. iteration = 0,
  13025. skipApply = isDefined(invokeApply) && !invokeApply,
  13026. deferred = (skipApply ? $$q : $q).defer(),
  13027. promise = deferred.promise;
  13028. count = isDefined(count) ? count : 0;
  13029. function callback() {
  13030. if (!hasParams) {
  13031. fn(iteration);
  13032. } else {
  13033. fn.apply(null, args);
  13034. }
  13035. }
  13036. function tick() {
  13037. if (skipApply) {
  13038. $browser.defer(callback);
  13039. } else {
  13040. $rootScope.$evalAsync(callback);
  13041. }
  13042. deferred.notify(iteration++);
  13043. if (count > 0 && iteration >= count) {
  13044. deferred.resolve(iteration);
  13045. clearIntervalFn(promise.$$intervalId);
  13046. }
  13047. if (!skipApply) $rootScope.$apply();
  13048. }
  13049. promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply);
  13050. return promise;
  13051. };
  13052. };
  13053. }];
  13054. }
  13055. /**
  13056. * @ngdoc service
  13057. * @name $jsonpCallbacks
  13058. * @requires $window
  13059. * @description
  13060. * This service handles the lifecycle of callbacks to handle JSONP requests.
  13061. * Override this service if you wish to customise where the callbacks are stored and
  13062. * how they vary compared to the requested url.
  13063. */
  13064. var $jsonpCallbacksProvider = /** @this */ function() {
  13065. this.$get = function() {
  13066. var callbacks = angular.callbacks;
  13067. var callbackMap = {};
  13068. function createCallback(callbackId) {
  13069. var callback = function(data) {
  13070. callback.data = data;
  13071. callback.called = true;
  13072. };
  13073. callback.id = callbackId;
  13074. return callback;
  13075. }
  13076. return {
  13077. /**
  13078. * @ngdoc method
  13079. * @name $jsonpCallbacks#createCallback
  13080. * @param {string} url the url of the JSONP request
  13081. * @returns {string} the callback path to send to the server as part of the JSONP request
  13082. * @description
  13083. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  13084. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  13085. */
  13086. createCallback: function(url) {
  13087. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  13088. var callbackPath = 'angular.callbacks.' + callbackId;
  13089. var callback = createCallback(callbackId);
  13090. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  13091. return callbackPath;
  13092. },
  13093. /**
  13094. * @ngdoc method
  13095. * @name $jsonpCallbacks#wasCalled
  13096. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  13097. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  13098. * @description
  13099. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  13100. * callback that was passed in the request.
  13101. */
  13102. wasCalled: function(callbackPath) {
  13103. return callbackMap[callbackPath].called;
  13104. },
  13105. /**
  13106. * @ngdoc method
  13107. * @name $jsonpCallbacks#getResponse
  13108. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  13109. * @returns {*} the data received from the response via the registered callback
  13110. * @description
  13111. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  13112. * in the JSONP response.
  13113. */
  13114. getResponse: function(callbackPath) {
  13115. return callbackMap[callbackPath].data;
  13116. },
  13117. /**
  13118. * @ngdoc method
  13119. * @name $jsonpCallbacks#removeCallback
  13120. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  13121. * @description
  13122. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  13123. * completed or timed-out.
  13124. */
  13125. removeCallback: function(callbackPath) {
  13126. var callback = callbackMap[callbackPath];
  13127. delete callbacks[callback.id];
  13128. delete callbackMap[callbackPath];
  13129. }
  13130. };
  13131. };
  13132. };
  13133. /**
  13134. * @ngdoc service
  13135. * @name $locale
  13136. *
  13137. * @description
  13138. * $locale service provides localization rules for various AngularJS components. As of right now the
  13139. * only public api is:
  13140. *
  13141. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  13142. */
  13143. /* global stripHash: true */
  13144. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  13145. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  13146. var $locationMinErr = minErr('$location');
  13147. /**
  13148. * Encode path using encodeUriSegment, ignoring forward slashes
  13149. *
  13150. * @param {string} path Path to encode
  13151. * @returns {string}
  13152. */
  13153. function encodePath(path) {
  13154. var segments = path.split('/'),
  13155. i = segments.length;
  13156. while (i--) {
  13157. // decode forward slashes to prevent them from being double encoded
  13158. segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
  13159. }
  13160. return segments.join('/');
  13161. }
  13162. function decodePath(path, html5Mode) {
  13163. var segments = path.split('/'),
  13164. i = segments.length;
  13165. while (i--) {
  13166. segments[i] = decodeURIComponent(segments[i]);
  13167. if (html5Mode) {
  13168. // encode forward slashes to prevent them from being mistaken for path separators
  13169. segments[i] = segments[i].replace(/\//g, '%2F');
  13170. }
  13171. }
  13172. return segments.join('/');
  13173. }
  13174. function normalizePath(pathValue, searchValue, hashValue) {
  13175. var search = toKeyValue(searchValue),
  13176. hash = hashValue ? '#' + encodeUriSegment(hashValue) : '',
  13177. path = encodePath(pathValue);
  13178. return path + (search ? '?' + search : '') + hash;
  13179. }
  13180. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  13181. var parsedUrl = urlResolve(absoluteUrl);
  13182. locationObj.$$protocol = parsedUrl.protocol;
  13183. locationObj.$$host = parsedUrl.hostname;
  13184. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  13185. }
  13186. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  13187. function parseAppUrl(url, locationObj, html5Mode) {
  13188. if (DOUBLE_SLASH_REGEX.test(url)) {
  13189. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  13190. }
  13191. var prefixed = (url.charAt(0) !== '/');
  13192. if (prefixed) {
  13193. url = '/' + url;
  13194. }
  13195. var match = urlResolve(url);
  13196. var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
  13197. locationObj.$$path = decodePath(path, html5Mode);
  13198. locationObj.$$search = parseKeyValue(match.search);
  13199. locationObj.$$hash = decodeURIComponent(match.hash);
  13200. // make sure path starts with '/';
  13201. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  13202. locationObj.$$path = '/' + locationObj.$$path;
  13203. }
  13204. }
  13205. function startsWith(str, search) {
  13206. return str.slice(0, search.length) === search;
  13207. }
  13208. /**
  13209. *
  13210. * @param {string} base
  13211. * @param {string} url
  13212. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  13213. * the expected string.
  13214. */
  13215. function stripBaseUrl(base, url) {
  13216. if (startsWith(url, base)) {
  13217. return url.substr(base.length);
  13218. }
  13219. }
  13220. function stripHash(url) {
  13221. var index = url.indexOf('#');
  13222. return index === -1 ? url : url.substr(0, index);
  13223. }
  13224. function stripFile(url) {
  13225. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  13226. }
  13227. /* return the server only (scheme://host:port) */
  13228. function serverBase(url) {
  13229. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  13230. }
  13231. /**
  13232. * LocationHtml5Url represents a URL
  13233. * This object is exposed as $location service when HTML5 mode is enabled and supported
  13234. *
  13235. * @constructor
  13236. * @param {string} appBase application base URL
  13237. * @param {string} appBaseNoFile application base URL stripped of any filename
  13238. * @param {string} basePrefix URL path prefix
  13239. */
  13240. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  13241. this.$$html5 = true;
  13242. basePrefix = basePrefix || '';
  13243. parseAbsoluteUrl(appBase, this);
  13244. /**
  13245. * Parse given HTML5 (regular) URL string into properties
  13246. * @param {string} url HTML5 URL
  13247. * @private
  13248. */
  13249. this.$$parse = function(url) {
  13250. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  13251. if (!isString(pathUrl)) {
  13252. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  13253. appBaseNoFile);
  13254. }
  13255. parseAppUrl(pathUrl, this, true);
  13256. if (!this.$$path) {
  13257. this.$$path = '/';
  13258. }
  13259. this.$$compose();
  13260. };
  13261. this.$$normalizeUrl = function(url) {
  13262. return appBaseNoFile + url.substr(1); // first char is always '/'
  13263. };
  13264. this.$$parseLinkUrl = function(url, relHref) {
  13265. if (relHref && relHref[0] === '#') {
  13266. // special case for links to hash fragments:
  13267. // keep the old url and only replace the hash fragment
  13268. this.hash(relHref.slice(1));
  13269. return true;
  13270. }
  13271. var appUrl, prevAppUrl;
  13272. var rewrittenUrl;
  13273. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  13274. prevAppUrl = appUrl;
  13275. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  13276. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  13277. } else {
  13278. rewrittenUrl = appBase + prevAppUrl;
  13279. }
  13280. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  13281. rewrittenUrl = appBaseNoFile + appUrl;
  13282. } else if (appBaseNoFile === url + '/') {
  13283. rewrittenUrl = appBaseNoFile;
  13284. }
  13285. if (rewrittenUrl) {
  13286. this.$$parse(rewrittenUrl);
  13287. }
  13288. return !!rewrittenUrl;
  13289. };
  13290. }
  13291. /**
  13292. * LocationHashbangUrl represents URL
  13293. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  13294. * It also serves as the base class for html5 mode fallback on legacy browsers.
  13295. *
  13296. * @constructor
  13297. * @param {string} appBase application base URL
  13298. * @param {string} appBaseNoFile application base URL stripped of any filename
  13299. * @param {string} hashPrefix hashbang prefix
  13300. */
  13301. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  13302. parseAbsoluteUrl(appBase, this);
  13303. /**
  13304. * Parse given hashbang URL into properties
  13305. * @param {string} url Hashbang URL
  13306. * @private
  13307. */
  13308. this.$$parse = function(url) {
  13309. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  13310. var withoutHashUrl;
  13311. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  13312. // The rest of the URL starts with a hash so we have
  13313. // got either a hashbang path or a plain hash fragment
  13314. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  13315. if (isUndefined(withoutHashUrl)) {
  13316. // There was no hashbang prefix so we just have a hash fragment
  13317. withoutHashUrl = withoutBaseUrl;
  13318. }
  13319. } else {
  13320. // There was no hashbang path nor hash fragment:
  13321. // If we are in HTML5 mode we use what is left as the path;
  13322. // Otherwise we ignore what is left
  13323. if (this.$$html5) {
  13324. withoutHashUrl = withoutBaseUrl;
  13325. } else {
  13326. withoutHashUrl = '';
  13327. if (isUndefined(withoutBaseUrl)) {
  13328. appBase = url;
  13329. /** @type {?} */ (this).replace();
  13330. }
  13331. }
  13332. }
  13333. parseAppUrl(withoutHashUrl, this, false);
  13334. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  13335. this.$$compose();
  13336. /*
  13337. * In Windows, on an anchor node on documents loaded from
  13338. * the filesystem, the browser will return a pathname
  13339. * prefixed with the drive name ('/C:/path') when a
  13340. * pathname without a drive is set:
  13341. * * a.setAttribute('href', '/foo')
  13342. * * a.pathname === '/C:/foo' //true
  13343. *
  13344. * Inside of AngularJS, we're always using pathnames that
  13345. * do not include drive names for routing.
  13346. */
  13347. function removeWindowsDriveName(path, url, base) {
  13348. /*
  13349. Matches paths for file protocol on windows,
  13350. such as /C:/foo/bar, and captures only /foo/bar.
  13351. */
  13352. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  13353. var firstPathSegmentMatch;
  13354. //Get the relative path from the input URL.
  13355. if (startsWith(url, base)) {
  13356. url = url.replace(base, '');
  13357. }
  13358. // The input URL intentionally contains a first path segment that ends with a colon.
  13359. if (windowsFilePathExp.exec(url)) {
  13360. return path;
  13361. }
  13362. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  13363. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  13364. }
  13365. };
  13366. this.$$normalizeUrl = function(url) {
  13367. return appBase + (url ? hashPrefix + url : '');
  13368. };
  13369. this.$$parseLinkUrl = function(url, relHref) {
  13370. if (stripHash(appBase) === stripHash(url)) {
  13371. this.$$parse(url);
  13372. return true;
  13373. }
  13374. return false;
  13375. };
  13376. }
  13377. /**
  13378. * LocationHashbangUrl represents URL
  13379. * This object is exposed as $location service when html5 history api is enabled but the browser
  13380. * does not support it.
  13381. *
  13382. * @constructor
  13383. * @param {string} appBase application base URL
  13384. * @param {string} appBaseNoFile application base URL stripped of any filename
  13385. * @param {string} hashPrefix hashbang prefix
  13386. */
  13387. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  13388. this.$$html5 = true;
  13389. LocationHashbangUrl.apply(this, arguments);
  13390. this.$$parseLinkUrl = function(url, relHref) {
  13391. if (relHref && relHref[0] === '#') {
  13392. // special case for links to hash fragments:
  13393. // keep the old url and only replace the hash fragment
  13394. this.hash(relHref.slice(1));
  13395. return true;
  13396. }
  13397. var rewrittenUrl;
  13398. var appUrl;
  13399. if (appBase === stripHash(url)) {
  13400. rewrittenUrl = url;
  13401. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  13402. rewrittenUrl = appBase + hashPrefix + appUrl;
  13403. } else if (appBaseNoFile === url + '/') {
  13404. rewrittenUrl = appBaseNoFile;
  13405. }
  13406. if (rewrittenUrl) {
  13407. this.$$parse(rewrittenUrl);
  13408. }
  13409. return !!rewrittenUrl;
  13410. };
  13411. this.$$normalizeUrl = function(url) {
  13412. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  13413. return appBase + hashPrefix + url;
  13414. };
  13415. }
  13416. var locationPrototype = {
  13417. /**
  13418. * Ensure absolute URL is initialized.
  13419. * @private
  13420. */
  13421. $$absUrl:'',
  13422. /**
  13423. * Are we in html5 mode?
  13424. * @private
  13425. */
  13426. $$html5: false,
  13427. /**
  13428. * Has any change been replacing?
  13429. * @private
  13430. */
  13431. $$replace: false,
  13432. /**
  13433. * Compose url and update `url` and `absUrl` property
  13434. * @private
  13435. */
  13436. $$compose: function() {
  13437. this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash);
  13438. this.$$absUrl = this.$$normalizeUrl(this.$$url);
  13439. this.$$urlUpdatedByLocation = true;
  13440. },
  13441. /**
  13442. * @ngdoc method
  13443. * @name $location#absUrl
  13444. *
  13445. * @description
  13446. * This method is getter only.
  13447. *
  13448. * Return full URL representation with all segments encoded according to rules specified in
  13449. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  13450. *
  13451. *
  13452. * ```js
  13453. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13454. * var absUrl = $location.absUrl();
  13455. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  13456. * ```
  13457. *
  13458. * @return {string} full URL
  13459. */
  13460. absUrl: locationGetter('$$absUrl'),
  13461. /**
  13462. * @ngdoc method
  13463. * @name $location#url
  13464. *
  13465. * @description
  13466. * This method is getter / setter.
  13467. *
  13468. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  13469. *
  13470. * Change path, search and hash, when called with parameter and return `$location`.
  13471. *
  13472. *
  13473. * ```js
  13474. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13475. * var url = $location.url();
  13476. * // => "/some/path?foo=bar&baz=xoxo"
  13477. * ```
  13478. *
  13479. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  13480. * @return {string} url
  13481. */
  13482. url: function(url) {
  13483. if (isUndefined(url)) {
  13484. return this.$$url;
  13485. }
  13486. var match = PATH_MATCH.exec(url);
  13487. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  13488. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  13489. this.hash(match[5] || '');
  13490. return this;
  13491. },
  13492. /**
  13493. * @ngdoc method
  13494. * @name $location#protocol
  13495. *
  13496. * @description
  13497. * This method is getter only.
  13498. *
  13499. * Return protocol of current URL.
  13500. *
  13501. *
  13502. * ```js
  13503. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13504. * var protocol = $location.protocol();
  13505. * // => "http"
  13506. * ```
  13507. *
  13508. * @return {string} protocol of current URL
  13509. */
  13510. protocol: locationGetter('$$protocol'),
  13511. /**
  13512. * @ngdoc method
  13513. * @name $location#host
  13514. *
  13515. * @description
  13516. * This method is getter only.
  13517. *
  13518. * Return host of current URL.
  13519. *
  13520. * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  13521. *
  13522. *
  13523. * ```js
  13524. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13525. * var host = $location.host();
  13526. * // => "example.com"
  13527. *
  13528. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  13529. * host = $location.host();
  13530. * // => "example.com"
  13531. * host = location.host;
  13532. * // => "example.com:8080"
  13533. * ```
  13534. *
  13535. * @return {string} host of current URL.
  13536. */
  13537. host: locationGetter('$$host'),
  13538. /**
  13539. * @ngdoc method
  13540. * @name $location#port
  13541. *
  13542. * @description
  13543. * This method is getter only.
  13544. *
  13545. * Return port of current URL.
  13546. *
  13547. *
  13548. * ```js
  13549. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13550. * var port = $location.port();
  13551. * // => 80
  13552. * ```
  13553. *
  13554. * @return {Number} port
  13555. */
  13556. port: locationGetter('$$port'),
  13557. /**
  13558. * @ngdoc method
  13559. * @name $location#path
  13560. *
  13561. * @description
  13562. * This method is getter / setter.
  13563. *
  13564. * Return path of current URL when called without any parameter.
  13565. *
  13566. * Change path when called with parameter and return `$location`.
  13567. *
  13568. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  13569. * if it is missing.
  13570. *
  13571. *
  13572. * ```js
  13573. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13574. * var path = $location.path();
  13575. * // => "/some/path"
  13576. * ```
  13577. *
  13578. * @param {(string|number)=} path New path
  13579. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  13580. */
  13581. path: locationGetterSetter('$$path', function(path) {
  13582. path = path !== null ? path.toString() : '';
  13583. return path.charAt(0) === '/' ? path : '/' + path;
  13584. }),
  13585. /**
  13586. * @ngdoc method
  13587. * @name $location#search
  13588. *
  13589. * @description
  13590. * This method is getter / setter.
  13591. *
  13592. * Return search part (as object) of current URL when called without any parameter.
  13593. *
  13594. * Change search part when called with parameter and return `$location`.
  13595. *
  13596. *
  13597. * ```js
  13598. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13599. * var searchObject = $location.search();
  13600. * // => {foo: 'bar', baz: 'xoxo'}
  13601. *
  13602. * // set foo to 'yipee'
  13603. * $location.search('foo', 'yipee');
  13604. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  13605. * ```
  13606. *
  13607. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  13608. * hash object.
  13609. *
  13610. * When called with a single argument the method acts as a setter, setting the `search` component
  13611. * of `$location` to the specified value.
  13612. *
  13613. * If the argument is a hash object containing an array of values, these values will be encoded
  13614. * as duplicate search parameters in the URL.
  13615. *
  13616. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  13617. * will override only a single search property.
  13618. *
  13619. * If `paramValue` is an array, it will override the property of the `search` component of
  13620. * `$location` specified via the first argument.
  13621. *
  13622. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  13623. *
  13624. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  13625. * value nor trailing equal sign.
  13626. *
  13627. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  13628. * one or more arguments returns `$location` object itself.
  13629. */
  13630. search: function(search, paramValue) {
  13631. switch (arguments.length) {
  13632. case 0:
  13633. return this.$$search;
  13634. case 1:
  13635. if (isString(search) || isNumber(search)) {
  13636. search = search.toString();
  13637. this.$$search = parseKeyValue(search);
  13638. } else if (isObject(search)) {
  13639. search = copy(search, {});
  13640. // remove object undefined or null properties
  13641. forEach(search, function(value, key) {
  13642. if (value == null) delete search[key];
  13643. });
  13644. this.$$search = search;
  13645. } else {
  13646. throw $locationMinErr('isrcharg',
  13647. 'The first argument of the `$location#search()` call must be a string or an object.');
  13648. }
  13649. break;
  13650. default:
  13651. if (isUndefined(paramValue) || paramValue === null) {
  13652. delete this.$$search[search];
  13653. } else {
  13654. this.$$search[search] = paramValue;
  13655. }
  13656. }
  13657. this.$$compose();
  13658. return this;
  13659. },
  13660. /**
  13661. * @ngdoc method
  13662. * @name $location#hash
  13663. *
  13664. * @description
  13665. * This method is getter / setter.
  13666. *
  13667. * Returns the hash fragment when called without any parameters.
  13668. *
  13669. * Changes the hash fragment when called with a parameter and returns `$location`.
  13670. *
  13671. *
  13672. * ```js
  13673. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  13674. * var hash = $location.hash();
  13675. * // => "hashValue"
  13676. * ```
  13677. *
  13678. * @param {(string|number)=} hash New hash fragment
  13679. * @return {string} hash
  13680. */
  13681. hash: locationGetterSetter('$$hash', function(hash) {
  13682. return hash !== null ? hash.toString() : '';
  13683. }),
  13684. /**
  13685. * @ngdoc method
  13686. * @name $location#replace
  13687. *
  13688. * @description
  13689. * If called, all changes to $location during the current `$digest` will replace the current history
  13690. * record, instead of adding a new one.
  13691. */
  13692. replace: function() {
  13693. this.$$replace = true;
  13694. return this;
  13695. }
  13696. };
  13697. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  13698. Location.prototype = Object.create(locationPrototype);
  13699. /**
  13700. * @ngdoc method
  13701. * @name $location#state
  13702. *
  13703. * @description
  13704. * This method is getter / setter.
  13705. *
  13706. * Return the history state object when called without any parameter.
  13707. *
  13708. * Change the history state object when called with one parameter and return `$location`.
  13709. * The state object is later passed to `pushState` or `replaceState`.
  13710. *
  13711. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  13712. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  13713. * older browsers (like IE9 or Android < 4.0), don't use this method.
  13714. *
  13715. * @param {object=} state State object for pushState or replaceState
  13716. * @return {object} state
  13717. */
  13718. Location.prototype.state = function(state) {
  13719. if (!arguments.length) {
  13720. return this.$$state;
  13721. }
  13722. if (Location !== LocationHtml5Url || !this.$$html5) {
  13723. throw $locationMinErr('nostate', 'History API state support is available only ' +
  13724. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  13725. }
  13726. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  13727. // but we're changing the $$state reference to $browser.state() during the $digest
  13728. // so the modification window is narrow.
  13729. this.$$state = isUndefined(state) ? null : state;
  13730. this.$$urlUpdatedByLocation = true;
  13731. return this;
  13732. };
  13733. });
  13734. function locationGetter(property) {
  13735. return /** @this */ function() {
  13736. return this[property];
  13737. };
  13738. }
  13739. function locationGetterSetter(property, preprocess) {
  13740. return /** @this */ function(value) {
  13741. if (isUndefined(value)) {
  13742. return this[property];
  13743. }
  13744. this[property] = preprocess(value);
  13745. this.$$compose();
  13746. return this;
  13747. };
  13748. }
  13749. /**
  13750. * @ngdoc service
  13751. * @name $location
  13752. *
  13753. * @requires $rootElement
  13754. *
  13755. * @description
  13756. * The $location service parses the URL in the browser address bar (based on the
  13757. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  13758. * available to your application. Changes to the URL in the address bar are reflected into
  13759. * $location service and changes to $location are reflected into the browser address bar.
  13760. *
  13761. * **The $location service:**
  13762. *
  13763. * - Exposes the current URL in the browser address bar, so you can
  13764. * - Watch and observe the URL.
  13765. * - Change the URL.
  13766. * - Synchronizes the URL with the browser when the user
  13767. * - Changes the address bar.
  13768. * - Clicks the back or forward button (or clicks a History link).
  13769. * - Clicks on a link.
  13770. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  13771. *
  13772. * For more information see {@link guide/$location Developer Guide: Using $location}
  13773. */
  13774. /**
  13775. * @ngdoc provider
  13776. * @name $locationProvider
  13777. * @this
  13778. *
  13779. * @description
  13780. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  13781. */
  13782. function $LocationProvider() {
  13783. var hashPrefix = '!',
  13784. html5Mode = {
  13785. enabled: false,
  13786. requireBase: true,
  13787. rewriteLinks: true
  13788. };
  13789. /**
  13790. * @ngdoc method
  13791. * @name $locationProvider#hashPrefix
  13792. * @description
  13793. * The default value for the prefix is `'!'`.
  13794. * @param {string=} prefix Prefix for hash part (containing path and search)
  13795. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13796. */
  13797. this.hashPrefix = function(prefix) {
  13798. if (isDefined(prefix)) {
  13799. hashPrefix = prefix;
  13800. return this;
  13801. } else {
  13802. return hashPrefix;
  13803. }
  13804. };
  13805. /**
  13806. * @ngdoc method
  13807. * @name $locationProvider#html5Mode
  13808. * @description
  13809. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  13810. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  13811. * properties:
  13812. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  13813. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  13814. * support `pushState`.
  13815. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  13816. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  13817. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  13818. * See the {@link guide/$location $location guide for more information}
  13819. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  13820. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  13821. * only happen on links with an attribute that matches the given string. For example, if set
  13822. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  13823. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  13824. * here, so `'internalLink'` will **not** match `'internal-link'`.
  13825. *
  13826. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  13827. */
  13828. this.html5Mode = function(mode) {
  13829. if (isBoolean(mode)) {
  13830. html5Mode.enabled = mode;
  13831. return this;
  13832. } else if (isObject(mode)) {
  13833. if (isBoolean(mode.enabled)) {
  13834. html5Mode.enabled = mode.enabled;
  13835. }
  13836. if (isBoolean(mode.requireBase)) {
  13837. html5Mode.requireBase = mode.requireBase;
  13838. }
  13839. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  13840. html5Mode.rewriteLinks = mode.rewriteLinks;
  13841. }
  13842. return this;
  13843. } else {
  13844. return html5Mode;
  13845. }
  13846. };
  13847. /**
  13848. * @ngdoc event
  13849. * @name $location#$locationChangeStart
  13850. * @eventType broadcast on root scope
  13851. * @description
  13852. * Broadcasted before a URL will change.
  13853. *
  13854. * This change can be prevented by calling
  13855. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  13856. * details about event object. Upon successful change
  13857. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  13858. *
  13859. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13860. * the browser supports the HTML5 History API.
  13861. *
  13862. * @param {Object} angularEvent Synthetic event object.
  13863. * @param {string} newUrl New URL
  13864. * @param {string=} oldUrl URL that was before it was changed.
  13865. * @param {string=} newState New history state object
  13866. * @param {string=} oldState History state object that was before it was changed.
  13867. */
  13868. /**
  13869. * @ngdoc event
  13870. * @name $location#$locationChangeSuccess
  13871. * @eventType broadcast on root scope
  13872. * @description
  13873. * Broadcasted after a URL was changed.
  13874. *
  13875. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13876. * the browser supports the HTML5 History API.
  13877. *
  13878. * @param {Object} angularEvent Synthetic event object.
  13879. * @param {string} newUrl New URL
  13880. * @param {string=} oldUrl URL that was before it was changed.
  13881. * @param {string=} newState New history state object
  13882. * @param {string=} oldState History state object that was before it was changed.
  13883. */
  13884. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  13885. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  13886. var $location,
  13887. LocationMode,
  13888. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  13889. initialUrl = $browser.url(),
  13890. appBase;
  13891. if (html5Mode.enabled) {
  13892. if (!baseHref && html5Mode.requireBase) {
  13893. throw $locationMinErr('nobase',
  13894. '$location in HTML5 mode requires a <base> tag to be present!');
  13895. }
  13896. appBase = serverBase(initialUrl) + (baseHref || '/');
  13897. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  13898. } else {
  13899. appBase = stripHash(initialUrl);
  13900. LocationMode = LocationHashbangUrl;
  13901. }
  13902. var appBaseNoFile = stripFile(appBase);
  13903. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  13904. $location.$$parseLinkUrl(initialUrl, initialUrl);
  13905. $location.$$state = $browser.state();
  13906. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  13907. // Determine if two URLs are equal despite potentially having different encoding/normalizing
  13908. // such as $location.absUrl() vs $browser.url()
  13909. // See https://github.com/angular/angular.js/issues/16592
  13910. function urlsEqual(a, b) {
  13911. return a === b || urlResolve(a).href === urlResolve(b).href;
  13912. }
  13913. function setBrowserUrlWithFallback(url, replace, state) {
  13914. var oldUrl = $location.url();
  13915. var oldState = $location.$$state;
  13916. try {
  13917. $browser.url(url, replace, state);
  13918. // Make sure $location.state() returns referentially identical (not just deeply equal)
  13919. // state object; this makes possible quick checking if the state changed in the digest
  13920. // loop. Checking deep equality would be too expensive.
  13921. $location.$$state = $browser.state();
  13922. } catch (e) {
  13923. // Restore old values if pushState fails
  13924. $location.url(oldUrl);
  13925. $location.$$state = oldState;
  13926. throw e;
  13927. }
  13928. }
  13929. $rootElement.on('click', function(event) {
  13930. var rewriteLinks = html5Mode.rewriteLinks;
  13931. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  13932. // currently we open nice url link and redirect then
  13933. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  13934. var elm = jqLite(event.target);
  13935. // traverse the DOM up to find first A tag
  13936. while (nodeName_(elm[0]) !== 'a') {
  13937. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  13938. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  13939. }
  13940. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  13941. var absHref = elm.prop('href');
  13942. // get the actual href attribute - see
  13943. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  13944. var relHref = elm.attr('href') || elm.attr('xlink:href');
  13945. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  13946. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  13947. // an animation.
  13948. absHref = urlResolve(absHref.animVal).href;
  13949. }
  13950. // Ignore when url is started with javascript: or mailto:
  13951. if (IGNORE_URI_REGEXP.test(absHref)) return;
  13952. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  13953. if ($location.$$parseLinkUrl(absHref, relHref)) {
  13954. // We do a preventDefault for all urls that are part of the AngularJS application,
  13955. // in html5mode and also without, so that we are able to abort navigation without
  13956. // getting double entries in the location history.
  13957. event.preventDefault();
  13958. // update location manually
  13959. if ($location.absUrl() !== $browser.url()) {
  13960. $rootScope.$apply();
  13961. }
  13962. }
  13963. }
  13964. });
  13965. // rewrite hashbang url <> html5 url
  13966. if ($location.absUrl() !== initialUrl) {
  13967. $browser.url($location.absUrl(), true);
  13968. }
  13969. var initializing = true;
  13970. // update $location when $browser url changes
  13971. $browser.onUrlChange(function(newUrl, newState) {
  13972. if (!startsWith(newUrl, appBaseNoFile)) {
  13973. // If we are navigating outside of the app then force a reload
  13974. $window.location.href = newUrl;
  13975. return;
  13976. }
  13977. $rootScope.$evalAsync(function() {
  13978. var oldUrl = $location.absUrl();
  13979. var oldState = $location.$$state;
  13980. var defaultPrevented;
  13981. $location.$$parse(newUrl);
  13982. $location.$$state = newState;
  13983. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13984. newState, oldState).defaultPrevented;
  13985. // if the location was changed by a `$locationChangeStart` handler then stop
  13986. // processing this location change
  13987. if ($location.absUrl() !== newUrl) return;
  13988. if (defaultPrevented) {
  13989. $location.$$parse(oldUrl);
  13990. $location.$$state = oldState;
  13991. setBrowserUrlWithFallback(oldUrl, false, oldState);
  13992. } else {
  13993. initializing = false;
  13994. afterLocationChange(oldUrl, oldState);
  13995. }
  13996. });
  13997. if (!$rootScope.$$phase) $rootScope.$digest();
  13998. });
  13999. // update browser
  14000. $rootScope.$watch(function $locationWatch() {
  14001. if (initializing || $location.$$urlUpdatedByLocation) {
  14002. $location.$$urlUpdatedByLocation = false;
  14003. var oldUrl = $browser.url();
  14004. var newUrl = $location.absUrl();
  14005. var oldState = $browser.state();
  14006. var currentReplace = $location.$$replace;
  14007. var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) ||
  14008. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  14009. if (initializing || urlOrStateChanged) {
  14010. initializing = false;
  14011. $rootScope.$evalAsync(function() {
  14012. var newUrl = $location.absUrl();
  14013. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  14014. $location.$$state, oldState).defaultPrevented;
  14015. // if the location was changed by a `$locationChangeStart` handler then stop
  14016. // processing this location change
  14017. if ($location.absUrl() !== newUrl) return;
  14018. if (defaultPrevented) {
  14019. $location.$$parse(oldUrl);
  14020. $location.$$state = oldState;
  14021. } else {
  14022. if (urlOrStateChanged) {
  14023. setBrowserUrlWithFallback(newUrl, currentReplace,
  14024. oldState === $location.$$state ? null : $location.$$state);
  14025. }
  14026. afterLocationChange(oldUrl, oldState);
  14027. }
  14028. });
  14029. }
  14030. }
  14031. $location.$$replace = false;
  14032. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  14033. // there is a change
  14034. });
  14035. return $location;
  14036. function afterLocationChange(oldUrl, oldState) {
  14037. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  14038. $location.$$state, oldState);
  14039. }
  14040. }];
  14041. }
  14042. /**
  14043. * @ngdoc service
  14044. * @name $log
  14045. * @requires $window
  14046. *
  14047. * @description
  14048. * Simple service for logging. Default implementation safely writes the message
  14049. * into the browser's console (if present).
  14050. *
  14051. * The main purpose of this service is to simplify debugging and troubleshooting.
  14052. *
  14053. * To reveal the location of the calls to `$log` in the JavaScript console,
  14054. * you can "blackbox" the AngularJS source in your browser:
  14055. *
  14056. * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).
  14057. * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).
  14058. *
  14059. * Note: Not all browsers support blackboxing.
  14060. *
  14061. * The default is to log `debug` messages. You can use
  14062. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  14063. *
  14064. * @example
  14065. <example module="logExample" name="log-service">
  14066. <file name="script.js">
  14067. angular.module('logExample', [])
  14068. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  14069. $scope.$log = $log;
  14070. $scope.message = 'Hello World!';
  14071. }]);
  14072. </file>
  14073. <file name="index.html">
  14074. <div ng-controller="LogController">
  14075. <p>Reload this page with open console, enter text and hit the log button...</p>
  14076. <label>Message:
  14077. <input type="text" ng-model="message" /></label>
  14078. <button ng-click="$log.log(message)">log</button>
  14079. <button ng-click="$log.warn(message)">warn</button>
  14080. <button ng-click="$log.info(message)">info</button>
  14081. <button ng-click="$log.error(message)">error</button>
  14082. <button ng-click="$log.debug(message)">debug</button>
  14083. </div>
  14084. </file>
  14085. </example>
  14086. */
  14087. /**
  14088. * @ngdoc provider
  14089. * @name $logProvider
  14090. * @this
  14091. *
  14092. * @description
  14093. * Use the `$logProvider` to configure how the application logs messages
  14094. */
  14095. function $LogProvider() {
  14096. var debug = true,
  14097. self = this;
  14098. /**
  14099. * @ngdoc method
  14100. * @name $logProvider#debugEnabled
  14101. * @description
  14102. * @param {boolean=} flag enable or disable debug level messages
  14103. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  14104. */
  14105. this.debugEnabled = function(flag) {
  14106. if (isDefined(flag)) {
  14107. debug = flag;
  14108. return this;
  14109. } else {
  14110. return debug;
  14111. }
  14112. };
  14113. this.$get = ['$window', function($window) {
  14114. // Support: IE 9-11, Edge 12-14+
  14115. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  14116. // to see the stack trace. There is no way to feature-detect it so there's a chance
  14117. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  14118. // break apps. Other browsers display errors in a sensible way and some of them map stack
  14119. // traces along source maps if available so it makes sense to let browsers display it
  14120. // as they want.
  14121. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  14122. return {
  14123. /**
  14124. * @ngdoc method
  14125. * @name $log#log
  14126. *
  14127. * @description
  14128. * Write a log message
  14129. */
  14130. log: consoleLog('log'),
  14131. /**
  14132. * @ngdoc method
  14133. * @name $log#info
  14134. *
  14135. * @description
  14136. * Write an information message
  14137. */
  14138. info: consoleLog('info'),
  14139. /**
  14140. * @ngdoc method
  14141. * @name $log#warn
  14142. *
  14143. * @description
  14144. * Write a warning message
  14145. */
  14146. warn: consoleLog('warn'),
  14147. /**
  14148. * @ngdoc method
  14149. * @name $log#error
  14150. *
  14151. * @description
  14152. * Write an error message
  14153. */
  14154. error: consoleLog('error'),
  14155. /**
  14156. * @ngdoc method
  14157. * @name $log#debug
  14158. *
  14159. * @description
  14160. * Write a debug message
  14161. */
  14162. debug: (function() {
  14163. var fn = consoleLog('debug');
  14164. return function() {
  14165. if (debug) {
  14166. fn.apply(self, arguments);
  14167. }
  14168. };
  14169. })()
  14170. };
  14171. function formatError(arg) {
  14172. if (isError(arg)) {
  14173. if (arg.stack && formatStackTrace) {
  14174. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  14175. ? 'Error: ' + arg.message + '\n' + arg.stack
  14176. : arg.stack;
  14177. } else if (arg.sourceURL) {
  14178. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  14179. }
  14180. }
  14181. return arg;
  14182. }
  14183. function consoleLog(type) {
  14184. var console = $window.console || {},
  14185. logFn = console[type] || console.log || noop;
  14186. return function() {
  14187. var args = [];
  14188. forEach(arguments, function(arg) {
  14189. args.push(formatError(arg));
  14190. });
  14191. // Support: IE 9 only
  14192. // console methods don't inherit from Function.prototype in IE 9 so we can't
  14193. // call `logFn.apply(console, args)` directly.
  14194. return Function.prototype.apply.call(logFn, console, args);
  14195. };
  14196. }
  14197. }];
  14198. }
  14199. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14200. * Any commits to this file should be reviewed with security in mind. *
  14201. * Changes to this file can potentially create security vulnerabilities. *
  14202. * An approval from 2 Core members with history of modifying *
  14203. * this file is required. *
  14204. * *
  14205. * Does the change somehow allow for arbitrary javascript to be executed? *
  14206. * Or allows for someone to change the prototype of built-in objects? *
  14207. * Or gives undesired access to variables likes document or window? *
  14208. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14209. var $parseMinErr = minErr('$parse');
  14210. var objectValueOf = {}.constructor.prototype.valueOf;
  14211. // Sandboxing AngularJS Expressions
  14212. // ------------------------------
  14213. // AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  14214. // various means such as obtaining a reference to native JS functions like the Function constructor.
  14215. //
  14216. // As an example, consider the following AngularJS expression:
  14217. //
  14218. // {}.toString.constructor('alert("evil JS code")')
  14219. //
  14220. // It is important to realize that if you create an expression from a string that contains user provided
  14221. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  14222. //
  14223. // See https://docs.angularjs.org/guide/security
  14224. function getStringValue(name) {
  14225. // Property names must be strings. This means that non-string objects cannot be used
  14226. // as keys in an object. Any non-string object, including a number, is typecasted
  14227. // into a string via the toString method.
  14228. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  14229. //
  14230. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  14231. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  14232. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  14233. //
  14234. // TypeError: Cannot convert object to primitive value
  14235. //
  14236. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  14237. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  14238. // such a 'broken' object as a key.
  14239. return name + '';
  14240. }
  14241. var OPERATORS = createMap();
  14242. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  14243. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  14244. /////////////////////////////////////////
  14245. /**
  14246. * @constructor
  14247. */
  14248. var Lexer = function Lexer(options) {
  14249. this.options = options;
  14250. };
  14251. Lexer.prototype = {
  14252. constructor: Lexer,
  14253. lex: function(text) {
  14254. this.text = text;
  14255. this.index = 0;
  14256. this.tokens = [];
  14257. while (this.index < this.text.length) {
  14258. var ch = this.text.charAt(this.index);
  14259. if (ch === '"' || ch === '\'') {
  14260. this.readString(ch);
  14261. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  14262. this.readNumber();
  14263. } else if (this.isIdentifierStart(this.peekMultichar())) {
  14264. this.readIdent();
  14265. } else if (this.is(ch, '(){}[].,;:?')) {
  14266. this.tokens.push({index: this.index, text: ch});
  14267. this.index++;
  14268. } else if (this.isWhitespace(ch)) {
  14269. this.index++;
  14270. } else {
  14271. var ch2 = ch + this.peek();
  14272. var ch3 = ch2 + this.peek(2);
  14273. var op1 = OPERATORS[ch];
  14274. var op2 = OPERATORS[ch2];
  14275. var op3 = OPERATORS[ch3];
  14276. if (op1 || op2 || op3) {
  14277. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  14278. this.tokens.push({index: this.index, text: token, operator: true});
  14279. this.index += token.length;
  14280. } else {
  14281. this.throwError('Unexpected next character ', this.index, this.index + 1);
  14282. }
  14283. }
  14284. }
  14285. return this.tokens;
  14286. },
  14287. is: function(ch, chars) {
  14288. return chars.indexOf(ch) !== -1;
  14289. },
  14290. peek: function(i) {
  14291. var num = i || 1;
  14292. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  14293. },
  14294. isNumber: function(ch) {
  14295. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  14296. },
  14297. isWhitespace: function(ch) {
  14298. // IE treats non-breaking space as \u00A0
  14299. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  14300. ch === '\n' || ch === '\v' || ch === '\u00A0');
  14301. },
  14302. isIdentifierStart: function(ch) {
  14303. return this.options.isIdentifierStart ?
  14304. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  14305. this.isValidIdentifierStart(ch);
  14306. },
  14307. isValidIdentifierStart: function(ch) {
  14308. return ('a' <= ch && ch <= 'z' ||
  14309. 'A' <= ch && ch <= 'Z' ||
  14310. '_' === ch || ch === '$');
  14311. },
  14312. isIdentifierContinue: function(ch) {
  14313. return this.options.isIdentifierContinue ?
  14314. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  14315. this.isValidIdentifierContinue(ch);
  14316. },
  14317. isValidIdentifierContinue: function(ch, cp) {
  14318. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  14319. },
  14320. codePointAt: function(ch) {
  14321. if (ch.length === 1) return ch.charCodeAt(0);
  14322. // eslint-disable-next-line no-bitwise
  14323. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  14324. },
  14325. peekMultichar: function() {
  14326. var ch = this.text.charAt(this.index);
  14327. var peek = this.peek();
  14328. if (!peek) {
  14329. return ch;
  14330. }
  14331. var cp1 = ch.charCodeAt(0);
  14332. var cp2 = peek.charCodeAt(0);
  14333. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  14334. return ch + peek;
  14335. }
  14336. return ch;
  14337. },
  14338. isExpOperator: function(ch) {
  14339. return (ch === '-' || ch === '+' || this.isNumber(ch));
  14340. },
  14341. throwError: function(error, start, end) {
  14342. end = end || this.index;
  14343. var colStr = (isDefined(start)
  14344. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  14345. : ' ' + end);
  14346. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  14347. error, colStr, this.text);
  14348. },
  14349. readNumber: function() {
  14350. var number = '';
  14351. var start = this.index;
  14352. while (this.index < this.text.length) {
  14353. var ch = lowercase(this.text.charAt(this.index));
  14354. if (ch === '.' || this.isNumber(ch)) {
  14355. number += ch;
  14356. } else {
  14357. var peekCh = this.peek();
  14358. if (ch === 'e' && this.isExpOperator(peekCh)) {
  14359. number += ch;
  14360. } else if (this.isExpOperator(ch) &&
  14361. peekCh && this.isNumber(peekCh) &&
  14362. number.charAt(number.length - 1) === 'e') {
  14363. number += ch;
  14364. } else if (this.isExpOperator(ch) &&
  14365. (!peekCh || !this.isNumber(peekCh)) &&
  14366. number.charAt(number.length - 1) === 'e') {
  14367. this.throwError('Invalid exponent');
  14368. } else {
  14369. break;
  14370. }
  14371. }
  14372. this.index++;
  14373. }
  14374. this.tokens.push({
  14375. index: start,
  14376. text: number,
  14377. constant: true,
  14378. value: Number(number)
  14379. });
  14380. },
  14381. readIdent: function() {
  14382. var start = this.index;
  14383. this.index += this.peekMultichar().length;
  14384. while (this.index < this.text.length) {
  14385. var ch = this.peekMultichar();
  14386. if (!this.isIdentifierContinue(ch)) {
  14387. break;
  14388. }
  14389. this.index += ch.length;
  14390. }
  14391. this.tokens.push({
  14392. index: start,
  14393. text: this.text.slice(start, this.index),
  14394. identifier: true
  14395. });
  14396. },
  14397. readString: function(quote) {
  14398. var start = this.index;
  14399. this.index++;
  14400. var string = '';
  14401. var rawString = quote;
  14402. var escape = false;
  14403. while (this.index < this.text.length) {
  14404. var ch = this.text.charAt(this.index);
  14405. rawString += ch;
  14406. if (escape) {
  14407. if (ch === 'u') {
  14408. var hex = this.text.substring(this.index + 1, this.index + 5);
  14409. if (!hex.match(/[\da-f]{4}/i)) {
  14410. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  14411. }
  14412. this.index += 4;
  14413. string += String.fromCharCode(parseInt(hex, 16));
  14414. } else {
  14415. var rep = ESCAPE[ch];
  14416. string = string + (rep || ch);
  14417. }
  14418. escape = false;
  14419. } else if (ch === '\\') {
  14420. escape = true;
  14421. } else if (ch === quote) {
  14422. this.index++;
  14423. this.tokens.push({
  14424. index: start,
  14425. text: rawString,
  14426. constant: true,
  14427. value: string
  14428. });
  14429. return;
  14430. } else {
  14431. string += ch;
  14432. }
  14433. this.index++;
  14434. }
  14435. this.throwError('Unterminated quote', start);
  14436. }
  14437. };
  14438. var AST = function AST(lexer, options) {
  14439. this.lexer = lexer;
  14440. this.options = options;
  14441. };
  14442. AST.Program = 'Program';
  14443. AST.ExpressionStatement = 'ExpressionStatement';
  14444. AST.AssignmentExpression = 'AssignmentExpression';
  14445. AST.ConditionalExpression = 'ConditionalExpression';
  14446. AST.LogicalExpression = 'LogicalExpression';
  14447. AST.BinaryExpression = 'BinaryExpression';
  14448. AST.UnaryExpression = 'UnaryExpression';
  14449. AST.CallExpression = 'CallExpression';
  14450. AST.MemberExpression = 'MemberExpression';
  14451. AST.Identifier = 'Identifier';
  14452. AST.Literal = 'Literal';
  14453. AST.ArrayExpression = 'ArrayExpression';
  14454. AST.Property = 'Property';
  14455. AST.ObjectExpression = 'ObjectExpression';
  14456. AST.ThisExpression = 'ThisExpression';
  14457. AST.LocalsExpression = 'LocalsExpression';
  14458. // Internal use only
  14459. AST.NGValueParameter = 'NGValueParameter';
  14460. AST.prototype = {
  14461. ast: function(text) {
  14462. this.text = text;
  14463. this.tokens = this.lexer.lex(text);
  14464. var value = this.program();
  14465. if (this.tokens.length !== 0) {
  14466. this.throwError('is an unexpected token', this.tokens[0]);
  14467. }
  14468. return value;
  14469. },
  14470. program: function() {
  14471. var body = [];
  14472. while (true) {
  14473. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  14474. body.push(this.expressionStatement());
  14475. if (!this.expect(';')) {
  14476. return { type: AST.Program, body: body};
  14477. }
  14478. }
  14479. },
  14480. expressionStatement: function() {
  14481. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  14482. },
  14483. filterChain: function() {
  14484. var left = this.expression();
  14485. while (this.expect('|')) {
  14486. left = this.filter(left);
  14487. }
  14488. return left;
  14489. },
  14490. expression: function() {
  14491. return this.assignment();
  14492. },
  14493. assignment: function() {
  14494. var result = this.ternary();
  14495. if (this.expect('=')) {
  14496. if (!isAssignable(result)) {
  14497. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  14498. }
  14499. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  14500. }
  14501. return result;
  14502. },
  14503. ternary: function() {
  14504. var test = this.logicalOR();
  14505. var alternate;
  14506. var consequent;
  14507. if (this.expect('?')) {
  14508. alternate = this.expression();
  14509. if (this.consume(':')) {
  14510. consequent = this.expression();
  14511. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  14512. }
  14513. }
  14514. return test;
  14515. },
  14516. logicalOR: function() {
  14517. var left = this.logicalAND();
  14518. while (this.expect('||')) {
  14519. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  14520. }
  14521. return left;
  14522. },
  14523. logicalAND: function() {
  14524. var left = this.equality();
  14525. while (this.expect('&&')) {
  14526. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  14527. }
  14528. return left;
  14529. },
  14530. equality: function() {
  14531. var left = this.relational();
  14532. var token;
  14533. while ((token = this.expect('==','!=','===','!=='))) {
  14534. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  14535. }
  14536. return left;
  14537. },
  14538. relational: function() {
  14539. var left = this.additive();
  14540. var token;
  14541. while ((token = this.expect('<', '>', '<=', '>='))) {
  14542. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  14543. }
  14544. return left;
  14545. },
  14546. additive: function() {
  14547. var left = this.multiplicative();
  14548. var token;
  14549. while ((token = this.expect('+','-'))) {
  14550. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  14551. }
  14552. return left;
  14553. },
  14554. multiplicative: function() {
  14555. var left = this.unary();
  14556. var token;
  14557. while ((token = this.expect('*','/','%'))) {
  14558. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  14559. }
  14560. return left;
  14561. },
  14562. unary: function() {
  14563. var token;
  14564. if ((token = this.expect('+', '-', '!'))) {
  14565. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  14566. } else {
  14567. return this.primary();
  14568. }
  14569. },
  14570. primary: function() {
  14571. var primary;
  14572. if (this.expect('(')) {
  14573. primary = this.filterChain();
  14574. this.consume(')');
  14575. } else if (this.expect('[')) {
  14576. primary = this.arrayDeclaration();
  14577. } else if (this.expect('{')) {
  14578. primary = this.object();
  14579. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  14580. primary = copy(this.selfReferential[this.consume().text]);
  14581. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  14582. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  14583. } else if (this.peek().identifier) {
  14584. primary = this.identifier();
  14585. } else if (this.peek().constant) {
  14586. primary = this.constant();
  14587. } else {
  14588. this.throwError('not a primary expression', this.peek());
  14589. }
  14590. var next;
  14591. while ((next = this.expect('(', '[', '.'))) {
  14592. if (next.text === '(') {
  14593. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  14594. this.consume(')');
  14595. } else if (next.text === '[') {
  14596. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  14597. this.consume(']');
  14598. } else if (next.text === '.') {
  14599. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  14600. } else {
  14601. this.throwError('IMPOSSIBLE');
  14602. }
  14603. }
  14604. return primary;
  14605. },
  14606. filter: function(baseExpression) {
  14607. var args = [baseExpression];
  14608. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  14609. while (this.expect(':')) {
  14610. args.push(this.expression());
  14611. }
  14612. return result;
  14613. },
  14614. parseArguments: function() {
  14615. var args = [];
  14616. if (this.peekToken().text !== ')') {
  14617. do {
  14618. args.push(this.filterChain());
  14619. } while (this.expect(','));
  14620. }
  14621. return args;
  14622. },
  14623. identifier: function() {
  14624. var token = this.consume();
  14625. if (!token.identifier) {
  14626. this.throwError('is not a valid identifier', token);
  14627. }
  14628. return { type: AST.Identifier, name: token.text };
  14629. },
  14630. constant: function() {
  14631. // TODO check that it is a constant
  14632. return { type: AST.Literal, value: this.consume().value };
  14633. },
  14634. arrayDeclaration: function() {
  14635. var elements = [];
  14636. if (this.peekToken().text !== ']') {
  14637. do {
  14638. if (this.peek(']')) {
  14639. // Support trailing commas per ES5.1.
  14640. break;
  14641. }
  14642. elements.push(this.expression());
  14643. } while (this.expect(','));
  14644. }
  14645. this.consume(']');
  14646. return { type: AST.ArrayExpression, elements: elements };
  14647. },
  14648. object: function() {
  14649. var properties = [], property;
  14650. if (this.peekToken().text !== '}') {
  14651. do {
  14652. if (this.peek('}')) {
  14653. // Support trailing commas per ES5.1.
  14654. break;
  14655. }
  14656. property = {type: AST.Property, kind: 'init'};
  14657. if (this.peek().constant) {
  14658. property.key = this.constant();
  14659. property.computed = false;
  14660. this.consume(':');
  14661. property.value = this.expression();
  14662. } else if (this.peek().identifier) {
  14663. property.key = this.identifier();
  14664. property.computed = false;
  14665. if (this.peek(':')) {
  14666. this.consume(':');
  14667. property.value = this.expression();
  14668. } else {
  14669. property.value = property.key;
  14670. }
  14671. } else if (this.peek('[')) {
  14672. this.consume('[');
  14673. property.key = this.expression();
  14674. this.consume(']');
  14675. property.computed = true;
  14676. this.consume(':');
  14677. property.value = this.expression();
  14678. } else {
  14679. this.throwError('invalid key', this.peek());
  14680. }
  14681. properties.push(property);
  14682. } while (this.expect(','));
  14683. }
  14684. this.consume('}');
  14685. return {type: AST.ObjectExpression, properties: properties };
  14686. },
  14687. throwError: function(msg, token) {
  14688. throw $parseMinErr('syntax',
  14689. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  14690. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  14691. },
  14692. consume: function(e1) {
  14693. if (this.tokens.length === 0) {
  14694. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  14695. }
  14696. var token = this.expect(e1);
  14697. if (!token) {
  14698. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  14699. }
  14700. return token;
  14701. },
  14702. peekToken: function() {
  14703. if (this.tokens.length === 0) {
  14704. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  14705. }
  14706. return this.tokens[0];
  14707. },
  14708. peek: function(e1, e2, e3, e4) {
  14709. return this.peekAhead(0, e1, e2, e3, e4);
  14710. },
  14711. peekAhead: function(i, e1, e2, e3, e4) {
  14712. if (this.tokens.length > i) {
  14713. var token = this.tokens[i];
  14714. var t = token.text;
  14715. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  14716. (!e1 && !e2 && !e3 && !e4)) {
  14717. return token;
  14718. }
  14719. }
  14720. return false;
  14721. },
  14722. expect: function(e1, e2, e3, e4) {
  14723. var token = this.peek(e1, e2, e3, e4);
  14724. if (token) {
  14725. this.tokens.shift();
  14726. return token;
  14727. }
  14728. return false;
  14729. },
  14730. selfReferential: {
  14731. 'this': {type: AST.ThisExpression },
  14732. '$locals': {type: AST.LocalsExpression }
  14733. }
  14734. };
  14735. function ifDefined(v, d) {
  14736. return typeof v !== 'undefined' ? v : d;
  14737. }
  14738. function plusFn(l, r) {
  14739. if (typeof l === 'undefined') return r;
  14740. if (typeof r === 'undefined') return l;
  14741. return l + r;
  14742. }
  14743. function isStateless($filter, filterName) {
  14744. var fn = $filter(filterName);
  14745. return !fn.$stateful;
  14746. }
  14747. var PURITY_ABSOLUTE = 1;
  14748. var PURITY_RELATIVE = 2;
  14749. // Detect nodes which could depend on non-shallow state of objects
  14750. function isPure(node, parentIsPure) {
  14751. switch (node.type) {
  14752. // Computed members might invoke a stateful toString()
  14753. case AST.MemberExpression:
  14754. if (node.computed) {
  14755. return false;
  14756. }
  14757. break;
  14758. // Unary always convert to primative
  14759. case AST.UnaryExpression:
  14760. return PURITY_ABSOLUTE;
  14761. // The binary + operator can invoke a stateful toString().
  14762. case AST.BinaryExpression:
  14763. return node.operator !== '+' ? PURITY_ABSOLUTE : false;
  14764. // Functions / filters probably read state from within objects
  14765. case AST.CallExpression:
  14766. return false;
  14767. }
  14768. return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;
  14769. }
  14770. function findConstantAndWatchExpressions(ast, $filter, parentIsPure) {
  14771. var allConstants;
  14772. var argsToWatch;
  14773. var isStatelessFilter;
  14774. var astIsPure = ast.isPure = isPure(ast, parentIsPure);
  14775. switch (ast.type) {
  14776. case AST.Program:
  14777. allConstants = true;
  14778. forEach(ast.body, function(expr) {
  14779. findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);
  14780. allConstants = allConstants && expr.expression.constant;
  14781. });
  14782. ast.constant = allConstants;
  14783. break;
  14784. case AST.Literal:
  14785. ast.constant = true;
  14786. ast.toWatch = [];
  14787. break;
  14788. case AST.UnaryExpression:
  14789. findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);
  14790. ast.constant = ast.argument.constant;
  14791. ast.toWatch = ast.argument.toWatch;
  14792. break;
  14793. case AST.BinaryExpression:
  14794. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14795. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14796. ast.constant = ast.left.constant && ast.right.constant;
  14797. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  14798. break;
  14799. case AST.LogicalExpression:
  14800. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14801. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14802. ast.constant = ast.left.constant && ast.right.constant;
  14803. ast.toWatch = ast.constant ? [] : [ast];
  14804. break;
  14805. case AST.ConditionalExpression:
  14806. findConstantAndWatchExpressions(ast.test, $filter, astIsPure);
  14807. findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);
  14808. findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);
  14809. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  14810. ast.toWatch = ast.constant ? [] : [ast];
  14811. break;
  14812. case AST.Identifier:
  14813. ast.constant = false;
  14814. ast.toWatch = [ast];
  14815. break;
  14816. case AST.MemberExpression:
  14817. findConstantAndWatchExpressions(ast.object, $filter, astIsPure);
  14818. if (ast.computed) {
  14819. findConstantAndWatchExpressions(ast.property, $filter, astIsPure);
  14820. }
  14821. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  14822. ast.toWatch = ast.constant ? [] : [ast];
  14823. break;
  14824. case AST.CallExpression:
  14825. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  14826. allConstants = isStatelessFilter;
  14827. argsToWatch = [];
  14828. forEach(ast.arguments, function(expr) {
  14829. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14830. allConstants = allConstants && expr.constant;
  14831. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14832. });
  14833. ast.constant = allConstants;
  14834. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  14835. break;
  14836. case AST.AssignmentExpression:
  14837. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14838. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14839. ast.constant = ast.left.constant && ast.right.constant;
  14840. ast.toWatch = [ast];
  14841. break;
  14842. case AST.ArrayExpression:
  14843. allConstants = true;
  14844. argsToWatch = [];
  14845. forEach(ast.elements, function(expr) {
  14846. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14847. allConstants = allConstants && expr.constant;
  14848. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14849. });
  14850. ast.constant = allConstants;
  14851. ast.toWatch = argsToWatch;
  14852. break;
  14853. case AST.ObjectExpression:
  14854. allConstants = true;
  14855. argsToWatch = [];
  14856. forEach(ast.properties, function(property) {
  14857. findConstantAndWatchExpressions(property.value, $filter, astIsPure);
  14858. allConstants = allConstants && property.value.constant;
  14859. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  14860. if (property.computed) {
  14861. //`{[key]: value}` implicitly does `key.toString()` which may be non-pure
  14862. findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);
  14863. allConstants = allConstants && property.key.constant;
  14864. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  14865. }
  14866. });
  14867. ast.constant = allConstants;
  14868. ast.toWatch = argsToWatch;
  14869. break;
  14870. case AST.ThisExpression:
  14871. ast.constant = false;
  14872. ast.toWatch = [];
  14873. break;
  14874. case AST.LocalsExpression:
  14875. ast.constant = false;
  14876. ast.toWatch = [];
  14877. break;
  14878. }
  14879. }
  14880. function getInputs(body) {
  14881. if (body.length !== 1) return;
  14882. var lastExpression = body[0].expression;
  14883. var candidate = lastExpression.toWatch;
  14884. if (candidate.length !== 1) return candidate;
  14885. return candidate[0] !== lastExpression ? candidate : undefined;
  14886. }
  14887. function isAssignable(ast) {
  14888. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  14889. }
  14890. function assignableAST(ast) {
  14891. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  14892. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  14893. }
  14894. }
  14895. function isLiteral(ast) {
  14896. return ast.body.length === 0 ||
  14897. ast.body.length === 1 && (
  14898. ast.body[0].expression.type === AST.Literal ||
  14899. ast.body[0].expression.type === AST.ArrayExpression ||
  14900. ast.body[0].expression.type === AST.ObjectExpression);
  14901. }
  14902. function isConstant(ast) {
  14903. return ast.constant;
  14904. }
  14905. function ASTCompiler($filter) {
  14906. this.$filter = $filter;
  14907. }
  14908. ASTCompiler.prototype = {
  14909. compile: function(ast) {
  14910. var self = this;
  14911. this.state = {
  14912. nextId: 0,
  14913. filters: {},
  14914. fn: {vars: [], body: [], own: {}},
  14915. assign: {vars: [], body: [], own: {}},
  14916. inputs: []
  14917. };
  14918. findConstantAndWatchExpressions(ast, self.$filter);
  14919. var extra = '';
  14920. var assignable;
  14921. this.stage = 'assign';
  14922. if ((assignable = assignableAST(ast))) {
  14923. this.state.computing = 'assign';
  14924. var result = this.nextId();
  14925. this.recurse(assignable, result);
  14926. this.return_(result);
  14927. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  14928. }
  14929. var toWatch = getInputs(ast.body);
  14930. self.stage = 'inputs';
  14931. forEach(toWatch, function(watch, key) {
  14932. var fnKey = 'fn' + key;
  14933. self.state[fnKey] = {vars: [], body: [], own: {}};
  14934. self.state.computing = fnKey;
  14935. var intoId = self.nextId();
  14936. self.recurse(watch, intoId);
  14937. self.return_(intoId);
  14938. self.state.inputs.push({name: fnKey, isPure: watch.isPure});
  14939. watch.watchId = key;
  14940. });
  14941. this.state.computing = 'fn';
  14942. this.stage = 'main';
  14943. this.recurse(ast);
  14944. var fnString =
  14945. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  14946. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  14947. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  14948. this.filterPrefix() +
  14949. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  14950. extra +
  14951. this.watchFns() +
  14952. 'return fn;';
  14953. // eslint-disable-next-line no-new-func
  14954. var fn = (new Function('$filter',
  14955. 'getStringValue',
  14956. 'ifDefined',
  14957. 'plus',
  14958. fnString))(
  14959. this.$filter,
  14960. getStringValue,
  14961. ifDefined,
  14962. plusFn);
  14963. this.state = this.stage = undefined;
  14964. return fn;
  14965. },
  14966. USE: 'use',
  14967. STRICT: 'strict',
  14968. watchFns: function() {
  14969. var result = [];
  14970. var inputs = this.state.inputs;
  14971. var self = this;
  14972. forEach(inputs, function(input) {
  14973. result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));
  14974. if (input.isPure) {
  14975. result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');
  14976. }
  14977. });
  14978. if (inputs.length) {
  14979. result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');
  14980. }
  14981. return result.join('');
  14982. },
  14983. generateFunction: function(name, params) {
  14984. return 'function(' + params + '){' +
  14985. this.varsPrefix(name) +
  14986. this.body(name) +
  14987. '};';
  14988. },
  14989. filterPrefix: function() {
  14990. var parts = [];
  14991. var self = this;
  14992. forEach(this.state.filters, function(id, filter) {
  14993. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  14994. });
  14995. if (parts.length) return 'var ' + parts.join(',') + ';';
  14996. return '';
  14997. },
  14998. varsPrefix: function(section) {
  14999. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  15000. },
  15001. body: function(section) {
  15002. return this.state[section].body.join('');
  15003. },
  15004. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  15005. var left, right, self = this, args, expression, computed;
  15006. recursionFn = recursionFn || noop;
  15007. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  15008. intoId = intoId || this.nextId();
  15009. this.if_('i',
  15010. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  15011. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  15012. );
  15013. return;
  15014. }
  15015. switch (ast.type) {
  15016. case AST.Program:
  15017. forEach(ast.body, function(expression, pos) {
  15018. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  15019. if (pos !== ast.body.length - 1) {
  15020. self.current().body.push(right, ';');
  15021. } else {
  15022. self.return_(right);
  15023. }
  15024. });
  15025. break;
  15026. case AST.Literal:
  15027. expression = this.escape(ast.value);
  15028. this.assign(intoId, expression);
  15029. recursionFn(intoId || expression);
  15030. break;
  15031. case AST.UnaryExpression:
  15032. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  15033. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  15034. this.assign(intoId, expression);
  15035. recursionFn(expression);
  15036. break;
  15037. case AST.BinaryExpression:
  15038. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  15039. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  15040. if (ast.operator === '+') {
  15041. expression = this.plus(left, right);
  15042. } else if (ast.operator === '-') {
  15043. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  15044. } else {
  15045. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  15046. }
  15047. this.assign(intoId, expression);
  15048. recursionFn(expression);
  15049. break;
  15050. case AST.LogicalExpression:
  15051. intoId = intoId || this.nextId();
  15052. self.recurse(ast.left, intoId);
  15053. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  15054. recursionFn(intoId);
  15055. break;
  15056. case AST.ConditionalExpression:
  15057. intoId = intoId || this.nextId();
  15058. self.recurse(ast.test, intoId);
  15059. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  15060. recursionFn(intoId);
  15061. break;
  15062. case AST.Identifier:
  15063. intoId = intoId || this.nextId();
  15064. if (nameId) {
  15065. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  15066. nameId.computed = false;
  15067. nameId.name = ast.name;
  15068. }
  15069. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  15070. function() {
  15071. self.if_(self.stage === 'inputs' || 's', function() {
  15072. if (create && create !== 1) {
  15073. self.if_(
  15074. self.isNull(self.nonComputedMember('s', ast.name)),
  15075. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  15076. }
  15077. self.assign(intoId, self.nonComputedMember('s', ast.name));
  15078. });
  15079. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  15080. );
  15081. recursionFn(intoId);
  15082. break;
  15083. case AST.MemberExpression:
  15084. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  15085. intoId = intoId || this.nextId();
  15086. self.recurse(ast.object, left, undefined, function() {
  15087. self.if_(self.notNull(left), function() {
  15088. if (ast.computed) {
  15089. right = self.nextId();
  15090. self.recurse(ast.property, right);
  15091. self.getStringValue(right);
  15092. if (create && create !== 1) {
  15093. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  15094. }
  15095. expression = self.computedMember(left, right);
  15096. self.assign(intoId, expression);
  15097. if (nameId) {
  15098. nameId.computed = true;
  15099. nameId.name = right;
  15100. }
  15101. } else {
  15102. if (create && create !== 1) {
  15103. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  15104. }
  15105. expression = self.nonComputedMember(left, ast.property.name);
  15106. self.assign(intoId, expression);
  15107. if (nameId) {
  15108. nameId.computed = false;
  15109. nameId.name = ast.property.name;
  15110. }
  15111. }
  15112. }, function() {
  15113. self.assign(intoId, 'undefined');
  15114. });
  15115. recursionFn(intoId);
  15116. }, !!create);
  15117. break;
  15118. case AST.CallExpression:
  15119. intoId = intoId || this.nextId();
  15120. if (ast.filter) {
  15121. right = self.filter(ast.callee.name);
  15122. args = [];
  15123. forEach(ast.arguments, function(expr) {
  15124. var argument = self.nextId();
  15125. self.recurse(expr, argument);
  15126. args.push(argument);
  15127. });
  15128. expression = right + '(' + args.join(',') + ')';
  15129. self.assign(intoId, expression);
  15130. recursionFn(intoId);
  15131. } else {
  15132. right = self.nextId();
  15133. left = {};
  15134. args = [];
  15135. self.recurse(ast.callee, right, left, function() {
  15136. self.if_(self.notNull(right), function() {
  15137. forEach(ast.arguments, function(expr) {
  15138. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  15139. args.push(argument);
  15140. });
  15141. });
  15142. if (left.name) {
  15143. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  15144. } else {
  15145. expression = right + '(' + args.join(',') + ')';
  15146. }
  15147. self.assign(intoId, expression);
  15148. }, function() {
  15149. self.assign(intoId, 'undefined');
  15150. });
  15151. recursionFn(intoId);
  15152. });
  15153. }
  15154. break;
  15155. case AST.AssignmentExpression:
  15156. right = this.nextId();
  15157. left = {};
  15158. this.recurse(ast.left, undefined, left, function() {
  15159. self.if_(self.notNull(left.context), function() {
  15160. self.recurse(ast.right, right);
  15161. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  15162. self.assign(intoId, expression);
  15163. recursionFn(intoId || expression);
  15164. });
  15165. }, 1);
  15166. break;
  15167. case AST.ArrayExpression:
  15168. args = [];
  15169. forEach(ast.elements, function(expr) {
  15170. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  15171. args.push(argument);
  15172. });
  15173. });
  15174. expression = '[' + args.join(',') + ']';
  15175. this.assign(intoId, expression);
  15176. recursionFn(intoId || expression);
  15177. break;
  15178. case AST.ObjectExpression:
  15179. args = [];
  15180. computed = false;
  15181. forEach(ast.properties, function(property) {
  15182. if (property.computed) {
  15183. computed = true;
  15184. }
  15185. });
  15186. if (computed) {
  15187. intoId = intoId || this.nextId();
  15188. this.assign(intoId, '{}');
  15189. forEach(ast.properties, function(property) {
  15190. if (property.computed) {
  15191. left = self.nextId();
  15192. self.recurse(property.key, left);
  15193. } else {
  15194. left = property.key.type === AST.Identifier ?
  15195. property.key.name :
  15196. ('' + property.key.value);
  15197. }
  15198. right = self.nextId();
  15199. self.recurse(property.value, right);
  15200. self.assign(self.member(intoId, left, property.computed), right);
  15201. });
  15202. } else {
  15203. forEach(ast.properties, function(property) {
  15204. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  15205. args.push(self.escape(
  15206. property.key.type === AST.Identifier ? property.key.name :
  15207. ('' + property.key.value)) +
  15208. ':' + expr);
  15209. });
  15210. });
  15211. expression = '{' + args.join(',') + '}';
  15212. this.assign(intoId, expression);
  15213. }
  15214. recursionFn(intoId || expression);
  15215. break;
  15216. case AST.ThisExpression:
  15217. this.assign(intoId, 's');
  15218. recursionFn(intoId || 's');
  15219. break;
  15220. case AST.LocalsExpression:
  15221. this.assign(intoId, 'l');
  15222. recursionFn(intoId || 'l');
  15223. break;
  15224. case AST.NGValueParameter:
  15225. this.assign(intoId, 'v');
  15226. recursionFn(intoId || 'v');
  15227. break;
  15228. }
  15229. },
  15230. getHasOwnProperty: function(element, property) {
  15231. var key = element + '.' + property;
  15232. var own = this.current().own;
  15233. if (!own.hasOwnProperty(key)) {
  15234. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  15235. }
  15236. return own[key];
  15237. },
  15238. assign: function(id, value) {
  15239. if (!id) return;
  15240. this.current().body.push(id, '=', value, ';');
  15241. return id;
  15242. },
  15243. filter: function(filterName) {
  15244. if (!this.state.filters.hasOwnProperty(filterName)) {
  15245. this.state.filters[filterName] = this.nextId(true);
  15246. }
  15247. return this.state.filters[filterName];
  15248. },
  15249. ifDefined: function(id, defaultValue) {
  15250. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  15251. },
  15252. plus: function(left, right) {
  15253. return 'plus(' + left + ',' + right + ')';
  15254. },
  15255. return_: function(id) {
  15256. this.current().body.push('return ', id, ';');
  15257. },
  15258. if_: function(test, alternate, consequent) {
  15259. if (test === true) {
  15260. alternate();
  15261. } else {
  15262. var body = this.current().body;
  15263. body.push('if(', test, '){');
  15264. alternate();
  15265. body.push('}');
  15266. if (consequent) {
  15267. body.push('else{');
  15268. consequent();
  15269. body.push('}');
  15270. }
  15271. }
  15272. },
  15273. not: function(expression) {
  15274. return '!(' + expression + ')';
  15275. },
  15276. isNull: function(expression) {
  15277. return expression + '==null';
  15278. },
  15279. notNull: function(expression) {
  15280. return expression + '!=null';
  15281. },
  15282. nonComputedMember: function(left, right) {
  15283. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  15284. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  15285. if (SAFE_IDENTIFIER.test(right)) {
  15286. return left + '.' + right;
  15287. } else {
  15288. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  15289. }
  15290. },
  15291. computedMember: function(left, right) {
  15292. return left + '[' + right + ']';
  15293. },
  15294. member: function(left, right, computed) {
  15295. if (computed) return this.computedMember(left, right);
  15296. return this.nonComputedMember(left, right);
  15297. },
  15298. getStringValue: function(item) {
  15299. this.assign(item, 'getStringValue(' + item + ')');
  15300. },
  15301. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  15302. var self = this;
  15303. return function() {
  15304. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  15305. };
  15306. },
  15307. lazyAssign: function(id, value) {
  15308. var self = this;
  15309. return function() {
  15310. self.assign(id, value);
  15311. };
  15312. },
  15313. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  15314. stringEscapeFn: function(c) {
  15315. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  15316. },
  15317. escape: function(value) {
  15318. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  15319. if (isNumber(value)) return value.toString();
  15320. if (value === true) return 'true';
  15321. if (value === false) return 'false';
  15322. if (value === null) return 'null';
  15323. if (typeof value === 'undefined') return 'undefined';
  15324. throw $parseMinErr('esc', 'IMPOSSIBLE');
  15325. },
  15326. nextId: function(skip, init) {
  15327. var id = 'v' + (this.state.nextId++);
  15328. if (!skip) {
  15329. this.current().vars.push(id + (init ? '=' + init : ''));
  15330. }
  15331. return id;
  15332. },
  15333. current: function() {
  15334. return this.state[this.state.computing];
  15335. }
  15336. };
  15337. function ASTInterpreter($filter) {
  15338. this.$filter = $filter;
  15339. }
  15340. ASTInterpreter.prototype = {
  15341. compile: function(ast) {
  15342. var self = this;
  15343. findConstantAndWatchExpressions(ast, self.$filter);
  15344. var assignable;
  15345. var assign;
  15346. if ((assignable = assignableAST(ast))) {
  15347. assign = this.recurse(assignable);
  15348. }
  15349. var toWatch = getInputs(ast.body);
  15350. var inputs;
  15351. if (toWatch) {
  15352. inputs = [];
  15353. forEach(toWatch, function(watch, key) {
  15354. var input = self.recurse(watch);
  15355. input.isPure = watch.isPure;
  15356. watch.input = input;
  15357. inputs.push(input);
  15358. watch.watchId = key;
  15359. });
  15360. }
  15361. var expressions = [];
  15362. forEach(ast.body, function(expression) {
  15363. expressions.push(self.recurse(expression.expression));
  15364. });
  15365. var fn = ast.body.length === 0 ? noop :
  15366. ast.body.length === 1 ? expressions[0] :
  15367. function(scope, locals) {
  15368. var lastValue;
  15369. forEach(expressions, function(exp) {
  15370. lastValue = exp(scope, locals);
  15371. });
  15372. return lastValue;
  15373. };
  15374. if (assign) {
  15375. fn.assign = function(scope, value, locals) {
  15376. return assign(scope, locals, value);
  15377. };
  15378. }
  15379. if (inputs) {
  15380. fn.inputs = inputs;
  15381. }
  15382. return fn;
  15383. },
  15384. recurse: function(ast, context, create) {
  15385. var left, right, self = this, args;
  15386. if (ast.input) {
  15387. return this.inputs(ast.input, ast.watchId);
  15388. }
  15389. switch (ast.type) {
  15390. case AST.Literal:
  15391. return this.value(ast.value, context);
  15392. case AST.UnaryExpression:
  15393. right = this.recurse(ast.argument);
  15394. return this['unary' + ast.operator](right, context);
  15395. case AST.BinaryExpression:
  15396. left = this.recurse(ast.left);
  15397. right = this.recurse(ast.right);
  15398. return this['binary' + ast.operator](left, right, context);
  15399. case AST.LogicalExpression:
  15400. left = this.recurse(ast.left);
  15401. right = this.recurse(ast.right);
  15402. return this['binary' + ast.operator](left, right, context);
  15403. case AST.ConditionalExpression:
  15404. return this['ternary?:'](
  15405. this.recurse(ast.test),
  15406. this.recurse(ast.alternate),
  15407. this.recurse(ast.consequent),
  15408. context
  15409. );
  15410. case AST.Identifier:
  15411. return self.identifier(ast.name, context, create);
  15412. case AST.MemberExpression:
  15413. left = this.recurse(ast.object, false, !!create);
  15414. if (!ast.computed) {
  15415. right = ast.property.name;
  15416. }
  15417. if (ast.computed) right = this.recurse(ast.property);
  15418. return ast.computed ?
  15419. this.computedMember(left, right, context, create) :
  15420. this.nonComputedMember(left, right, context, create);
  15421. case AST.CallExpression:
  15422. args = [];
  15423. forEach(ast.arguments, function(expr) {
  15424. args.push(self.recurse(expr));
  15425. });
  15426. if (ast.filter) right = this.$filter(ast.callee.name);
  15427. if (!ast.filter) right = this.recurse(ast.callee, true);
  15428. return ast.filter ?
  15429. function(scope, locals, assign, inputs) {
  15430. var values = [];
  15431. for (var i = 0; i < args.length; ++i) {
  15432. values.push(args[i](scope, locals, assign, inputs));
  15433. }
  15434. var value = right.apply(undefined, values, inputs);
  15435. return context ? {context: undefined, name: undefined, value: value} : value;
  15436. } :
  15437. function(scope, locals, assign, inputs) {
  15438. var rhs = right(scope, locals, assign, inputs);
  15439. var value;
  15440. if (rhs.value != null) {
  15441. var values = [];
  15442. for (var i = 0; i < args.length; ++i) {
  15443. values.push(args[i](scope, locals, assign, inputs));
  15444. }
  15445. value = rhs.value.apply(rhs.context, values);
  15446. }
  15447. return context ? {value: value} : value;
  15448. };
  15449. case AST.AssignmentExpression:
  15450. left = this.recurse(ast.left, true, 1);
  15451. right = this.recurse(ast.right);
  15452. return function(scope, locals, assign, inputs) {
  15453. var lhs = left(scope, locals, assign, inputs);
  15454. var rhs = right(scope, locals, assign, inputs);
  15455. lhs.context[lhs.name] = rhs;
  15456. return context ? {value: rhs} : rhs;
  15457. };
  15458. case AST.ArrayExpression:
  15459. args = [];
  15460. forEach(ast.elements, function(expr) {
  15461. args.push(self.recurse(expr));
  15462. });
  15463. return function(scope, locals, assign, inputs) {
  15464. var value = [];
  15465. for (var i = 0; i < args.length; ++i) {
  15466. value.push(args[i](scope, locals, assign, inputs));
  15467. }
  15468. return context ? {value: value} : value;
  15469. };
  15470. case AST.ObjectExpression:
  15471. args = [];
  15472. forEach(ast.properties, function(property) {
  15473. if (property.computed) {
  15474. args.push({key: self.recurse(property.key),
  15475. computed: true,
  15476. value: self.recurse(property.value)
  15477. });
  15478. } else {
  15479. args.push({key: property.key.type === AST.Identifier ?
  15480. property.key.name :
  15481. ('' + property.key.value),
  15482. computed: false,
  15483. value: self.recurse(property.value)
  15484. });
  15485. }
  15486. });
  15487. return function(scope, locals, assign, inputs) {
  15488. var value = {};
  15489. for (var i = 0; i < args.length; ++i) {
  15490. if (args[i].computed) {
  15491. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  15492. } else {
  15493. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  15494. }
  15495. }
  15496. return context ? {value: value} : value;
  15497. };
  15498. case AST.ThisExpression:
  15499. return function(scope) {
  15500. return context ? {value: scope} : scope;
  15501. };
  15502. case AST.LocalsExpression:
  15503. return function(scope, locals) {
  15504. return context ? {value: locals} : locals;
  15505. };
  15506. case AST.NGValueParameter:
  15507. return function(scope, locals, assign) {
  15508. return context ? {value: assign} : assign;
  15509. };
  15510. }
  15511. },
  15512. 'unary+': function(argument, context) {
  15513. return function(scope, locals, assign, inputs) {
  15514. var arg = argument(scope, locals, assign, inputs);
  15515. if (isDefined(arg)) {
  15516. arg = +arg;
  15517. } else {
  15518. arg = 0;
  15519. }
  15520. return context ? {value: arg} : arg;
  15521. };
  15522. },
  15523. 'unary-': function(argument, context) {
  15524. return function(scope, locals, assign, inputs) {
  15525. var arg = argument(scope, locals, assign, inputs);
  15526. if (isDefined(arg)) {
  15527. arg = -arg;
  15528. } else {
  15529. arg = -0;
  15530. }
  15531. return context ? {value: arg} : arg;
  15532. };
  15533. },
  15534. 'unary!': function(argument, context) {
  15535. return function(scope, locals, assign, inputs) {
  15536. var arg = !argument(scope, locals, assign, inputs);
  15537. return context ? {value: arg} : arg;
  15538. };
  15539. },
  15540. 'binary+': function(left, right, context) {
  15541. return function(scope, locals, assign, inputs) {
  15542. var lhs = left(scope, locals, assign, inputs);
  15543. var rhs = right(scope, locals, assign, inputs);
  15544. var arg = plusFn(lhs, rhs);
  15545. return context ? {value: arg} : arg;
  15546. };
  15547. },
  15548. 'binary-': function(left, right, context) {
  15549. return function(scope, locals, assign, inputs) {
  15550. var lhs = left(scope, locals, assign, inputs);
  15551. var rhs = right(scope, locals, assign, inputs);
  15552. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  15553. return context ? {value: arg} : arg;
  15554. };
  15555. },
  15556. 'binary*': function(left, right, context) {
  15557. return function(scope, locals, assign, inputs) {
  15558. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  15559. return context ? {value: arg} : arg;
  15560. };
  15561. },
  15562. 'binary/': function(left, right, context) {
  15563. return function(scope, locals, assign, inputs) {
  15564. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  15565. return context ? {value: arg} : arg;
  15566. };
  15567. },
  15568. 'binary%': function(left, right, context) {
  15569. return function(scope, locals, assign, inputs) {
  15570. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  15571. return context ? {value: arg} : arg;
  15572. };
  15573. },
  15574. 'binary===': function(left, right, context) {
  15575. return function(scope, locals, assign, inputs) {
  15576. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  15577. return context ? {value: arg} : arg;
  15578. };
  15579. },
  15580. 'binary!==': function(left, right, context) {
  15581. return function(scope, locals, assign, inputs) {
  15582. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  15583. return context ? {value: arg} : arg;
  15584. };
  15585. },
  15586. 'binary==': function(left, right, context) {
  15587. return function(scope, locals, assign, inputs) {
  15588. // eslint-disable-next-line eqeqeq
  15589. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  15590. return context ? {value: arg} : arg;
  15591. };
  15592. },
  15593. 'binary!=': function(left, right, context) {
  15594. return function(scope, locals, assign, inputs) {
  15595. // eslint-disable-next-line eqeqeq
  15596. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  15597. return context ? {value: arg} : arg;
  15598. };
  15599. },
  15600. 'binary<': function(left, right, context) {
  15601. return function(scope, locals, assign, inputs) {
  15602. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  15603. return context ? {value: arg} : arg;
  15604. };
  15605. },
  15606. 'binary>': function(left, right, context) {
  15607. return function(scope, locals, assign, inputs) {
  15608. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  15609. return context ? {value: arg} : arg;
  15610. };
  15611. },
  15612. 'binary<=': function(left, right, context) {
  15613. return function(scope, locals, assign, inputs) {
  15614. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  15615. return context ? {value: arg} : arg;
  15616. };
  15617. },
  15618. 'binary>=': function(left, right, context) {
  15619. return function(scope, locals, assign, inputs) {
  15620. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  15621. return context ? {value: arg} : arg;
  15622. };
  15623. },
  15624. 'binary&&': function(left, right, context) {
  15625. return function(scope, locals, assign, inputs) {
  15626. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  15627. return context ? {value: arg} : arg;
  15628. };
  15629. },
  15630. 'binary||': function(left, right, context) {
  15631. return function(scope, locals, assign, inputs) {
  15632. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  15633. return context ? {value: arg} : arg;
  15634. };
  15635. },
  15636. 'ternary?:': function(test, alternate, consequent, context) {
  15637. return function(scope, locals, assign, inputs) {
  15638. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  15639. return context ? {value: arg} : arg;
  15640. };
  15641. },
  15642. value: function(value, context) {
  15643. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  15644. },
  15645. identifier: function(name, context, create) {
  15646. return function(scope, locals, assign, inputs) {
  15647. var base = locals && (name in locals) ? locals : scope;
  15648. if (create && create !== 1 && base && base[name] == null) {
  15649. base[name] = {};
  15650. }
  15651. var value = base ? base[name] : undefined;
  15652. if (context) {
  15653. return {context: base, name: name, value: value};
  15654. } else {
  15655. return value;
  15656. }
  15657. };
  15658. },
  15659. computedMember: function(left, right, context, create) {
  15660. return function(scope, locals, assign, inputs) {
  15661. var lhs = left(scope, locals, assign, inputs);
  15662. var rhs;
  15663. var value;
  15664. if (lhs != null) {
  15665. rhs = right(scope, locals, assign, inputs);
  15666. rhs = getStringValue(rhs);
  15667. if (create && create !== 1) {
  15668. if (lhs && !(lhs[rhs])) {
  15669. lhs[rhs] = {};
  15670. }
  15671. }
  15672. value = lhs[rhs];
  15673. }
  15674. if (context) {
  15675. return {context: lhs, name: rhs, value: value};
  15676. } else {
  15677. return value;
  15678. }
  15679. };
  15680. },
  15681. nonComputedMember: function(left, right, context, create) {
  15682. return function(scope, locals, assign, inputs) {
  15683. var lhs = left(scope, locals, assign, inputs);
  15684. if (create && create !== 1) {
  15685. if (lhs && lhs[right] == null) {
  15686. lhs[right] = {};
  15687. }
  15688. }
  15689. var value = lhs != null ? lhs[right] : undefined;
  15690. if (context) {
  15691. return {context: lhs, name: right, value: value};
  15692. } else {
  15693. return value;
  15694. }
  15695. };
  15696. },
  15697. inputs: function(input, watchId) {
  15698. return function(scope, value, locals, inputs) {
  15699. if (inputs) return inputs[watchId];
  15700. return input(scope, value, locals);
  15701. };
  15702. }
  15703. };
  15704. /**
  15705. * @constructor
  15706. */
  15707. function Parser(lexer, $filter, options) {
  15708. this.ast = new AST(lexer, options);
  15709. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  15710. new ASTCompiler($filter);
  15711. }
  15712. Parser.prototype = {
  15713. constructor: Parser,
  15714. parse: function(text) {
  15715. var ast = this.getAst(text);
  15716. var fn = this.astCompiler.compile(ast.ast);
  15717. fn.literal = isLiteral(ast.ast);
  15718. fn.constant = isConstant(ast.ast);
  15719. fn.oneTime = ast.oneTime;
  15720. return fn;
  15721. },
  15722. getAst: function(exp) {
  15723. var oneTime = false;
  15724. exp = exp.trim();
  15725. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  15726. oneTime = true;
  15727. exp = exp.substring(2);
  15728. }
  15729. return {
  15730. ast: this.ast.ast(exp),
  15731. oneTime: oneTime
  15732. };
  15733. }
  15734. };
  15735. function getValueOf(value) {
  15736. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  15737. }
  15738. ///////////////////////////////////
  15739. /**
  15740. * @ngdoc service
  15741. * @name $parse
  15742. * @kind function
  15743. *
  15744. * @description
  15745. *
  15746. * Converts AngularJS {@link guide/expression expression} into a function.
  15747. *
  15748. * ```js
  15749. * var getter = $parse('user.name');
  15750. * var setter = getter.assign;
  15751. * var context = {user:{name:'AngularJS'}};
  15752. * var locals = {user:{name:'local'}};
  15753. *
  15754. * expect(getter(context)).toEqual('AngularJS');
  15755. * setter(context, 'newValue');
  15756. * expect(context.user.name).toEqual('newValue');
  15757. * expect(getter(context, locals)).toEqual('local');
  15758. * ```
  15759. *
  15760. *
  15761. * @param {string} expression String expression to compile.
  15762. * @returns {function(context, locals)} a function which represents the compiled expression:
  15763. *
  15764. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15765. * are evaluated against (typically a scope object).
  15766. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15767. * `context`.
  15768. *
  15769. * The returned function also has the following properties:
  15770. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  15771. * literal.
  15772. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  15773. * constant literals.
  15774. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  15775. * set to a function to change its value on the given context.
  15776. *
  15777. */
  15778. /**
  15779. * @ngdoc provider
  15780. * @name $parseProvider
  15781. * @this
  15782. *
  15783. * @description
  15784. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  15785. * service.
  15786. */
  15787. function $ParseProvider() {
  15788. var cache = createMap();
  15789. var literals = {
  15790. 'true': true,
  15791. 'false': false,
  15792. 'null': null,
  15793. 'undefined': undefined
  15794. };
  15795. var identStart, identContinue;
  15796. /**
  15797. * @ngdoc method
  15798. * @name $parseProvider#addLiteral
  15799. * @description
  15800. *
  15801. * Configure $parse service to add literal values that will be present as literal at expressions.
  15802. *
  15803. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  15804. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  15805. *
  15806. **/
  15807. this.addLiteral = function(literalName, literalValue) {
  15808. literals[literalName] = literalValue;
  15809. };
  15810. /**
  15811. * @ngdoc method
  15812. * @name $parseProvider#setIdentifierFns
  15813. *
  15814. * @description
  15815. *
  15816. * Allows defining the set of characters that are allowed in AngularJS expressions. The function
  15817. * `identifierStart` will get called to know if a given character is a valid character to be the
  15818. * first character for an identifier. The function `identifierContinue` will get called to know if
  15819. * a given character is a valid character to be a follow-up identifier character. The functions
  15820. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  15821. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  15822. * mind that the `string` parameter can be two characters long depending on the character
  15823. * representation. It is expected for the function to return `true` or `false`, whether that
  15824. * character is allowed or not.
  15825. *
  15826. * Since this function will be called extensively, keep the implementation of these functions fast,
  15827. * as the performance of these functions have a direct impact on the expressions parsing speed.
  15828. *
  15829. * @param {function=} identifierStart The function that will decide whether the given character is
  15830. * a valid identifier start character.
  15831. * @param {function=} identifierContinue The function that will decide whether the given character is
  15832. * a valid identifier continue character.
  15833. */
  15834. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  15835. identStart = identifierStart;
  15836. identContinue = identifierContinue;
  15837. return this;
  15838. };
  15839. this.$get = ['$filter', function($filter) {
  15840. var noUnsafeEval = csp().noUnsafeEval;
  15841. var $parseOptions = {
  15842. csp: noUnsafeEval,
  15843. literals: copy(literals),
  15844. isIdentifierStart: isFunction(identStart) && identStart,
  15845. isIdentifierContinue: isFunction(identContinue) && identContinue
  15846. };
  15847. $parse.$$getAst = $$getAst;
  15848. return $parse;
  15849. function $parse(exp, interceptorFn) {
  15850. var parsedExpression, cacheKey;
  15851. switch (typeof exp) {
  15852. case 'string':
  15853. exp = exp.trim();
  15854. cacheKey = exp;
  15855. parsedExpression = cache[cacheKey];
  15856. if (!parsedExpression) {
  15857. var lexer = new Lexer($parseOptions);
  15858. var parser = new Parser(lexer, $filter, $parseOptions);
  15859. parsedExpression = parser.parse(exp);
  15860. cache[cacheKey] = addWatchDelegate(parsedExpression);
  15861. }
  15862. return addInterceptor(parsedExpression, interceptorFn);
  15863. case 'function':
  15864. return addInterceptor(exp, interceptorFn);
  15865. default:
  15866. return addInterceptor(noop, interceptorFn);
  15867. }
  15868. }
  15869. function $$getAst(exp) {
  15870. var lexer = new Lexer($parseOptions);
  15871. var parser = new Parser(lexer, $filter, $parseOptions);
  15872. return parser.getAst(exp).ast;
  15873. }
  15874. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  15875. if (newValue == null || oldValueOfValue == null) { // null/undefined
  15876. return newValue === oldValueOfValue;
  15877. }
  15878. if (typeof newValue === 'object') {
  15879. // attempt to convert the value to a primitive type
  15880. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  15881. // be cheaply dirty-checked
  15882. newValue = getValueOf(newValue);
  15883. if (typeof newValue === 'object' && !compareObjectIdentity) {
  15884. // objects/arrays are not supported - deep-watching them would be too expensive
  15885. return false;
  15886. }
  15887. // fall-through to the primitive equality check
  15888. }
  15889. //Primitive or NaN
  15890. // eslint-disable-next-line no-self-compare
  15891. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  15892. }
  15893. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15894. var inputExpressions = parsedExpression.inputs;
  15895. var lastResult;
  15896. if (inputExpressions.length === 1) {
  15897. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15898. inputExpressions = inputExpressions[0];
  15899. return scope.$watch(function expressionInputWatch(scope) {
  15900. var newInputValue = inputExpressions(scope);
  15901. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {
  15902. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  15903. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  15904. }
  15905. return lastResult;
  15906. }, listener, objectEquality, prettyPrintExpression);
  15907. }
  15908. var oldInputValueOfValues = [];
  15909. var oldInputValues = [];
  15910. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15911. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15912. oldInputValues[i] = null;
  15913. }
  15914. return scope.$watch(function expressionInputsWatch(scope) {
  15915. var changed = false;
  15916. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15917. var newInputValue = inputExpressions[i](scope);
  15918. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {
  15919. oldInputValues[i] = newInputValue;
  15920. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  15921. }
  15922. }
  15923. if (changed) {
  15924. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  15925. }
  15926. return lastResult;
  15927. }, listener, objectEquality, prettyPrintExpression);
  15928. }
  15929. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15930. var isDone = parsedExpression.literal ? isAllDefined : isDefined;
  15931. var unwatch, lastValue;
  15932. var exp = parsedExpression.$$intercepted || parsedExpression;
  15933. var post = parsedExpression.$$interceptor || identity;
  15934. var useInputs = parsedExpression.inputs && !exp.inputs;
  15935. // Propogate the literal/inputs/constant attributes
  15936. // ... but not oneTime since we are handling it
  15937. oneTimeWatch.literal = parsedExpression.literal;
  15938. oneTimeWatch.constant = parsedExpression.constant;
  15939. oneTimeWatch.inputs = parsedExpression.inputs;
  15940. // Allow other delegates to run on this wrapped expression
  15941. addWatchDelegate(oneTimeWatch);
  15942. unwatch = scope.$watch(oneTimeWatch, listener, objectEquality, prettyPrintExpression);
  15943. return unwatch;
  15944. function unwatchIfDone() {
  15945. if (isDone(lastValue)) {
  15946. unwatch();
  15947. }
  15948. }
  15949. function oneTimeWatch(scope, locals, assign, inputs) {
  15950. lastValue = useInputs && inputs ? inputs[0] : exp(scope, locals, assign, inputs);
  15951. if (isDone(lastValue)) {
  15952. scope.$$postDigest(unwatchIfDone);
  15953. }
  15954. return post(lastValue);
  15955. }
  15956. }
  15957. function isAllDefined(value) {
  15958. var allDefined = true;
  15959. forEach(value, function(val) {
  15960. if (!isDefined(val)) allDefined = false;
  15961. });
  15962. return allDefined;
  15963. }
  15964. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15965. var unwatch = scope.$watch(function constantWatch(scope) {
  15966. unwatch();
  15967. return parsedExpression(scope);
  15968. }, listener, objectEquality);
  15969. return unwatch;
  15970. }
  15971. function addWatchDelegate(parsedExpression) {
  15972. if (parsedExpression.constant) {
  15973. parsedExpression.$$watchDelegate = constantWatchDelegate;
  15974. } else if (parsedExpression.oneTime) {
  15975. parsedExpression.$$watchDelegate = oneTimeWatchDelegate;
  15976. } else if (parsedExpression.inputs) {
  15977. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  15978. }
  15979. return parsedExpression;
  15980. }
  15981. function chainInterceptors(first, second) {
  15982. function chainedInterceptor(value) {
  15983. return second(first(value));
  15984. }
  15985. chainedInterceptor.$stateful = first.$stateful || second.$stateful;
  15986. chainedInterceptor.$$pure = first.$$pure && second.$$pure;
  15987. return chainedInterceptor;
  15988. }
  15989. function addInterceptor(parsedExpression, interceptorFn) {
  15990. if (!interceptorFn) return parsedExpression;
  15991. // Extract any existing interceptors out of the parsedExpression
  15992. // to ensure the original parsedExpression is always the $$intercepted
  15993. if (parsedExpression.$$interceptor) {
  15994. interceptorFn = chainInterceptors(parsedExpression.$$interceptor, interceptorFn);
  15995. parsedExpression = parsedExpression.$$intercepted;
  15996. }
  15997. var useInputs = false;
  15998. var fn = function interceptedExpression(scope, locals, assign, inputs) {
  15999. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  16000. return interceptorFn(value);
  16001. };
  16002. // Maintain references to the interceptor/intercepted
  16003. fn.$$intercepted = parsedExpression;
  16004. fn.$$interceptor = interceptorFn;
  16005. // Propogate the literal/oneTime/constant attributes
  16006. fn.literal = parsedExpression.literal;
  16007. fn.oneTime = parsedExpression.oneTime;
  16008. fn.constant = parsedExpression.constant;
  16009. // Treat the interceptor like filters.
  16010. // If it is not $stateful then only watch its inputs.
  16011. // If the expression itself has no inputs then use the full expression as an input.
  16012. if (!interceptorFn.$stateful) {
  16013. useInputs = !parsedExpression.inputs;
  16014. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  16015. if (!interceptorFn.$$pure) {
  16016. fn.inputs = fn.inputs.map(function(e) {
  16017. // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a
  16018. // non-pure interceptor function.
  16019. if (e.isPure === PURITY_RELATIVE) {
  16020. return function depurifier(s) { return e(s); };
  16021. }
  16022. return e;
  16023. });
  16024. }
  16025. }
  16026. return addWatchDelegate(fn);
  16027. }
  16028. }];
  16029. }
  16030. /**
  16031. * @ngdoc service
  16032. * @name $q
  16033. * @requires $rootScope
  16034. *
  16035. * @description
  16036. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  16037. * when they are done processing.
  16038. *
  16039. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  16040. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  16041. *
  16042. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  16043. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  16044. *
  16045. * ## $q constructor
  16046. *
  16047. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  16048. * function as the first argument. This is similar to the native Promise implementation from ES6,
  16049. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  16050. *
  16051. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  16052. * available yet.
  16053. *
  16054. * It can be used like so:
  16055. *
  16056. * ```js
  16057. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  16058. * // are available in the current lexical scope (they could have been injected or passed in).
  16059. *
  16060. * function asyncGreet(name) {
  16061. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  16062. * return $q(function(resolve, reject) {
  16063. * setTimeout(function() {
  16064. * if (okToGreet(name)) {
  16065. * resolve('Hello, ' + name + '!');
  16066. * } else {
  16067. * reject('Greeting ' + name + ' is not allowed.');
  16068. * }
  16069. * }, 1000);
  16070. * });
  16071. * }
  16072. *
  16073. * var promise = asyncGreet('Robin Hood');
  16074. * promise.then(function(greeting) {
  16075. * alert('Success: ' + greeting);
  16076. * }, function(reason) {
  16077. * alert('Failed: ' + reason);
  16078. * });
  16079. * ```
  16080. *
  16081. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  16082. *
  16083. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  16084. *
  16085. * However, the more traditional CommonJS-style usage is still available, and documented below.
  16086. *
  16087. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  16088. * interface for interacting with an object that represents the result of an action that is
  16089. * performed asynchronously, and may or may not be finished at any given point in time.
  16090. *
  16091. * From the perspective of dealing with error handling, deferred and promise APIs are to
  16092. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  16093. *
  16094. * ```js
  16095. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  16096. * // are available in the current lexical scope (they could have been injected or passed in).
  16097. *
  16098. * function asyncGreet(name) {
  16099. * var deferred = $q.defer();
  16100. *
  16101. * setTimeout(function() {
  16102. * deferred.notify('About to greet ' + name + '.');
  16103. *
  16104. * if (okToGreet(name)) {
  16105. * deferred.resolve('Hello, ' + name + '!');
  16106. * } else {
  16107. * deferred.reject('Greeting ' + name + ' is not allowed.');
  16108. * }
  16109. * }, 1000);
  16110. *
  16111. * return deferred.promise;
  16112. * }
  16113. *
  16114. * var promise = asyncGreet('Robin Hood');
  16115. * promise.then(function(greeting) {
  16116. * alert('Success: ' + greeting);
  16117. * }, function(reason) {
  16118. * alert('Failed: ' + reason);
  16119. * }, function(update) {
  16120. * alert('Got notification: ' + update);
  16121. * });
  16122. * ```
  16123. *
  16124. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  16125. * comes in the way of guarantees that promise and deferred APIs make, see
  16126. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  16127. *
  16128. * Additionally the promise api allows for composition that is very hard to do with the
  16129. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  16130. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  16131. * section on serial or parallel joining of promises.
  16132. *
  16133. * ## The Deferred API
  16134. *
  16135. * A new instance of deferred is constructed by calling `$q.defer()`.
  16136. *
  16137. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  16138. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  16139. * of the task.
  16140. *
  16141. * **Methods**
  16142. *
  16143. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  16144. * constructed via `$q.reject`, the promise will be rejected instead.
  16145. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  16146. * resolving it with a rejection constructed via `$q.reject`.
  16147. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  16148. * multiple times before the promise is either resolved or rejected.
  16149. *
  16150. * **Properties**
  16151. *
  16152. * - promise – `{Promise}` – promise object associated with this deferred.
  16153. *
  16154. *
  16155. * ## The Promise API
  16156. *
  16157. * A new promise instance is created when a deferred instance is created and can be retrieved by
  16158. * calling `deferred.promise`.
  16159. *
  16160. * The purpose of the promise object is to allow for interested parties to get access to the result
  16161. * of the deferred task when it completes.
  16162. *
  16163. * **Methods**
  16164. *
  16165. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  16166. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  16167. * as soon as the result is available. The callbacks are called with a single argument: the result
  16168. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  16169. * provide a progress indication, before the promise is resolved or rejected.
  16170. *
  16171. * This method *returns a new promise* which is resolved or rejected via the return value of the
  16172. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  16173. * with the value which is resolved in that promise using
  16174. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  16175. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  16176. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  16177. * arguments are optional.
  16178. *
  16179. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  16180. *
  16181. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  16182. * but to do so without modifying the final value. This is useful to release resources or do some
  16183. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  16184. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  16185. * more information.
  16186. *
  16187. * ## Chaining promises
  16188. *
  16189. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  16190. * possible to create a chain of promises:
  16191. *
  16192. * ```js
  16193. * promiseB = promiseA.then(function(result) {
  16194. * return result + 1;
  16195. * });
  16196. *
  16197. * // promiseB will be resolved immediately after promiseA is resolved and its value
  16198. * // will be the result of promiseA incremented by 1
  16199. * ```
  16200. *
  16201. * It is possible to create chains of any length and since a promise can be resolved with another
  16202. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  16203. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  16204. * $http's response interceptors.
  16205. *
  16206. *
  16207. * ## Differences between Kris Kowal's Q and $q
  16208. *
  16209. * There are two main differences:
  16210. *
  16211. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  16212. * mechanism in AngularJS, which means faster propagation of resolution or rejection into your
  16213. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  16214. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  16215. * all the important functionality needed for common async tasks.
  16216. *
  16217. * ## Testing
  16218. *
  16219. * ```js
  16220. * it('should simulate promise', inject(function($q, $rootScope) {
  16221. * var deferred = $q.defer();
  16222. * var promise = deferred.promise;
  16223. * var resolvedValue;
  16224. *
  16225. * promise.then(function(value) { resolvedValue = value; });
  16226. * expect(resolvedValue).toBeUndefined();
  16227. *
  16228. * // Simulate resolving of promise
  16229. * deferred.resolve(123);
  16230. * // Note that the 'then' function does not get called synchronously.
  16231. * // This is because we want the promise API to always be async, whether or not
  16232. * // it got called synchronously or asynchronously.
  16233. * expect(resolvedValue).toBeUndefined();
  16234. *
  16235. * // Propagate promise resolution to 'then' functions using $apply().
  16236. * $rootScope.$apply();
  16237. * expect(resolvedValue).toEqual(123);
  16238. * }));
  16239. * ```
  16240. *
  16241. * @param {function(function, function)} resolver Function which is responsible for resolving or
  16242. * rejecting the newly created promise. The first parameter is a function which resolves the
  16243. * promise, the second parameter is a function which rejects the promise.
  16244. *
  16245. * @returns {Promise} The newly created promise.
  16246. */
  16247. /**
  16248. * @ngdoc provider
  16249. * @name $qProvider
  16250. * @this
  16251. *
  16252. * @description
  16253. */
  16254. function $QProvider() {
  16255. var errorOnUnhandledRejections = true;
  16256. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  16257. return qFactory(function(callback) {
  16258. $rootScope.$evalAsync(callback);
  16259. }, $exceptionHandler, errorOnUnhandledRejections);
  16260. }];
  16261. /**
  16262. * @ngdoc method
  16263. * @name $qProvider#errorOnUnhandledRejections
  16264. * @kind function
  16265. *
  16266. * @description
  16267. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  16268. * This feature is enabled by default.
  16269. *
  16270. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  16271. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  16272. * chaining otherwise.
  16273. */
  16274. this.errorOnUnhandledRejections = function(value) {
  16275. if (isDefined(value)) {
  16276. errorOnUnhandledRejections = value;
  16277. return this;
  16278. } else {
  16279. return errorOnUnhandledRejections;
  16280. }
  16281. };
  16282. }
  16283. /** @this */
  16284. function $$QProvider() {
  16285. var errorOnUnhandledRejections = true;
  16286. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  16287. return qFactory(function(callback) {
  16288. $browser.defer(callback);
  16289. }, $exceptionHandler, errorOnUnhandledRejections);
  16290. }];
  16291. this.errorOnUnhandledRejections = function(value) {
  16292. if (isDefined(value)) {
  16293. errorOnUnhandledRejections = value;
  16294. return this;
  16295. } else {
  16296. return errorOnUnhandledRejections;
  16297. }
  16298. };
  16299. }
  16300. /**
  16301. * Constructs a promise manager.
  16302. *
  16303. * @param {function(function)} nextTick Function for executing functions in the next turn.
  16304. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  16305. * debugging purposes.
  16306. * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled
  16307. * promises rejections.
  16308. * @returns {object} Promise manager.
  16309. */
  16310. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  16311. var $qMinErr = minErr('$q', TypeError);
  16312. var queueSize = 0;
  16313. var checkQueue = [];
  16314. /**
  16315. * @ngdoc method
  16316. * @name ng.$q#defer
  16317. * @kind function
  16318. *
  16319. * @description
  16320. * Creates a `Deferred` object which represents a task which will finish in the future.
  16321. *
  16322. * @returns {Deferred} Returns a new instance of deferred.
  16323. */
  16324. function defer() {
  16325. return new Deferred();
  16326. }
  16327. function Deferred() {
  16328. var promise = this.promise = new Promise();
  16329. //Non prototype methods necessary to support unbound execution :/
  16330. this.resolve = function(val) { resolvePromise(promise, val); };
  16331. this.reject = function(reason) { rejectPromise(promise, reason); };
  16332. this.notify = function(progress) { notifyPromise(promise, progress); };
  16333. }
  16334. function Promise() {
  16335. this.$$state = { status: 0 };
  16336. }
  16337. extend(Promise.prototype, {
  16338. then: function(onFulfilled, onRejected, progressBack) {
  16339. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  16340. return this;
  16341. }
  16342. var result = new Promise();
  16343. this.$$state.pending = this.$$state.pending || [];
  16344. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  16345. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  16346. return result;
  16347. },
  16348. 'catch': function(callback) {
  16349. return this.then(null, callback);
  16350. },
  16351. 'finally': function(callback, progressBack) {
  16352. return this.then(function(value) {
  16353. return handleCallback(value, resolve, callback);
  16354. }, function(error) {
  16355. return handleCallback(error, reject, callback);
  16356. }, progressBack);
  16357. }
  16358. });
  16359. function processQueue(state) {
  16360. var fn, promise, pending;
  16361. pending = state.pending;
  16362. state.processScheduled = false;
  16363. state.pending = undefined;
  16364. try {
  16365. for (var i = 0, ii = pending.length; i < ii; ++i) {
  16366. markQStateExceptionHandled(state);
  16367. promise = pending[i][0];
  16368. fn = pending[i][state.status];
  16369. try {
  16370. if (isFunction(fn)) {
  16371. resolvePromise(promise, fn(state.value));
  16372. } else if (state.status === 1) {
  16373. resolvePromise(promise, state.value);
  16374. } else {
  16375. rejectPromise(promise, state.value);
  16376. }
  16377. } catch (e) {
  16378. rejectPromise(promise, e);
  16379. // This error is explicitly marked for being passed to the $exceptionHandler
  16380. if (e && e.$$passToExceptionHandler === true) {
  16381. exceptionHandler(e);
  16382. }
  16383. }
  16384. }
  16385. } finally {
  16386. --queueSize;
  16387. if (errorOnUnhandledRejections && queueSize === 0) {
  16388. nextTick(processChecks);
  16389. }
  16390. }
  16391. }
  16392. function processChecks() {
  16393. // eslint-disable-next-line no-unmodified-loop-condition
  16394. while (!queueSize && checkQueue.length) {
  16395. var toCheck = checkQueue.shift();
  16396. if (!isStateExceptionHandled(toCheck)) {
  16397. markQStateExceptionHandled(toCheck);
  16398. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  16399. if (isError(toCheck.value)) {
  16400. exceptionHandler(toCheck.value, errorMessage);
  16401. } else {
  16402. exceptionHandler(errorMessage);
  16403. }
  16404. }
  16405. }
  16406. }
  16407. function scheduleProcessQueue(state) {
  16408. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {
  16409. if (queueSize === 0 && checkQueue.length === 0) {
  16410. nextTick(processChecks);
  16411. }
  16412. checkQueue.push(state);
  16413. }
  16414. if (state.processScheduled || !state.pending) return;
  16415. state.processScheduled = true;
  16416. ++queueSize;
  16417. nextTick(function() { processQueue(state); });
  16418. }
  16419. function resolvePromise(promise, val) {
  16420. if (promise.$$state.status) return;
  16421. if (val === promise) {
  16422. $$reject(promise, $qMinErr(
  16423. 'qcycle',
  16424. 'Expected promise to be resolved with value other than itself \'{0}\'',
  16425. val));
  16426. } else {
  16427. $$resolve(promise, val);
  16428. }
  16429. }
  16430. function $$resolve(promise, val) {
  16431. var then;
  16432. var done = false;
  16433. try {
  16434. if (isObject(val) || isFunction(val)) then = val.then;
  16435. if (isFunction(then)) {
  16436. promise.$$state.status = -1;
  16437. then.call(val, doResolve, doReject, doNotify);
  16438. } else {
  16439. promise.$$state.value = val;
  16440. promise.$$state.status = 1;
  16441. scheduleProcessQueue(promise.$$state);
  16442. }
  16443. } catch (e) {
  16444. doReject(e);
  16445. }
  16446. function doResolve(val) {
  16447. if (done) return;
  16448. done = true;
  16449. $$resolve(promise, val);
  16450. }
  16451. function doReject(val) {
  16452. if (done) return;
  16453. done = true;
  16454. $$reject(promise, val);
  16455. }
  16456. function doNotify(progress) {
  16457. notifyPromise(promise, progress);
  16458. }
  16459. }
  16460. function rejectPromise(promise, reason) {
  16461. if (promise.$$state.status) return;
  16462. $$reject(promise, reason);
  16463. }
  16464. function $$reject(promise, reason) {
  16465. promise.$$state.value = reason;
  16466. promise.$$state.status = 2;
  16467. scheduleProcessQueue(promise.$$state);
  16468. }
  16469. function notifyPromise(promise, progress) {
  16470. var callbacks = promise.$$state.pending;
  16471. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  16472. nextTick(function() {
  16473. var callback, result;
  16474. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  16475. result = callbacks[i][0];
  16476. callback = callbacks[i][3];
  16477. try {
  16478. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  16479. } catch (e) {
  16480. exceptionHandler(e);
  16481. }
  16482. }
  16483. });
  16484. }
  16485. }
  16486. /**
  16487. * @ngdoc method
  16488. * @name $q#reject
  16489. * @kind function
  16490. *
  16491. * @description
  16492. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  16493. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  16494. * a promise chain, you don't need to worry about it.
  16495. *
  16496. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  16497. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  16498. * a promise error callback and you want to forward the error to the promise derived from the
  16499. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  16500. * `reject`.
  16501. *
  16502. * ```js
  16503. * promiseB = promiseA.then(function(result) {
  16504. * // success: do something and resolve promiseB
  16505. * // with the old or a new result
  16506. * return result;
  16507. * }, function(reason) {
  16508. * // error: handle the error if possible and
  16509. * // resolve promiseB with newPromiseOrValue,
  16510. * // otherwise forward the rejection to promiseB
  16511. * if (canHandle(reason)) {
  16512. * // handle the error and recover
  16513. * return newPromiseOrValue;
  16514. * }
  16515. * return $q.reject(reason);
  16516. * });
  16517. * ```
  16518. *
  16519. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  16520. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  16521. */
  16522. function reject(reason) {
  16523. var result = new Promise();
  16524. rejectPromise(result, reason);
  16525. return result;
  16526. }
  16527. function handleCallback(value, resolver, callback) {
  16528. var callbackOutput = null;
  16529. try {
  16530. if (isFunction(callback)) callbackOutput = callback();
  16531. } catch (e) {
  16532. return reject(e);
  16533. }
  16534. if (isPromiseLike(callbackOutput)) {
  16535. return callbackOutput.then(function() {
  16536. return resolver(value);
  16537. }, reject);
  16538. } else {
  16539. return resolver(value);
  16540. }
  16541. }
  16542. /**
  16543. * @ngdoc method
  16544. * @name $q#when
  16545. * @kind function
  16546. *
  16547. * @description
  16548. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  16549. * This is useful when you are dealing with an object that might or might not be a promise, or if
  16550. * the promise comes from a source that can't be trusted.
  16551. *
  16552. * @param {*} value Value or a promise
  16553. * @param {Function=} successCallback
  16554. * @param {Function=} errorCallback
  16555. * @param {Function=} progressCallback
  16556. * @returns {Promise} Returns a promise of the passed value or promise
  16557. */
  16558. function when(value, callback, errback, progressBack) {
  16559. var result = new Promise();
  16560. resolvePromise(result, value);
  16561. return result.then(callback, errback, progressBack);
  16562. }
  16563. /**
  16564. * @ngdoc method
  16565. * @name $q#resolve
  16566. * @kind function
  16567. *
  16568. * @description
  16569. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  16570. *
  16571. * @param {*} value Value or a promise
  16572. * @param {Function=} successCallback
  16573. * @param {Function=} errorCallback
  16574. * @param {Function=} progressCallback
  16575. * @returns {Promise} Returns a promise of the passed value or promise
  16576. */
  16577. var resolve = when;
  16578. /**
  16579. * @ngdoc method
  16580. * @name $q#all
  16581. * @kind function
  16582. *
  16583. * @description
  16584. * Combines multiple promises into a single promise that is resolved when all of the input
  16585. * promises are resolved.
  16586. *
  16587. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  16588. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  16589. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  16590. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  16591. * with the same rejection value.
  16592. */
  16593. function all(promises) {
  16594. var result = new Promise(),
  16595. counter = 0,
  16596. results = isArray(promises) ? [] : {};
  16597. forEach(promises, function(promise, key) {
  16598. counter++;
  16599. when(promise).then(function(value) {
  16600. results[key] = value;
  16601. if (!(--counter)) resolvePromise(result, results);
  16602. }, function(reason) {
  16603. rejectPromise(result, reason);
  16604. });
  16605. });
  16606. if (counter === 0) {
  16607. resolvePromise(result, results);
  16608. }
  16609. return result;
  16610. }
  16611. /**
  16612. * @ngdoc method
  16613. * @name $q#race
  16614. * @kind function
  16615. *
  16616. * @description
  16617. * Returns a promise that resolves or rejects as soon as one of those promises
  16618. * resolves or rejects, with the value or reason from that promise.
  16619. *
  16620. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  16621. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  16622. * resolves or rejects, with the value or reason from that promise.
  16623. */
  16624. function race(promises) {
  16625. var deferred = defer();
  16626. forEach(promises, function(promise) {
  16627. when(promise).then(deferred.resolve, deferred.reject);
  16628. });
  16629. return deferred.promise;
  16630. }
  16631. function $Q(resolver) {
  16632. if (!isFunction(resolver)) {
  16633. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  16634. }
  16635. var promise = new Promise();
  16636. function resolveFn(value) {
  16637. resolvePromise(promise, value);
  16638. }
  16639. function rejectFn(reason) {
  16640. rejectPromise(promise, reason);
  16641. }
  16642. resolver(resolveFn, rejectFn);
  16643. return promise;
  16644. }
  16645. // Let's make the instanceof operator work for promises, so that
  16646. // `new $q(fn) instanceof $q` would evaluate to true.
  16647. $Q.prototype = Promise.prototype;
  16648. $Q.defer = defer;
  16649. $Q.reject = reject;
  16650. $Q.when = when;
  16651. $Q.resolve = resolve;
  16652. $Q.all = all;
  16653. $Q.race = race;
  16654. return $Q;
  16655. }
  16656. function isStateExceptionHandled(state) {
  16657. return !!state.pur;
  16658. }
  16659. function markQStateExceptionHandled(state) {
  16660. state.pur = true;
  16661. }
  16662. function markQExceptionHandled(q) {
  16663. // Built-in `$q` promises will always have a `$$state` property. This check is to allow
  16664. // overwriting `$q` with a different promise library (e.g. Bluebird + angular-bluebird-promises).
  16665. // (Currently, this is the only method that might be called with a promise, even if it is not
  16666. // created by the built-in `$q`.)
  16667. if (q.$$state) {
  16668. markQStateExceptionHandled(q.$$state);
  16669. }
  16670. }
  16671. /** @this */
  16672. function $$RAFProvider() { //rAF
  16673. this.$get = ['$window', '$timeout', function($window, $timeout) {
  16674. var requestAnimationFrame = $window.requestAnimationFrame ||
  16675. $window.webkitRequestAnimationFrame;
  16676. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  16677. $window.webkitCancelAnimationFrame ||
  16678. $window.webkitCancelRequestAnimationFrame;
  16679. var rafSupported = !!requestAnimationFrame;
  16680. var raf = rafSupported
  16681. ? function(fn) {
  16682. var id = requestAnimationFrame(fn);
  16683. return function() {
  16684. cancelAnimationFrame(id);
  16685. };
  16686. }
  16687. : function(fn) {
  16688. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  16689. return function() {
  16690. $timeout.cancel(timer);
  16691. };
  16692. };
  16693. raf.supported = rafSupported;
  16694. return raf;
  16695. }];
  16696. }
  16697. /**
  16698. * DESIGN NOTES
  16699. *
  16700. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  16701. *
  16702. * The typical use of scope is to watch the expressions, which most of the time return the same
  16703. * value as last time so we optimize the operation.
  16704. *
  16705. * Closures construction is expensive in terms of speed as well as memory:
  16706. * - No closures, instead use prototypical inheritance for API
  16707. * - Internal state needs to be stored on scope directly, which means that private state is
  16708. * exposed as $$____ properties
  16709. *
  16710. * Loop operations are optimized by using while(count--) { ... }
  16711. * - This means that in order to keep the same order of execution as addition we have to add
  16712. * items to the array at the beginning (unshift) instead of at the end (push)
  16713. *
  16714. * Child scopes are created and removed often
  16715. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  16716. *
  16717. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  16718. * in the same way as watch. Watch requires return of the initialization function which is expensive
  16719. * to construct.
  16720. */
  16721. /**
  16722. * @ngdoc provider
  16723. * @name $rootScopeProvider
  16724. * @description
  16725. *
  16726. * Provider for the $rootScope service.
  16727. */
  16728. /**
  16729. * @ngdoc method
  16730. * @name $rootScopeProvider#digestTtl
  16731. * @description
  16732. *
  16733. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  16734. * assuming that the model is unstable.
  16735. *
  16736. * The current default is 10 iterations.
  16737. *
  16738. * In complex applications it's possible that the dependencies between `$watch`s will result in
  16739. * several digest iterations. However if an application needs more than the default 10 digest
  16740. * iterations for its model to stabilize then you should investigate what is causing the model to
  16741. * continuously change during the digest.
  16742. *
  16743. * Increasing the TTL could have performance implications, so you should not change it without
  16744. * proper justification.
  16745. *
  16746. * @param {number} limit The number of digest iterations.
  16747. */
  16748. /**
  16749. * @ngdoc service
  16750. * @name $rootScope
  16751. * @this
  16752. *
  16753. * @description
  16754. *
  16755. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  16756. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  16757. * between the model and the view, via a mechanism for watching the model for changes.
  16758. * They also provide event emission/broadcast and subscription facility. See the
  16759. * {@link guide/scope developer guide on scopes}.
  16760. */
  16761. function $RootScopeProvider() {
  16762. var TTL = 10;
  16763. var $rootScopeMinErr = minErr('$rootScope');
  16764. var lastDirtyWatch = null;
  16765. var applyAsyncId = null;
  16766. this.digestTtl = function(value) {
  16767. if (arguments.length) {
  16768. TTL = value;
  16769. }
  16770. return TTL;
  16771. };
  16772. function createChildScopeClass(parent) {
  16773. function ChildScope() {
  16774. this.$$watchers = this.$$nextSibling =
  16775. this.$$childHead = this.$$childTail = null;
  16776. this.$$listeners = {};
  16777. this.$$listenerCount = {};
  16778. this.$$watchersCount = 0;
  16779. this.$id = nextUid();
  16780. this.$$ChildScope = null;
  16781. this.$$suspended = false;
  16782. }
  16783. ChildScope.prototype = parent;
  16784. return ChildScope;
  16785. }
  16786. this.$get = ['$exceptionHandler', '$parse', '$browser',
  16787. function($exceptionHandler, $parse, $browser) {
  16788. function destroyChildScope($event) {
  16789. $event.currentScope.$$destroyed = true;
  16790. }
  16791. function cleanUpScope($scope) {
  16792. // Support: IE 9 only
  16793. if (msie === 9) {
  16794. // There is a memory leak in IE9 if all child scopes are not disconnected
  16795. // completely when a scope is destroyed. So this code will recurse up through
  16796. // all this scopes children
  16797. //
  16798. // See issue https://github.com/angular/angular.js/issues/10706
  16799. if ($scope.$$childHead) {
  16800. cleanUpScope($scope.$$childHead);
  16801. }
  16802. if ($scope.$$nextSibling) {
  16803. cleanUpScope($scope.$$nextSibling);
  16804. }
  16805. }
  16806. // The code below works around IE9 and V8's memory leaks
  16807. //
  16808. // See:
  16809. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  16810. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  16811. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  16812. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  16813. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  16814. }
  16815. /**
  16816. * @ngdoc type
  16817. * @name $rootScope.Scope
  16818. *
  16819. * @description
  16820. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  16821. * {@link auto.$injector $injector}. Child scopes are created using the
  16822. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  16823. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  16824. * an in-depth introduction and usage examples.
  16825. *
  16826. *
  16827. * ## Inheritance
  16828. * A scope can inherit from a parent scope, as in this example:
  16829. * ```js
  16830. var parent = $rootScope;
  16831. var child = parent.$new();
  16832. parent.salutation = "Hello";
  16833. expect(child.salutation).toEqual('Hello');
  16834. child.salutation = "Welcome";
  16835. expect(child.salutation).toEqual('Welcome');
  16836. expect(parent.salutation).toEqual('Hello');
  16837. * ```
  16838. *
  16839. * When interacting with `Scope` in tests, additional helper methods are available on the
  16840. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  16841. * details.
  16842. *
  16843. *
  16844. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  16845. * provided for the current scope. Defaults to {@link ng}.
  16846. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  16847. * append/override services provided by `providers`. This is handy
  16848. * when unit-testing and having the need to override a default
  16849. * service.
  16850. * @returns {Object} Newly created scope.
  16851. *
  16852. */
  16853. function Scope() {
  16854. this.$id = nextUid();
  16855. this.$$phase = this.$parent = this.$$watchers =
  16856. this.$$nextSibling = this.$$prevSibling =
  16857. this.$$childHead = this.$$childTail = null;
  16858. this.$root = this;
  16859. this.$$destroyed = false;
  16860. this.$$suspended = false;
  16861. this.$$listeners = {};
  16862. this.$$listenerCount = {};
  16863. this.$$watchersCount = 0;
  16864. this.$$isolateBindings = null;
  16865. }
  16866. /**
  16867. * @ngdoc property
  16868. * @name $rootScope.Scope#$id
  16869. *
  16870. * @description
  16871. * Unique scope ID (monotonically increasing) useful for debugging.
  16872. */
  16873. /**
  16874. * @ngdoc property
  16875. * @name $rootScope.Scope#$parent
  16876. *
  16877. * @description
  16878. * Reference to the parent scope.
  16879. */
  16880. /**
  16881. * @ngdoc property
  16882. * @name $rootScope.Scope#$root
  16883. *
  16884. * @description
  16885. * Reference to the root scope.
  16886. */
  16887. Scope.prototype = {
  16888. constructor: Scope,
  16889. /**
  16890. * @ngdoc method
  16891. * @name $rootScope.Scope#$new
  16892. * @kind function
  16893. *
  16894. * @description
  16895. * Creates a new child {@link ng.$rootScope.Scope scope}.
  16896. *
  16897. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  16898. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  16899. *
  16900. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  16901. * desired for the scope and its child scopes to be permanently detached from the parent and
  16902. * thus stop participating in model change detection and listener notification by invoking.
  16903. *
  16904. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  16905. * parent scope. The scope is isolated, as it can not see parent scope properties.
  16906. * When creating widgets, it is useful for the widget to not accidentally read parent
  16907. * state.
  16908. *
  16909. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  16910. * of the newly created scope. Defaults to `this` scope if not provided.
  16911. * This is used when creating a transclude scope to correctly place it
  16912. * in the scope hierarchy while maintaining the correct prototypical
  16913. * inheritance.
  16914. *
  16915. * @returns {Object} The newly created child scope.
  16916. *
  16917. */
  16918. $new: function(isolate, parent) {
  16919. var child;
  16920. parent = parent || this;
  16921. if (isolate) {
  16922. child = new Scope();
  16923. child.$root = this.$root;
  16924. } else {
  16925. // Only create a child scope class if somebody asks for one,
  16926. // but cache it to allow the VM to optimize lookups.
  16927. if (!this.$$ChildScope) {
  16928. this.$$ChildScope = createChildScopeClass(this);
  16929. }
  16930. child = new this.$$ChildScope();
  16931. }
  16932. child.$parent = parent;
  16933. child.$$prevSibling = parent.$$childTail;
  16934. if (parent.$$childHead) {
  16935. parent.$$childTail.$$nextSibling = child;
  16936. parent.$$childTail = child;
  16937. } else {
  16938. parent.$$childHead = parent.$$childTail = child;
  16939. }
  16940. // When the new scope is not isolated or we inherit from `this`, and
  16941. // the parent scope is destroyed, the property `$$destroyed` is inherited
  16942. // prototypically. In all other cases, this property needs to be set
  16943. // when the parent scope is destroyed.
  16944. // The listener needs to be added after the parent is set
  16945. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  16946. return child;
  16947. },
  16948. /**
  16949. * @ngdoc method
  16950. * @name $rootScope.Scope#$watch
  16951. * @kind function
  16952. *
  16953. * @description
  16954. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  16955. *
  16956. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  16957. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  16958. * its value when executed multiple times with the same input because it may be executed multiple
  16959. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  16960. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  16961. * - The `listener` is called only when the value from the current `watchExpression` and the
  16962. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  16963. * see below). Inequality is determined according to reference inequality,
  16964. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  16965. * via the `!==` Javascript operator, unless `objectEquality == true`
  16966. * (see next point)
  16967. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  16968. * according to the {@link angular.equals} function. To save the value of the object for
  16969. * later comparison, the {@link angular.copy} function is used. This therefore means that
  16970. * watching complex objects will have adverse memory and performance implications.
  16971. * - This should not be used to watch for changes in objects that are (or contain)
  16972. * [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  16973. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  16974. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  16975. * iteration limit is 10 to prevent an infinite loop deadlock.
  16976. *
  16977. *
  16978. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  16979. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  16980. * multiple calls to your `watchExpression` because it will execute multiple times in a
  16981. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  16982. *
  16983. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  16984. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  16985. * watcher. In rare cases, this is undesirable because the listener is called when the result
  16986. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  16987. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  16988. * listener was called due to initialization.
  16989. *
  16990. *
  16991. *
  16992. * @example
  16993. * ```js
  16994. // let's assume that scope was dependency injected as the $rootScope
  16995. var scope = $rootScope;
  16996. scope.name = 'misko';
  16997. scope.counter = 0;
  16998. expect(scope.counter).toEqual(0);
  16999. scope.$watch('name', function(newValue, oldValue) {
  17000. scope.counter = scope.counter + 1;
  17001. });
  17002. expect(scope.counter).toEqual(0);
  17003. scope.$digest();
  17004. // the listener is always called during the first $digest loop after it was registered
  17005. expect(scope.counter).toEqual(1);
  17006. scope.$digest();
  17007. // but now it will not be called unless the value changes
  17008. expect(scope.counter).toEqual(1);
  17009. scope.name = 'adam';
  17010. scope.$digest();
  17011. expect(scope.counter).toEqual(2);
  17012. // Using a function as a watchExpression
  17013. var food;
  17014. scope.foodCounter = 0;
  17015. expect(scope.foodCounter).toEqual(0);
  17016. scope.$watch(
  17017. // This function returns the value being watched. It is called for each turn of the $digest loop
  17018. function() { return food; },
  17019. // This is the change listener, called when the value returned from the above function changes
  17020. function(newValue, oldValue) {
  17021. if ( newValue !== oldValue ) {
  17022. // Only increment the counter if the value changed
  17023. scope.foodCounter = scope.foodCounter + 1;
  17024. }
  17025. }
  17026. );
  17027. // No digest has been run so the counter will be zero
  17028. expect(scope.foodCounter).toEqual(0);
  17029. // Run the digest but since food has not changed count will still be zero
  17030. scope.$digest();
  17031. expect(scope.foodCounter).toEqual(0);
  17032. // Update food and run digest. Now the counter will increment
  17033. food = 'cheeseburger';
  17034. scope.$digest();
  17035. expect(scope.foodCounter).toEqual(1);
  17036. * ```
  17037. *
  17038. *
  17039. *
  17040. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  17041. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  17042. * a call to the `listener`.
  17043. *
  17044. * - `string`: Evaluated as {@link guide/expression expression}
  17045. * - `function(scope)`: called with current `scope` as a parameter.
  17046. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  17047. * of `watchExpression` changes.
  17048. *
  17049. * - `newVal` contains the current value of the `watchExpression`
  17050. * - `oldVal` contains the previous value of the `watchExpression`
  17051. * - `scope` refers to the current scope
  17052. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  17053. * comparing for reference equality.
  17054. * @returns {function()} Returns a deregistration function for this listener.
  17055. */
  17056. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  17057. var get = $parse(watchExp);
  17058. var fn = isFunction(listener) ? listener : noop;
  17059. if (get.$$watchDelegate) {
  17060. return get.$$watchDelegate(this, fn, objectEquality, get, watchExp);
  17061. }
  17062. var scope = this,
  17063. array = scope.$$watchers,
  17064. watcher = {
  17065. fn: fn,
  17066. last: initWatchVal,
  17067. get: get,
  17068. exp: prettyPrintExpression || watchExp,
  17069. eq: !!objectEquality
  17070. };
  17071. lastDirtyWatch = null;
  17072. if (!array) {
  17073. array = scope.$$watchers = [];
  17074. array.$$digestWatchIndex = -1;
  17075. }
  17076. // we use unshift since we use a while loop in $digest for speed.
  17077. // the while loop reads in reverse order.
  17078. array.unshift(watcher);
  17079. array.$$digestWatchIndex++;
  17080. incrementWatchersCount(this, 1);
  17081. return function deregisterWatch() {
  17082. var index = arrayRemove(array, watcher);
  17083. if (index >= 0) {
  17084. incrementWatchersCount(scope, -1);
  17085. if (index < array.$$digestWatchIndex) {
  17086. array.$$digestWatchIndex--;
  17087. }
  17088. }
  17089. lastDirtyWatch = null;
  17090. };
  17091. },
  17092. /**
  17093. * @ngdoc method
  17094. * @name $rootScope.Scope#$watchGroup
  17095. * @kind function
  17096. *
  17097. * @description
  17098. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  17099. * If any one expression in the collection changes the `listener` is executed.
  17100. *
  17101. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  17102. * values are examined for changes on every call to `$digest`.
  17103. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  17104. *
  17105. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  17106. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  17107. *
  17108. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  17109. * expression in `watchExpressions` changes
  17110. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  17111. * those of `watchExpression`
  17112. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  17113. * those of `watchExpression`
  17114. * The `scope` refers to the current scope.
  17115. * @returns {function()} Returns a de-registration function for all listeners.
  17116. */
  17117. $watchGroup: function(watchExpressions, listener) {
  17118. var oldValues = new Array(watchExpressions.length);
  17119. var newValues = new Array(watchExpressions.length);
  17120. var deregisterFns = [];
  17121. var self = this;
  17122. var changeReactionScheduled = false;
  17123. var firstRun = true;
  17124. if (!watchExpressions.length) {
  17125. // No expressions means we call the listener ASAP
  17126. var shouldCall = true;
  17127. self.$evalAsync(function() {
  17128. if (shouldCall) listener(newValues, newValues, self);
  17129. });
  17130. return function deregisterWatchGroup() {
  17131. shouldCall = false;
  17132. };
  17133. }
  17134. if (watchExpressions.length === 1) {
  17135. // Special case size of one
  17136. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  17137. newValues[0] = value;
  17138. oldValues[0] = oldValue;
  17139. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  17140. });
  17141. }
  17142. forEach(watchExpressions, function(expr, i) {
  17143. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value) {
  17144. newValues[i] = value;
  17145. if (!changeReactionScheduled) {
  17146. changeReactionScheduled = true;
  17147. self.$evalAsync(watchGroupAction);
  17148. }
  17149. });
  17150. deregisterFns.push(unwatchFn);
  17151. });
  17152. function watchGroupAction() {
  17153. changeReactionScheduled = false;
  17154. try {
  17155. if (firstRun) {
  17156. firstRun = false;
  17157. listener(newValues, newValues, self);
  17158. } else {
  17159. listener(newValues, oldValues, self);
  17160. }
  17161. } finally {
  17162. for (var i = 0; i < watchExpressions.length; i++) {
  17163. oldValues[i] = newValues[i];
  17164. }
  17165. }
  17166. }
  17167. return function deregisterWatchGroup() {
  17168. while (deregisterFns.length) {
  17169. deregisterFns.shift()();
  17170. }
  17171. };
  17172. },
  17173. /**
  17174. * @ngdoc method
  17175. * @name $rootScope.Scope#$watchCollection
  17176. * @kind function
  17177. *
  17178. * @description
  17179. * Shallow watches the properties of an object and fires whenever any of the properties change
  17180. * (for arrays, this implies watching the array items; for object maps, this implies watching
  17181. * the properties). If a change is detected, the `listener` callback is fired.
  17182. *
  17183. * - The `obj` collection is observed via standard $watch operation and is examined on every
  17184. * call to $digest() to see if any items have been added, removed, or moved.
  17185. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  17186. * adding, removing, and moving items belonging to an object or array.
  17187. *
  17188. *
  17189. * @example
  17190. * ```js
  17191. $scope.names = ['igor', 'matias', 'misko', 'james'];
  17192. $scope.dataCount = 4;
  17193. $scope.$watchCollection('names', function(newNames, oldNames) {
  17194. $scope.dataCount = newNames.length;
  17195. });
  17196. expect($scope.dataCount).toEqual(4);
  17197. $scope.$digest();
  17198. //still at 4 ... no changes
  17199. expect($scope.dataCount).toEqual(4);
  17200. $scope.names.pop();
  17201. $scope.$digest();
  17202. //now there's been a change
  17203. expect($scope.dataCount).toEqual(3);
  17204. * ```
  17205. *
  17206. *
  17207. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  17208. * expression value should evaluate to an object or an array which is observed on each
  17209. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  17210. * collection will trigger a call to the `listener`.
  17211. *
  17212. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  17213. * when a change is detected.
  17214. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  17215. * - The `oldCollection` object is a copy of the former collection data.
  17216. * Due to performance considerations, the`oldCollection` value is computed only if the
  17217. * `listener` function declares two or more arguments.
  17218. * - The `scope` argument refers to the current scope.
  17219. *
  17220. * @returns {function()} Returns a de-registration function for this listener. When the
  17221. * de-registration function is executed, the internal watch operation is terminated.
  17222. */
  17223. $watchCollection: function(obj, listener) {
  17224. // Mark the interceptor as
  17225. // ... $$pure when literal since the instance will change when any input changes
  17226. $watchCollectionInterceptor.$$pure = $parse(obj).literal;
  17227. // ... $stateful when non-literal since we must read the state of the collection
  17228. $watchCollectionInterceptor.$stateful = !$watchCollectionInterceptor.$$pure;
  17229. var self = this;
  17230. // the current value, updated on each dirty-check run
  17231. var newValue;
  17232. // a shallow copy of the newValue from the last dirty-check run,
  17233. // updated to match newValue during dirty-check run
  17234. var oldValue;
  17235. // a shallow copy of the newValue from when the last change happened
  17236. var veryOldValue;
  17237. // only track veryOldValue if the listener is asking for it
  17238. var trackVeryOldValue = (listener.length > 1);
  17239. var changeDetected = 0;
  17240. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  17241. var internalArray = [];
  17242. var internalObject = {};
  17243. var initRun = true;
  17244. var oldLength = 0;
  17245. function $watchCollectionInterceptor(_value) {
  17246. newValue = _value;
  17247. var newLength, key, bothNaN, newItem, oldItem;
  17248. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  17249. if (isUndefined(newValue)) return;
  17250. if (!isObject(newValue)) { // if primitive
  17251. if (oldValue !== newValue) {
  17252. oldValue = newValue;
  17253. changeDetected++;
  17254. }
  17255. } else if (isArrayLike(newValue)) {
  17256. if (oldValue !== internalArray) {
  17257. // we are transitioning from something which was not an array into array.
  17258. oldValue = internalArray;
  17259. oldLength = oldValue.length = 0;
  17260. changeDetected++;
  17261. }
  17262. newLength = newValue.length;
  17263. if (oldLength !== newLength) {
  17264. // if lengths do not match we need to trigger change notification
  17265. changeDetected++;
  17266. oldValue.length = oldLength = newLength;
  17267. }
  17268. // copy the items to oldValue and look for changes.
  17269. for (var i = 0; i < newLength; i++) {
  17270. oldItem = oldValue[i];
  17271. newItem = newValue[i];
  17272. // eslint-disable-next-line no-self-compare
  17273. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  17274. if (!bothNaN && (oldItem !== newItem)) {
  17275. changeDetected++;
  17276. oldValue[i] = newItem;
  17277. }
  17278. }
  17279. } else {
  17280. if (oldValue !== internalObject) {
  17281. // we are transitioning from something which was not an object into object.
  17282. oldValue = internalObject = {};
  17283. oldLength = 0;
  17284. changeDetected++;
  17285. }
  17286. // copy the items to oldValue and look for changes.
  17287. newLength = 0;
  17288. for (key in newValue) {
  17289. if (hasOwnProperty.call(newValue, key)) {
  17290. newLength++;
  17291. newItem = newValue[key];
  17292. oldItem = oldValue[key];
  17293. if (key in oldValue) {
  17294. // eslint-disable-next-line no-self-compare
  17295. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  17296. if (!bothNaN && (oldItem !== newItem)) {
  17297. changeDetected++;
  17298. oldValue[key] = newItem;
  17299. }
  17300. } else {
  17301. oldLength++;
  17302. oldValue[key] = newItem;
  17303. changeDetected++;
  17304. }
  17305. }
  17306. }
  17307. if (oldLength > newLength) {
  17308. // we used to have more keys, need to find them and destroy them.
  17309. changeDetected++;
  17310. for (key in oldValue) {
  17311. if (!hasOwnProperty.call(newValue, key)) {
  17312. oldLength--;
  17313. delete oldValue[key];
  17314. }
  17315. }
  17316. }
  17317. }
  17318. return changeDetected;
  17319. }
  17320. function $watchCollectionAction() {
  17321. if (initRun) {
  17322. initRun = false;
  17323. listener(newValue, newValue, self);
  17324. } else {
  17325. listener(newValue, veryOldValue, self);
  17326. }
  17327. // make a copy for the next time a collection is changed
  17328. if (trackVeryOldValue) {
  17329. if (!isObject(newValue)) {
  17330. //primitive
  17331. veryOldValue = newValue;
  17332. } else if (isArrayLike(newValue)) {
  17333. veryOldValue = new Array(newValue.length);
  17334. for (var i = 0; i < newValue.length; i++) {
  17335. veryOldValue[i] = newValue[i];
  17336. }
  17337. } else { // if object
  17338. veryOldValue = {};
  17339. for (var key in newValue) {
  17340. if (hasOwnProperty.call(newValue, key)) {
  17341. veryOldValue[key] = newValue[key];
  17342. }
  17343. }
  17344. }
  17345. }
  17346. }
  17347. return this.$watch(changeDetector, $watchCollectionAction);
  17348. },
  17349. /**
  17350. * @ngdoc method
  17351. * @name $rootScope.Scope#$digest
  17352. * @kind function
  17353. *
  17354. * @description
  17355. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  17356. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  17357. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  17358. * until no more listeners are firing. This means that it is possible to get into an infinite
  17359. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  17360. * iterations exceeds 10.
  17361. *
  17362. * Usually, you don't call `$digest()` directly in
  17363. * {@link ng.directive:ngController controllers} or in
  17364. * {@link ng.$compileProvider#directive directives}.
  17365. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  17366. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  17367. *
  17368. * If you want to be notified whenever `$digest()` is called,
  17369. * you can register a `watchExpression` function with
  17370. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  17371. *
  17372. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  17373. *
  17374. * @example
  17375. * ```js
  17376. var scope = ...;
  17377. scope.name = 'misko';
  17378. scope.counter = 0;
  17379. expect(scope.counter).toEqual(0);
  17380. scope.$watch('name', function(newValue, oldValue) {
  17381. scope.counter = scope.counter + 1;
  17382. });
  17383. expect(scope.counter).toEqual(0);
  17384. scope.$digest();
  17385. // the listener is always called during the first $digest loop after it was registered
  17386. expect(scope.counter).toEqual(1);
  17387. scope.$digest();
  17388. // but now it will not be called unless the value changes
  17389. expect(scope.counter).toEqual(1);
  17390. scope.name = 'adam';
  17391. scope.$digest();
  17392. expect(scope.counter).toEqual(2);
  17393. * ```
  17394. *
  17395. */
  17396. $digest: function() {
  17397. var watch, value, last, fn, get,
  17398. watchers,
  17399. dirty, ttl = TTL,
  17400. next, current, target = asyncQueue.length ? $rootScope : this,
  17401. watchLog = [],
  17402. logIdx, asyncTask;
  17403. beginPhase('$digest');
  17404. // Check for changes to browser url that happened in sync before the call to $digest
  17405. $browser.$$checkUrlChange();
  17406. if (this === $rootScope && applyAsyncId !== null) {
  17407. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  17408. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  17409. $browser.defer.cancel(applyAsyncId);
  17410. flushApplyAsync();
  17411. }
  17412. lastDirtyWatch = null;
  17413. do { // "while dirty" loop
  17414. dirty = false;
  17415. current = target;
  17416. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  17417. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  17418. // lead to a '$digest already in progress' error.
  17419. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  17420. try {
  17421. asyncTask = asyncQueue[asyncQueuePosition];
  17422. fn = asyncTask.fn;
  17423. fn(asyncTask.scope, asyncTask.locals);
  17424. } catch (e) {
  17425. $exceptionHandler(e);
  17426. }
  17427. lastDirtyWatch = null;
  17428. }
  17429. asyncQueue.length = 0;
  17430. traverseScopesLoop:
  17431. do { // "traverse the scopes" loop
  17432. if ((watchers = !current.$$suspended && current.$$watchers)) {
  17433. // process our watches
  17434. watchers.$$digestWatchIndex = watchers.length;
  17435. while (watchers.$$digestWatchIndex--) {
  17436. try {
  17437. watch = watchers[watchers.$$digestWatchIndex];
  17438. // Most common watches are on primitives, in which case we can short
  17439. // circuit it with === operator, only when === fails do we use .equals
  17440. if (watch) {
  17441. get = watch.get;
  17442. if ((value = get(current)) !== (last = watch.last) &&
  17443. !(watch.eq
  17444. ? equals(value, last)
  17445. : (isNumberNaN(value) && isNumberNaN(last)))) {
  17446. dirty = true;
  17447. lastDirtyWatch = watch;
  17448. watch.last = watch.eq ? copy(value, null) : value;
  17449. fn = watch.fn;
  17450. fn(value, ((last === initWatchVal) ? value : last), current);
  17451. if (ttl < 5) {
  17452. logIdx = 4 - ttl;
  17453. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  17454. watchLog[logIdx].push({
  17455. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  17456. newVal: value,
  17457. oldVal: last
  17458. });
  17459. }
  17460. } else if (watch === lastDirtyWatch) {
  17461. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  17462. // have already been tested.
  17463. dirty = false;
  17464. break traverseScopesLoop;
  17465. }
  17466. }
  17467. } catch (e) {
  17468. $exceptionHandler(e);
  17469. }
  17470. }
  17471. }
  17472. // Insanity Warning: scope depth-first traversal
  17473. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17474. // this piece should be kept in sync with the traversal in $broadcast
  17475. // (though it differs due to having the extra check for $$suspended and does not
  17476. // check $$listenerCount)
  17477. if (!(next = ((!current.$$suspended && current.$$watchersCount && current.$$childHead) ||
  17478. (current !== target && current.$$nextSibling)))) {
  17479. while (current !== target && !(next = current.$$nextSibling)) {
  17480. current = current.$parent;
  17481. }
  17482. }
  17483. } while ((current = next));
  17484. // `break traverseScopesLoop;` takes us to here
  17485. if ((dirty || asyncQueue.length) && !(ttl--)) {
  17486. clearPhase();
  17487. throw $rootScopeMinErr('infdig',
  17488. '{0} $digest() iterations reached. Aborting!\n' +
  17489. 'Watchers fired in the last 5 iterations: {1}',
  17490. TTL, watchLog);
  17491. }
  17492. } while (dirty || asyncQueue.length);
  17493. clearPhase();
  17494. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  17495. while (postDigestQueuePosition < postDigestQueue.length) {
  17496. try {
  17497. postDigestQueue[postDigestQueuePosition++]();
  17498. } catch (e) {
  17499. $exceptionHandler(e);
  17500. }
  17501. }
  17502. postDigestQueue.length = postDigestQueuePosition = 0;
  17503. // Check for changes to browser url that happened during the $digest
  17504. // (for which no event is fired; e.g. via `history.pushState()`)
  17505. $browser.$$checkUrlChange();
  17506. },
  17507. /**
  17508. * @ngdoc method
  17509. * @name $rootScope.Scope#$suspend
  17510. * @kind function
  17511. *
  17512. * @description
  17513. * Suspend watchers of this scope subtree so that they will not be invoked during digest.
  17514. *
  17515. * This can be used to optimize your application when you know that running those watchers
  17516. * is redundant.
  17517. *
  17518. * **Warning**
  17519. *
  17520. * Suspending scopes from the digest cycle can have unwanted and difficult to debug results.
  17521. * Only use this approach if you are confident that you know what you are doing and have
  17522. * ample tests to ensure that bindings get updated as you expect.
  17523. *
  17524. * Some of the things to consider are:
  17525. *
  17526. * * Any external event on a directive/component will not trigger a digest while the hosting
  17527. * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`.
  17528. * * Transcluded content exists on a scope that inherits from outside a directive but exists
  17529. * as a child of the directive's containing scope. If the containing scope is suspended the
  17530. * transcluded scope will also be suspended, even if the scope from which the transcluded
  17531. * scope inherits is not suspended.
  17532. * * Multiple directives trying to manage the suspended status of a scope can confuse each other:
  17533. * * A call to `$suspend()` on an already suspended scope is a no-op.
  17534. * * A call to `$resume()` on a non-suspended scope is a no-op.
  17535. * * If two directives suspend a scope, then one of them resumes the scope, the scope will no
  17536. * longer be suspended. This could result in the other directive believing a scope to be
  17537. * suspended when it is not.
  17538. * * If a parent scope is suspended then all its descendants will be also excluded from future
  17539. * digests whether or not they have been suspended themselves. Note that this also applies to
  17540. * isolate child scopes.
  17541. * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers
  17542. * for that scope and its descendants. When digesting we only check whether the current scope is
  17543. * locally suspended, rather than checking whether it has a suspended ancestor.
  17544. * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be
  17545. * included in future digests until all its ancestors have been resumed.
  17546. * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()`
  17547. * against the `$rootScope` and so will still trigger a global digest even if the promise was
  17548. * initiated by a component that lives on a suspended scope.
  17549. */
  17550. $suspend: function() {
  17551. this.$$suspended = true;
  17552. },
  17553. /**
  17554. * @ngdoc method
  17555. * @name $rootScope.Scope#$isSuspended
  17556. * @kind function
  17557. *
  17558. * @description
  17559. * Call this method to determine if this scope has been explicitly suspended. It will not
  17560. * tell you whether an ancestor has been suspended.
  17561. * To determine if this scope will be excluded from a digest triggered at the $rootScope,
  17562. * for example, you must check all its ancestors:
  17563. *
  17564. * ```
  17565. * function isExcludedFromDigest(scope) {
  17566. * while(scope) {
  17567. * if (scope.$isSuspended()) return true;
  17568. * scope = scope.$parent;
  17569. * }
  17570. * return false;
  17571. * ```
  17572. *
  17573. * Be aware that a scope may not be included in digests if it has a suspended ancestor,
  17574. * even if `$isSuspended()` returns false.
  17575. *
  17576. * @returns true if the current scope has been suspended.
  17577. */
  17578. $isSuspended: function() {
  17579. return this.$$suspended;
  17580. },
  17581. /**
  17582. * @ngdoc method
  17583. * @name $rootScope.Scope#$resume
  17584. * @kind function
  17585. *
  17586. * @description
  17587. * Resume watchers of this scope subtree in case it was suspended.
  17588. *
  17589. * See {@link $rootScope.Scope#$suspend} for information about the dangers of using this approach.
  17590. */
  17591. $resume: function() {
  17592. this.$$suspended = false;
  17593. },
  17594. /**
  17595. * @ngdoc event
  17596. * @name $rootScope.Scope#$destroy
  17597. * @eventType broadcast on scope being destroyed
  17598. *
  17599. * @description
  17600. * Broadcasted when a scope and its children are being destroyed.
  17601. *
  17602. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  17603. * clean up DOM bindings before an element is removed from the DOM.
  17604. */
  17605. /**
  17606. * @ngdoc method
  17607. * @name $rootScope.Scope#$destroy
  17608. * @kind function
  17609. *
  17610. * @description
  17611. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  17612. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  17613. * propagate to the current scope and its children. Removal also implies that the current
  17614. * scope is eligible for garbage collection.
  17615. *
  17616. * The `$destroy()` is usually used by directives such as
  17617. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  17618. * unrolling of the loop.
  17619. *
  17620. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  17621. * Application code can register a `$destroy` event handler that will give it a chance to
  17622. * perform any necessary cleanup.
  17623. *
  17624. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  17625. * clean up DOM bindings before an element is removed from the DOM.
  17626. */
  17627. $destroy: function() {
  17628. // We can't destroy a scope that has been already destroyed.
  17629. if (this.$$destroyed) return;
  17630. var parent = this.$parent;
  17631. this.$broadcast('$destroy');
  17632. this.$$destroyed = true;
  17633. if (this === $rootScope) {
  17634. //Remove handlers attached to window when $rootScope is removed
  17635. $browser.$$applicationDestroyed();
  17636. }
  17637. incrementWatchersCount(this, -this.$$watchersCount);
  17638. for (var eventName in this.$$listenerCount) {
  17639. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  17640. }
  17641. // sever all the references to parent scopes (after this cleanup, the current scope should
  17642. // not be retained by any of our references and should be eligible for garbage collection)
  17643. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  17644. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  17645. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  17646. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  17647. // Disable listeners, watchers and apply/digest methods
  17648. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  17649. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  17650. this.$$listeners = {};
  17651. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  17652. this.$$nextSibling = null;
  17653. cleanUpScope(this);
  17654. },
  17655. /**
  17656. * @ngdoc method
  17657. * @name $rootScope.Scope#$eval
  17658. * @kind function
  17659. *
  17660. * @description
  17661. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  17662. * the expression are propagated (uncaught). This is useful when evaluating AngularJS
  17663. * expressions.
  17664. *
  17665. * @example
  17666. * ```js
  17667. var scope = ng.$rootScope.Scope();
  17668. scope.a = 1;
  17669. scope.b = 2;
  17670. expect(scope.$eval('a+b')).toEqual(3);
  17671. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  17672. * ```
  17673. *
  17674. * @param {(string|function())=} expression An AngularJS expression to be executed.
  17675. *
  17676. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17677. * - `function(scope)`: execute the function with the current `scope` parameter.
  17678. *
  17679. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  17680. * @returns {*} The result of evaluating the expression.
  17681. */
  17682. $eval: function(expr, locals) {
  17683. return $parse(expr)(this, locals);
  17684. },
  17685. /**
  17686. * @ngdoc method
  17687. * @name $rootScope.Scope#$evalAsync
  17688. * @kind function
  17689. *
  17690. * @description
  17691. * Executes the expression on the current scope at a later point in time.
  17692. *
  17693. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  17694. * that:
  17695. *
  17696. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  17697. * rendering).
  17698. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  17699. * `expression` execution.
  17700. *
  17701. * Any exceptions from the execution of the expression are forwarded to the
  17702. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17703. *
  17704. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  17705. * will be scheduled. However, it is encouraged to always call code that changes the model
  17706. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  17707. *
  17708. * @param {(string|function())=} expression An AngularJS expression to be executed.
  17709. *
  17710. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17711. * - `function(scope)`: execute the function with the current `scope` parameter.
  17712. *
  17713. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  17714. */
  17715. $evalAsync: function(expr, locals) {
  17716. // if we are outside of an $digest loop and this is the first time we are scheduling async
  17717. // task also schedule async auto-flush
  17718. if (!$rootScope.$$phase && !asyncQueue.length) {
  17719. $browser.defer(function() {
  17720. if (asyncQueue.length) {
  17721. $rootScope.$digest();
  17722. }
  17723. }, null, '$evalAsync');
  17724. }
  17725. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  17726. },
  17727. $$postDigest: function(fn) {
  17728. postDigestQueue.push(fn);
  17729. },
  17730. /**
  17731. * @ngdoc method
  17732. * @name $rootScope.Scope#$apply
  17733. * @kind function
  17734. *
  17735. * @description
  17736. * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS
  17737. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  17738. * Because we are calling into the AngularJS framework we need to perform proper scope life
  17739. * cycle of {@link ng.$exceptionHandler exception handling},
  17740. * {@link ng.$rootScope.Scope#$digest executing watches}.
  17741. *
  17742. * **Life cycle: Pseudo-Code of `$apply()`**
  17743. *
  17744. * ```js
  17745. function $apply(expr) {
  17746. try {
  17747. return $eval(expr);
  17748. } catch (e) {
  17749. $exceptionHandler(e);
  17750. } finally {
  17751. $root.$digest();
  17752. }
  17753. }
  17754. * ```
  17755. *
  17756. *
  17757. * Scope's `$apply()` method transitions through the following stages:
  17758. *
  17759. * 1. The {@link guide/expression expression} is executed using the
  17760. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  17761. * 2. Any exceptions from the execution of the expression are forwarded to the
  17762. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17763. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  17764. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  17765. *
  17766. *
  17767. * @param {(string|function())=} exp An AngularJS expression to be executed.
  17768. *
  17769. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17770. * - `function(scope)`: execute the function with current `scope` parameter.
  17771. *
  17772. * @returns {*} The result of evaluating the expression.
  17773. */
  17774. $apply: function(expr) {
  17775. try {
  17776. beginPhase('$apply');
  17777. try {
  17778. return this.$eval(expr);
  17779. } finally {
  17780. clearPhase();
  17781. }
  17782. } catch (e) {
  17783. $exceptionHandler(e);
  17784. } finally {
  17785. try {
  17786. $rootScope.$digest();
  17787. } catch (e) {
  17788. $exceptionHandler(e);
  17789. // eslint-disable-next-line no-unsafe-finally
  17790. throw e;
  17791. }
  17792. }
  17793. },
  17794. /**
  17795. * @ngdoc method
  17796. * @name $rootScope.Scope#$applyAsync
  17797. * @kind function
  17798. *
  17799. * @description
  17800. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  17801. * varies across browsers, but is typically around ~10 milliseconds.
  17802. *
  17803. * This can be used to queue up multiple expressions which need to be evaluated in the same
  17804. * digest.
  17805. *
  17806. * @param {(string|function())=} exp An AngularJS expression to be executed.
  17807. *
  17808. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17809. * - `function(scope)`: execute the function with current `scope` parameter.
  17810. */
  17811. $applyAsync: function(expr) {
  17812. var scope = this;
  17813. if (expr) {
  17814. applyAsyncQueue.push($applyAsyncExpression);
  17815. }
  17816. expr = $parse(expr);
  17817. scheduleApplyAsync();
  17818. function $applyAsyncExpression() {
  17819. scope.$eval(expr);
  17820. }
  17821. },
  17822. /**
  17823. * @ngdoc method
  17824. * @name $rootScope.Scope#$on
  17825. * @kind function
  17826. *
  17827. * @description
  17828. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  17829. * discussion of event life cycle.
  17830. *
  17831. * The event listener function format is: `function(event, args...)`. The `event` object
  17832. * passed into the listener has the following attributes:
  17833. *
  17834. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  17835. * `$broadcast`-ed.
  17836. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  17837. * event propagates through the scope hierarchy, this property is set to null.
  17838. * - `name` - `{string}`: name of the event.
  17839. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  17840. * further event propagation (available only for events that were `$emit`-ed).
  17841. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  17842. * to true.
  17843. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  17844. *
  17845. * @param {string} name Event name to listen on.
  17846. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  17847. * @returns {function()} Returns a deregistration function for this listener.
  17848. */
  17849. $on: function(name, listener) {
  17850. var namedListeners = this.$$listeners[name];
  17851. if (!namedListeners) {
  17852. this.$$listeners[name] = namedListeners = [];
  17853. }
  17854. namedListeners.push(listener);
  17855. var current = this;
  17856. do {
  17857. if (!current.$$listenerCount[name]) {
  17858. current.$$listenerCount[name] = 0;
  17859. }
  17860. current.$$listenerCount[name]++;
  17861. } while ((current = current.$parent));
  17862. var self = this;
  17863. return function() {
  17864. var indexOfListener = namedListeners.indexOf(listener);
  17865. if (indexOfListener !== -1) {
  17866. // Use delete in the hope of the browser deallocating the memory for the array entry,
  17867. // while not shifting the array indexes of other listeners.
  17868. // See issue https://github.com/angular/angular.js/issues/16135
  17869. delete namedListeners[indexOfListener];
  17870. decrementListenerCount(self, 1, name);
  17871. }
  17872. };
  17873. },
  17874. /**
  17875. * @ngdoc method
  17876. * @name $rootScope.Scope#$emit
  17877. * @kind function
  17878. *
  17879. * @description
  17880. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  17881. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17882. *
  17883. * The event life cycle starts at the scope on which `$emit` was called. All
  17884. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17885. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  17886. * registered listeners along the way. The event will stop propagating if one of the listeners
  17887. * cancels it.
  17888. *
  17889. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17890. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17891. *
  17892. * @param {string} name Event name to emit.
  17893. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17894. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  17895. */
  17896. $emit: function(name, args) {
  17897. var empty = [],
  17898. namedListeners,
  17899. scope = this,
  17900. stopPropagation = false,
  17901. event = {
  17902. name: name,
  17903. targetScope: scope,
  17904. stopPropagation: function() {stopPropagation = true;},
  17905. preventDefault: function() {
  17906. event.defaultPrevented = true;
  17907. },
  17908. defaultPrevented: false
  17909. },
  17910. listenerArgs = concat([event], arguments, 1),
  17911. i, length;
  17912. do {
  17913. namedListeners = scope.$$listeners[name] || empty;
  17914. event.currentScope = scope;
  17915. for (i = 0, length = namedListeners.length; i < length; i++) {
  17916. // if listeners were deregistered, defragment the array
  17917. if (!namedListeners[i]) {
  17918. namedListeners.splice(i, 1);
  17919. i--;
  17920. length--;
  17921. continue;
  17922. }
  17923. try {
  17924. //allow all listeners attached to the current scope to run
  17925. namedListeners[i].apply(null, listenerArgs);
  17926. } catch (e) {
  17927. $exceptionHandler(e);
  17928. }
  17929. }
  17930. //if any listener on the current scope stops propagation, prevent bubbling
  17931. if (stopPropagation) {
  17932. break;
  17933. }
  17934. //traverse upwards
  17935. scope = scope.$parent;
  17936. } while (scope);
  17937. event.currentScope = null;
  17938. return event;
  17939. },
  17940. /**
  17941. * @ngdoc method
  17942. * @name $rootScope.Scope#$broadcast
  17943. * @kind function
  17944. *
  17945. * @description
  17946. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  17947. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17948. *
  17949. * The event life cycle starts at the scope on which `$broadcast` was called. All
  17950. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17951. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  17952. * scope and calls all registered listeners along the way. The event cannot be canceled.
  17953. *
  17954. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17955. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17956. *
  17957. * @param {string} name Event name to broadcast.
  17958. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17959. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  17960. */
  17961. $broadcast: function(name, args) {
  17962. var target = this,
  17963. current = target,
  17964. next = target,
  17965. event = {
  17966. name: name,
  17967. targetScope: target,
  17968. preventDefault: function() {
  17969. event.defaultPrevented = true;
  17970. },
  17971. defaultPrevented: false
  17972. };
  17973. if (!target.$$listenerCount[name]) return event;
  17974. var listenerArgs = concat([event], arguments, 1),
  17975. listeners, i, length;
  17976. //down while you can, then up and next sibling or up and next sibling until back at root
  17977. while ((current = next)) {
  17978. event.currentScope = current;
  17979. listeners = current.$$listeners[name] || [];
  17980. for (i = 0, length = listeners.length; i < length; i++) {
  17981. // if listeners were deregistered, defragment the array
  17982. if (!listeners[i]) {
  17983. listeners.splice(i, 1);
  17984. i--;
  17985. length--;
  17986. continue;
  17987. }
  17988. try {
  17989. listeners[i].apply(null, listenerArgs);
  17990. } catch (e) {
  17991. $exceptionHandler(e);
  17992. }
  17993. }
  17994. // Insanity Warning: scope depth-first traversal
  17995. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17996. // this piece should be kept in sync with the traversal in $digest
  17997. // (though it differs due to having the extra check for $$listenerCount and
  17998. // does not check $$suspended)
  17999. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  18000. (current !== target && current.$$nextSibling)))) {
  18001. while (current !== target && !(next = current.$$nextSibling)) {
  18002. current = current.$parent;
  18003. }
  18004. }
  18005. }
  18006. event.currentScope = null;
  18007. return event;
  18008. }
  18009. };
  18010. var $rootScope = new Scope();
  18011. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  18012. var asyncQueue = $rootScope.$$asyncQueue = [];
  18013. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  18014. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  18015. var postDigestQueuePosition = 0;
  18016. return $rootScope;
  18017. function beginPhase(phase) {
  18018. if ($rootScope.$$phase) {
  18019. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  18020. }
  18021. $rootScope.$$phase = phase;
  18022. }
  18023. function clearPhase() {
  18024. $rootScope.$$phase = null;
  18025. }
  18026. function incrementWatchersCount(current, count) {
  18027. do {
  18028. current.$$watchersCount += count;
  18029. } while ((current = current.$parent));
  18030. }
  18031. function decrementListenerCount(current, count, name) {
  18032. do {
  18033. current.$$listenerCount[name] -= count;
  18034. if (current.$$listenerCount[name] === 0) {
  18035. delete current.$$listenerCount[name];
  18036. }
  18037. } while ((current = current.$parent));
  18038. }
  18039. /**
  18040. * function used as an initial value for watchers.
  18041. * because it's unique we can easily tell it apart from other values
  18042. */
  18043. function initWatchVal() {}
  18044. function flushApplyAsync() {
  18045. while (applyAsyncQueue.length) {
  18046. try {
  18047. applyAsyncQueue.shift()();
  18048. } catch (e) {
  18049. $exceptionHandler(e);
  18050. }
  18051. }
  18052. applyAsyncId = null;
  18053. }
  18054. function scheduleApplyAsync() {
  18055. if (applyAsyncId === null) {
  18056. applyAsyncId = $browser.defer(function() {
  18057. $rootScope.$apply(flushApplyAsync);
  18058. }, null, '$applyAsync');
  18059. }
  18060. }
  18061. }];
  18062. }
  18063. /**
  18064. * @ngdoc service
  18065. * @name $rootElement
  18066. *
  18067. * @description
  18068. * The root element of AngularJS application. This is either the element where {@link
  18069. * ng.directive:ngApp ngApp} was declared or the element passed into
  18070. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  18071. * location where the application's {@link auto.$injector $injector} service gets
  18072. * published, and can be retrieved using `$rootElement.injector()`.
  18073. */
  18074. // the implementation is in angular.bootstrap
  18075. /**
  18076. * @this
  18077. * @description
  18078. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  18079. */
  18080. function $$SanitizeUriProvider() {
  18081. var aHrefSanitizationTrustedUrlList = /^\s*(https?|s?ftp|mailto|tel|file):/,
  18082. imgSrcSanitizationTrustedUrlList = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  18083. /**
  18084. * @description
  18085. * Retrieves or overrides the default regular expression that is used for determining trusted safe
  18086. * urls during a[href] sanitization.
  18087. *
  18088. * The sanitization is a security measure aimed at prevent XSS attacks via HTML anchor links.
  18089. *
  18090. * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring
  18091. * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)`
  18092. * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL.
  18093. *
  18094. * If the URL matches the `aHrefSanitizationTrustedUrlList` regular expression, it is returned unchanged.
  18095. *
  18096. * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written
  18097. * to the DOM it is inactive and potentially malicious code will not be executed.
  18098. *
  18099. * @param {RegExp=} regexp New regexp to trust urls with.
  18100. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18101. * chaining otherwise.
  18102. */
  18103. this.aHrefSanitizationTrustedUrlList = function(regexp) {
  18104. if (isDefined(regexp)) {
  18105. aHrefSanitizationTrustedUrlList = regexp;
  18106. return this;
  18107. }
  18108. return aHrefSanitizationTrustedUrlList;
  18109. };
  18110. /**
  18111. * @description
  18112. * Retrieves or overrides the default regular expression that is used for determining trusted safe
  18113. * urls during img[src] sanitization.
  18114. *
  18115. * The sanitization is a security measure aimed at prevent XSS attacks via HTML image src links.
  18116. *
  18117. * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring
  18118. * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to
  18119. * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize
  18120. * the potentially malicious URL.
  18121. *
  18122. * If the URL matches the `imgSrcSanitizationTrustedUrlList` regular expression, it is returned
  18123. * unchanged.
  18124. *
  18125. * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written
  18126. * to the DOM it is inactive and potentially malicious code will not be executed.
  18127. *
  18128. * @param {RegExp=} regexp New regexp to trust urls with.
  18129. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18130. * chaining otherwise.
  18131. */
  18132. this.imgSrcSanitizationTrustedUrlList = function(regexp) {
  18133. if (isDefined(regexp)) {
  18134. imgSrcSanitizationTrustedUrlList = regexp;
  18135. return this;
  18136. }
  18137. return imgSrcSanitizationTrustedUrlList;
  18138. };
  18139. this.$get = function() {
  18140. return function sanitizeUri(uri, isMediaUrl) {
  18141. // if (!uri) return uri;
  18142. var regex = isMediaUrl ? imgSrcSanitizationTrustedUrlList : aHrefSanitizationTrustedUrlList;
  18143. var normalizedVal = urlResolve(uri && uri.trim()).href;
  18144. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  18145. return 'unsafe:' + normalizedVal;
  18146. }
  18147. return uri;
  18148. };
  18149. };
  18150. }
  18151. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  18152. * Any commits to this file should be reviewed with security in mind. *
  18153. * Changes to this file can potentially create security vulnerabilities. *
  18154. * An approval from 2 Core members with history of modifying *
  18155. * this file is required. *
  18156. * *
  18157. * Does the change somehow allow for arbitrary javascript to be executed? *
  18158. * Or allows for someone to change the prototype of built-in objects? *
  18159. * Or gives undesired access to variables likes document or window? *
  18160. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  18161. /* exported $SceProvider, $SceDelegateProvider */
  18162. var $sceMinErr = minErr('$sce');
  18163. var SCE_CONTEXTS = {
  18164. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  18165. HTML: 'html',
  18166. // Style statements or stylesheets. Currently unused in AngularJS.
  18167. CSS: 'css',
  18168. // An URL used in a context where it refers to the source of media, which are not expected to be run
  18169. // as scripts, such as an image, audio, video, etc.
  18170. MEDIA_URL: 'mediaUrl',
  18171. // An URL used in a context where it does not refer to a resource that loads code.
  18172. // A value that can be trusted as a URL can also trusted as a MEDIA_URL.
  18173. URL: 'url',
  18174. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  18175. // code. (e.g. ng-include, script src binding, templateUrl)
  18176. // A value that can be trusted as a RESOURCE_URL, can also trusted as a URL and a MEDIA_URL.
  18177. RESOURCE_URL: 'resourceUrl',
  18178. // Script. Currently unused in AngularJS.
  18179. JS: 'js'
  18180. };
  18181. // Helper functions follow.
  18182. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  18183. function snakeToCamel(name) {
  18184. return name
  18185. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  18186. }
  18187. function adjustMatcher(matcher) {
  18188. if (matcher === 'self') {
  18189. return matcher;
  18190. } else if (isString(matcher)) {
  18191. // Strings match exactly except for 2 wildcards - '*' and '**'.
  18192. // '*' matches any character except those from the set ':/.?&'.
  18193. // '**' matches any character (like .* in a RegExp).
  18194. // More than 2 *'s raises an error as it's ill defined.
  18195. if (matcher.indexOf('***') > -1) {
  18196. throw $sceMinErr('iwcard',
  18197. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  18198. }
  18199. matcher = escapeForRegexp(matcher).
  18200. replace(/\\\*\\\*/g, '.*').
  18201. replace(/\\\*/g, '[^:/.?&;]*');
  18202. return new RegExp('^' + matcher + '$');
  18203. } else if (isRegExp(matcher)) {
  18204. // The only other type of matcher allowed is a Regexp.
  18205. // Match entire URL / disallow partial matches.
  18206. // Flags are reset (i.e. no global, ignoreCase or multiline)
  18207. return new RegExp('^' + matcher.source + '$');
  18208. } else {
  18209. throw $sceMinErr('imatcher',
  18210. 'Matchers may only be "self", string patterns or RegExp objects');
  18211. }
  18212. }
  18213. function adjustMatchers(matchers) {
  18214. var adjustedMatchers = [];
  18215. if (isDefined(matchers)) {
  18216. forEach(matchers, function(matcher) {
  18217. adjustedMatchers.push(adjustMatcher(matcher));
  18218. });
  18219. }
  18220. return adjustedMatchers;
  18221. }
  18222. /**
  18223. * @ngdoc service
  18224. * @name $sceDelegate
  18225. * @kind function
  18226. *
  18227. * @description
  18228. *
  18229. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  18230. * Contextual Escaping (SCE)} services to AngularJS.
  18231. *
  18232. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  18233. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  18234. * SCE works in their application, which shouldn't be needed in most cases.
  18235. *
  18236. * <div class="alert alert-danger">
  18237. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  18238. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  18239. * changes to this service will also influence users, so be extra careful and document your changes.
  18240. * </div>
  18241. *
  18242. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  18243. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  18244. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  18245. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  18246. * work because `$sce` delegates to `$sceDelegate` for these operations.
  18247. *
  18248. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  18249. *
  18250. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  18251. * can override it completely to change the behavior of `$sce`, the common case would
  18252. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  18253. * your own trusted and banned resource lists for trusting URLs used for loading AngularJS resources
  18254. * such as templates. Refer {@link ng.$sceDelegateProvider#trustedResourceUrlList
  18255. * $sceDelegateProvider.trustedResourceUrlList} and {@link
  18256. * ng.$sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider.bannedResourceUrlList}
  18257. */
  18258. /**
  18259. * @ngdoc provider
  18260. * @name $sceDelegateProvider
  18261. * @this
  18262. *
  18263. * @description
  18264. *
  18265. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  18266. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  18267. *
  18268. * The `$sceDelegateProvider` allows one to get/set the `trustedResourceUrlList` and
  18269. * `bannedResourceUrlList` used to ensure that the URLs used for sourcing AngularJS templates and
  18270. * other script-running URLs are safe (all places that use the `$sce.RESOURCE_URL` context). See
  18271. * {@link ng.$sceDelegateProvider#trustedResourceUrlList
  18272. * $sceDelegateProvider.trustedResourceUrlList} and
  18273. * {@link ng.$sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider.bannedResourceUrlList},
  18274. *
  18275. * For the general details about this service in AngularJS, read the main page for {@link ng.$sce
  18276. * Strict Contextual Escaping (SCE)}.
  18277. *
  18278. * **Example**: Consider the following case. <a name="example"></a>
  18279. *
  18280. * - your app is hosted at url `http://myapp.example.com/`
  18281. * - but some of your templates are hosted on other domains you control such as
  18282. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  18283. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  18284. *
  18285. * Here is what a secure configuration for this scenario might look like:
  18286. *
  18287. * ```
  18288. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  18289. * $sceDelegateProvider.trustedResourceUrlList([
  18290. * // Allow same origin resource loads.
  18291. * 'self',
  18292. * // Allow loading from our assets domain. Notice the difference between * and **.
  18293. * 'http://srv*.assets.example.com/**'
  18294. * ]);
  18295. *
  18296. * // The banned resource URL list overrides the trusted resource URL list so the open redirect
  18297. * // here is blocked.
  18298. * $sceDelegateProvider.bannedResourceUrlList([
  18299. * 'http://myapp.example.com/clickThru**'
  18300. * ]);
  18301. * });
  18302. * ```
  18303. * Note that an empty trusted resource URL list will block every resource URL from being loaded, and will require
  18304. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  18305. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  18306. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  18307. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  18308. * from the trusted resource URL lsit. This helps to mitigate the security impact of certain types
  18309. * of issues, like for instance attacker-controlled `ng-includes`.
  18310. */
  18311. function $SceDelegateProvider() {
  18312. this.SCE_CONTEXTS = SCE_CONTEXTS;
  18313. // Resource URLs can also be trusted by policy.
  18314. var trustedResourceUrlList = ['self'],
  18315. bannedResourceUrlList = [];
  18316. /**
  18317. * @ngdoc method
  18318. * @name $sceDelegateProvider#trustedResourceUrlList
  18319. * @kind function
  18320. *
  18321. * @param {Array=} trustedResourceUrlList When provided, replaces the trustedResourceUrlList with
  18322. * the value provided. This must be an array or null. A snapshot of this array is used so
  18323. * further changes to the array are ignored.
  18324. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  18325. * allowed in this array.
  18326. *
  18327. * @return {Array} The currently set trusted resource URL array.
  18328. *
  18329. * @description
  18330. * Sets/Gets the list trusted of resource URLs.
  18331. *
  18332. * The **default value** when no `trustedResourceUrlList` has been explicitly set is `['self']`
  18333. * allowing only same origin resource requests.
  18334. *
  18335. * <div class="alert alert-warning">
  18336. * **Note:** the default `trustedResourceUrlList` of 'self' is not recommended if your app shares
  18337. * its origin with other apps! It is a good idea to limit it to only your application's directory.
  18338. * </div>
  18339. */
  18340. this.trustedResourceUrlList = function(value) {
  18341. if (arguments.length) {
  18342. trustedResourceUrlList = adjustMatchers(value);
  18343. }
  18344. return trustedResourceUrlList;
  18345. };
  18346. /**
  18347. * @ngdoc method
  18348. * @name $sceDelegateProvider#resourceUrlWhitelist
  18349. * @kind function
  18350. *
  18351. * @deprecated
  18352. * sinceVersion="1.8.1"
  18353. *
  18354. * This method is deprecated. Use {@link $sceDelegateProvider#trustedResourceUrlList
  18355. * trustedResourceUrlList} instead.
  18356. */
  18357. Object.defineProperty(this, 'resourceUrlWhitelist', {
  18358. get: function() {
  18359. return this.trustedResourceUrlList;
  18360. },
  18361. set: function(value) {
  18362. this.trustedResourceUrlList = value;
  18363. }
  18364. });
  18365. /**
  18366. * @ngdoc method
  18367. * @name $sceDelegateProvider#bannedResourceUrlList
  18368. * @kind function
  18369. *
  18370. * @param {Array=} bannedResourceUrlList When provided, replaces the `bannedResourceUrlList` with
  18371. * the value provided. This must be an array or null. A snapshot of this array is used so
  18372. * further changes to the array are ignored.</p><p>
  18373. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  18374. * allowed in this array.</p><p>
  18375. * The typical usage for the `bannedResourceUrlList` is to **block
  18376. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  18377. * these would otherwise be trusted but actually return content from the redirected domain.
  18378. * </p><p>
  18379. * Finally, **the banned resource URL list overrides the trusted resource URL list** and has
  18380. * the final say.
  18381. *
  18382. * @return {Array} The currently set `bannedResourceUrlList` array.
  18383. *
  18384. * @description
  18385. * Sets/Gets the `bannedResourceUrlList` of trusted resource URLs.
  18386. *
  18387. * The **default value** when no trusted resource URL list has been explicitly set is the empty
  18388. * array (i.e. there is no `bannedResourceUrlList`.)
  18389. */
  18390. this.bannedResourceUrlList = function(value) {
  18391. if (arguments.length) {
  18392. bannedResourceUrlList = adjustMatchers(value);
  18393. }
  18394. return bannedResourceUrlList;
  18395. };
  18396. /**
  18397. * @ngdoc method
  18398. * @name $sceDelegateProvider#resourceUrlBlacklist
  18399. * @kind function
  18400. *
  18401. * @deprecated
  18402. * sinceVersion="1.8.1"
  18403. *
  18404. * This method is deprecated. Use {@link $sceDelegateProvider#bannedResourceUrlList
  18405. * bannedResourceUrlList} instead.
  18406. */
  18407. Object.defineProperty(this, 'resourceUrlBlacklist', {
  18408. get: function() {
  18409. return this.bannedResourceUrlList;
  18410. },
  18411. set: function(value) {
  18412. this.bannedResourceUrlList = value;
  18413. }
  18414. });
  18415. this.$get = ['$injector', '$$sanitizeUri', function($injector, $$sanitizeUri) {
  18416. var htmlSanitizer = function htmlSanitizer(html) {
  18417. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  18418. };
  18419. if ($injector.has('$sanitize')) {
  18420. htmlSanitizer = $injector.get('$sanitize');
  18421. }
  18422. function matchUrl(matcher, parsedUrl) {
  18423. if (matcher === 'self') {
  18424. return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl);
  18425. } else {
  18426. // definitely a regex. See adjustMatchers()
  18427. return !!matcher.exec(parsedUrl.href);
  18428. }
  18429. }
  18430. function isResourceUrlAllowedByPolicy(url) {
  18431. var parsedUrl = urlResolve(url.toString());
  18432. var i, n, allowed = false;
  18433. // Ensure that at least one item from the trusted resource URL list allows this url.
  18434. for (i = 0, n = trustedResourceUrlList.length; i < n; i++) {
  18435. if (matchUrl(trustedResourceUrlList[i], parsedUrl)) {
  18436. allowed = true;
  18437. break;
  18438. }
  18439. }
  18440. if (allowed) {
  18441. // Ensure that no item from the banned resource URL list has blocked this url.
  18442. for (i = 0, n = bannedResourceUrlList.length; i < n; i++) {
  18443. if (matchUrl(bannedResourceUrlList[i], parsedUrl)) {
  18444. allowed = false;
  18445. break;
  18446. }
  18447. }
  18448. }
  18449. return allowed;
  18450. }
  18451. function generateHolderType(Base) {
  18452. var holderType = function TrustedValueHolderType(trustedValue) {
  18453. this.$$unwrapTrustedValue = function() {
  18454. return trustedValue;
  18455. };
  18456. };
  18457. if (Base) {
  18458. holderType.prototype = new Base();
  18459. }
  18460. holderType.prototype.valueOf = function sceValueOf() {
  18461. return this.$$unwrapTrustedValue();
  18462. };
  18463. holderType.prototype.toString = function sceToString() {
  18464. return this.$$unwrapTrustedValue().toString();
  18465. };
  18466. return holderType;
  18467. }
  18468. var trustedValueHolderBase = generateHolderType(),
  18469. byType = {};
  18470. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  18471. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  18472. byType[SCE_CONTEXTS.MEDIA_URL] = generateHolderType(trustedValueHolderBase);
  18473. byType[SCE_CONTEXTS.URL] = generateHolderType(byType[SCE_CONTEXTS.MEDIA_URL]);
  18474. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  18475. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  18476. /**
  18477. * @ngdoc method
  18478. * @name $sceDelegate#trustAs
  18479. *
  18480. * @description
  18481. * Returns a trusted representation of the parameter for the specified context. This trusted
  18482. * object will later on be used as-is, without any security check, by bindings or directives
  18483. * that require this security context.
  18484. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  18485. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  18486. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  18487. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  18488. * security risk.
  18489. *
  18490. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  18491. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  18492. * escaping.
  18493. *
  18494. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  18495. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  18496. *
  18497. * @param {*} value The value that should be considered trusted.
  18498. * @return {*} A trusted representation of value, that can be used in the given context.
  18499. */
  18500. function trustAs(type, trustedValue) {
  18501. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  18502. if (!Constructor) {
  18503. throw $sceMinErr('icontext',
  18504. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  18505. type, trustedValue);
  18506. }
  18507. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  18508. return trustedValue;
  18509. }
  18510. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  18511. // mutable objects, we ensure here that the value passed in is actually a string.
  18512. if (typeof trustedValue !== 'string') {
  18513. throw $sceMinErr('itype',
  18514. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  18515. type);
  18516. }
  18517. return new Constructor(trustedValue);
  18518. }
  18519. /**
  18520. * @ngdoc method
  18521. * @name $sceDelegate#valueOf
  18522. *
  18523. * @description
  18524. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  18525. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  18526. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  18527. *
  18528. * If the passed parameter is not a value that had been returned by {@link
  18529. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  18530. *
  18531. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  18532. * call or anything else.
  18533. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  18534. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  18535. * `value` unchanged.
  18536. */
  18537. function valueOf(maybeTrusted) {
  18538. if (maybeTrusted instanceof trustedValueHolderBase) {
  18539. return maybeTrusted.$$unwrapTrustedValue();
  18540. } else {
  18541. return maybeTrusted;
  18542. }
  18543. }
  18544. /**
  18545. * @ngdoc method
  18546. * @name $sceDelegate#getTrusted
  18547. *
  18548. * @description
  18549. * Given an object and a security context in which to assign it, returns a value that's safe to
  18550. * use in this context, which was represented by the parameter. To do so, this function either
  18551. * unwraps the safe type it has been given (for instance, a {@link ng.$sceDelegate#trustAs
  18552. * `$sceDelegate.trustAs`} result), or it might try to sanitize the value given, depending on
  18553. * the context and sanitizer availablility.
  18554. *
  18555. * The contexts that can be sanitized are $sce.MEDIA_URL, $sce.URL and $sce.HTML. The first two are available
  18556. * by default, and the third one relies on the `$sanitize` service (which may be loaded through
  18557. * the `ngSanitize` module). Furthermore, for $sce.RESOURCE_URL context, a plain string may be
  18558. * accepted if the resource url policy defined by {@link ng.$sceDelegateProvider#trustedResourceUrlList
  18559. * `$sceDelegateProvider.trustedResourceUrlList`} and {@link ng.$sceDelegateProvider#bannedResourceUrlList
  18560. * `$sceDelegateProvider.bannedResourceUrlList`} accepts that resource.
  18561. *
  18562. * This function will throw if the safe type isn't appropriate for this context, or if the
  18563. * value given cannot be accepted in the context (which might be caused by sanitization not
  18564. * being available, or the value not being recognized as safe).
  18565. *
  18566. * <div class="alert alert-danger">
  18567. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  18568. * (XSS) vulnerability in your application.
  18569. * </div>
  18570. *
  18571. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  18572. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  18573. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  18574. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18575. * exception if this is impossible.
  18576. */
  18577. function getTrusted(type, maybeTrusted) {
  18578. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  18579. return maybeTrusted;
  18580. }
  18581. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  18582. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  18583. // as-is.
  18584. if (constructor && maybeTrusted instanceof constructor) {
  18585. return maybeTrusted.$$unwrapTrustedValue();
  18586. }
  18587. // If maybeTrusted is a trusted class instance but not of the correct trusted type
  18588. // then unwrap it and allow it to pass through to the rest of the checks
  18589. if (isFunction(maybeTrusted.$$unwrapTrustedValue)) {
  18590. maybeTrusted = maybeTrusted.$$unwrapTrustedValue();
  18591. }
  18592. // If we get here, then we will either sanitize the value or throw an exception.
  18593. if (type === SCE_CONTEXTS.MEDIA_URL || type === SCE_CONTEXTS.URL) {
  18594. // we attempt to sanitize non-resource URLs
  18595. return $$sanitizeUri(maybeTrusted.toString(), type === SCE_CONTEXTS.MEDIA_URL);
  18596. } else if (type === SCE_CONTEXTS.RESOURCE_URL) {
  18597. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  18598. return maybeTrusted;
  18599. } else {
  18600. throw $sceMinErr('insecurl',
  18601. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  18602. maybeTrusted.toString());
  18603. }
  18604. } else if (type === SCE_CONTEXTS.HTML) {
  18605. // htmlSanitizer throws its own error when no sanitizer is available.
  18606. return htmlSanitizer(maybeTrusted);
  18607. }
  18608. // Default error when the $sce service has no way to make the input safe.
  18609. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  18610. }
  18611. return { trustAs: trustAs,
  18612. getTrusted: getTrusted,
  18613. valueOf: valueOf };
  18614. }];
  18615. }
  18616. /**
  18617. * @ngdoc provider
  18618. * @name $sceProvider
  18619. * @this
  18620. *
  18621. * @description
  18622. *
  18623. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  18624. * - enable/disable Strict Contextual Escaping (SCE) in a module
  18625. * - override the default implementation with a custom delegate
  18626. *
  18627. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  18628. */
  18629. /**
  18630. * @ngdoc service
  18631. * @name $sce
  18632. * @kind function
  18633. *
  18634. * @description
  18635. *
  18636. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  18637. *
  18638. * ## Strict Contextual Escaping
  18639. *
  18640. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  18641. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  18642. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  18643. *
  18644. * ### Overview
  18645. *
  18646. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  18647. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  18648. * run security checks on them (sanitizations, trusted URL resource, depending on context), or throw
  18649. * when it cannot guarantee the security of the result. That behavior depends strongly on contexts:
  18650. * HTML can be sanitized, but template URLs cannot, for instance.
  18651. *
  18652. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  18653. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  18654. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  18655. * render the input as-is, you will need to mark it as trusted for that context before attempting
  18656. * to bind it.
  18657. *
  18658. * As of version 1.2, AngularJS ships with SCE enabled by default.
  18659. *
  18660. * ### In practice
  18661. *
  18662. * Here's an example of a binding in a privileged context:
  18663. *
  18664. * ```
  18665. * <input ng-model="userHtml" aria-label="User input">
  18666. * <div ng-bind-html="userHtml"></div>
  18667. * ```
  18668. *
  18669. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  18670. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  18671. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  18672. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  18673. * controlled input creates security vulnerabilities.)
  18674. *
  18675. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  18676. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  18677. *
  18678. * How would you ensure that every place that used these types of bindings was bound to a value that
  18679. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  18680. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  18681. * properties/fields and forgot to update the binding to the sanitized value?
  18682. *
  18683. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  18684. * any similar validation process, unless there's a good reason to trust the given value in this
  18685. * context. That trust is formalized with a function call. This means that as a developer, you
  18686. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  18687. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  18688. * received from your server, sanitized by your library, etc. You can organize your codebase to
  18689. * help with this - perhaps allowing only the files in a specific directory to do this.
  18690. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  18691. * becomes a more manageable task.
  18692. *
  18693. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  18694. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  18695. * build the trusted versions of your values.
  18696. *
  18697. * ### How does it work?
  18698. *
  18699. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  18700. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  18701. * a way to enforce the required security context in your data sink. Directives use {@link
  18702. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  18703. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  18704. * when binding without directives, AngularJS will understand the context of your bindings
  18705. * automatically.
  18706. *
  18707. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  18708. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  18709. * simplified):
  18710. *
  18711. * ```
  18712. * var ngBindHtmlDirective = ['$sce', function($sce) {
  18713. * return function(scope, element, attr) {
  18714. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  18715. * element.html(value || '');
  18716. * });
  18717. * };
  18718. * }];
  18719. * ```
  18720. *
  18721. * ### Impact on loading templates
  18722. *
  18723. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  18724. * `templateUrl`'s specified by {@link guide/directive directives}.
  18725. *
  18726. * By default, AngularJS only loads templates from the same domain and protocol as the application
  18727. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  18728. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  18729. * protocols, you may either add them to the {@link ng.$sceDelegateProvider#trustedResourceUrlList
  18730. * trustedResourceUrlList} or {@link ng.$sce#trustAsResourceUrl wrap them} into trusted values.
  18731. *
  18732. * *Please note*:
  18733. * The browser's
  18734. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  18735. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  18736. * policy apply in addition to this and may further restrict whether the template is successfully
  18737. * loaded. This means that without the right CORS policy, loading templates from a different domain
  18738. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  18739. * browsers.
  18740. *
  18741. * ### This feels like too much overhead
  18742. *
  18743. * It's important to remember that SCE only applies to interpolation expressions.
  18744. *
  18745. * If your expressions are constant literals, they're automatically trusted and you don't need to
  18746. * call `$sce.trustAs` on them (e.g.
  18747. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works (remember to include the
  18748. * `ngSanitize` module). The `$sceDelegate` will also use the `$sanitize` service if it is available
  18749. * when binding untrusted values to `$sce.HTML` context.
  18750. * AngularJS provides an implementation in `angular-sanitize.js`, and if you
  18751. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  18752. * your application.
  18753. *
  18754. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  18755. * templates in `ng-include` from your application's domain without having to even know about SCE.
  18756. * It blocks loading templates from other domains or loading templates over http from an https
  18757. * served document. You can change these by setting your own custom {@link
  18758. * ng.$sceDelegateProvider#trustedResourceUrlList trusted resource URL list} and {@link
  18759. * ng.$sceDelegateProvider#bannedResourceUrlList banned resource URL list} for matching such URLs.
  18760. *
  18761. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  18762. * application that's secure and can be audited to verify that with much more ease than bolting
  18763. * security onto an application later.
  18764. *
  18765. * <a name="contexts"></a>
  18766. * ### What trusted context types are supported?
  18767. *
  18768. * | Context | Notes |
  18769. * |---------------------|----------------|
  18770. * | `$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. |
  18771. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  18772. * | `$sce.MEDIA_URL` | For URLs that are safe to render as media. Is automatically converted from string by sanitizing when needed. |
  18773. * | `$sce.URL` | For URLs that are safe to follow as links. Is automatically converted from string by sanitizing when needed. Note that `$sce.URL` makes a stronger statement about the URL than `$sce.MEDIA_URL` does and therefore contexts requiring values trusted for `$sce.URL` can be used anywhere that values trusted for `$sce.MEDIA_URL` are required.|
  18774. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` or `$sce.MEDIA_URL` do and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` or `$sce.MEDIA_URL` are required. <br><br> The {@link $sceDelegateProvider#trustedResourceUrlList $sceDelegateProvider#trustedResourceUrlList()} and {@link $sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider#bannedResourceUrlList()} can be used to restrict trusted origins for `RESOURCE_URL` |
  18775. * | `$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. |
  18776. *
  18777. *
  18778. * <div class="alert alert-warning">
  18779. * Be aware that, before AngularJS 1.7.0, `a[href]` and `img[src]` used to sanitize their
  18780. * interpolated values directly rather than rely upon {@link ng.$sce#getTrusted `$sce.getTrusted`}.
  18781. *
  18782. * **As of 1.7.0, this is no longer the case.**
  18783. *
  18784. * Now such interpolations are marked as requiring `$sce.URL` (for `a[href]`) or `$sce.MEDIA_URL`
  18785. * (for `img[src]`), so that the sanitization happens (via `$sce.getTrusted...`) when the `$interpolate`
  18786. * service evaluates the expressions.
  18787. * </div>
  18788. *
  18789. * There are no CSS or JS context bindings in AngularJS currently, so their corresponding `$sce.trustAs`
  18790. * functions aren't useful yet. This might evolve.
  18791. *
  18792. * ### Format of items in {@link ng.$sceDelegateProvider#trustedResourceUrlList trustedResourceUrlList}/{@link ng.$sceDelegateProvider#bannedResourceUrlList bannedResourceUrlList} <a name="resourceUrlPatternItem"></a>
  18793. *
  18794. * Each element in these arrays must be one of the following:
  18795. *
  18796. * - **'self'**
  18797. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  18798. * domain** as the application document using the **same protocol**.
  18799. * - **String** (except the special value `'self'`)
  18800. * - The string is matched against the full *normalized / absolute URL* of the resource
  18801. * being tested (substring matches are not good enough.)
  18802. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  18803. * match themselves.
  18804. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  18805. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  18806. * for matching resource URL lists.
  18807. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  18808. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  18809. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  18810. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  18811. * http://foo.example.com/templates/**).
  18812. * - **RegExp** (*see caveat below*)
  18813. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  18814. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  18815. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  18816. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  18817. * small number of cases. A `.` character in the regex used when matching the scheme or a
  18818. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  18819. * is highly recommended to use the string patterns and only fall back to regular expressions
  18820. * as a last resort.
  18821. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  18822. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  18823. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  18824. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  18825. * - If you are generating your JavaScript from some other templating engine (not
  18826. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  18827. * remember to escape your regular expression (and be aware that you might need more than
  18828. * one level of escaping depending on your templating engine and the way you interpolated
  18829. * the value.) Do make use of your platform's escaping mechanism as it might be good
  18830. * enough before coding your own. E.g. Ruby has
  18831. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  18832. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  18833. * Javascript lacks a similar built in function for escaping. Take a look at Google
  18834. * Closure library's [goog.string.regExpEscape(s)](
  18835. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  18836. *
  18837. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  18838. *
  18839. * ### Show me an example using SCE.
  18840. *
  18841. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  18842. * <file name="index.html">
  18843. * <div ng-controller="AppController as myCtrl">
  18844. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  18845. * <b>User comments</b><br>
  18846. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  18847. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  18848. * exploit.
  18849. * <div class="well">
  18850. * <div ng-repeat="userComment in myCtrl.userComments">
  18851. * <b>{{userComment.name}}</b>:
  18852. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  18853. * <br>
  18854. * </div>
  18855. * </div>
  18856. * </div>
  18857. * </file>
  18858. *
  18859. * <file name="script.js">
  18860. * angular.module('mySceApp', ['ngSanitize'])
  18861. * .controller('AppController', ['$http', '$templateCache', '$sce',
  18862. * function AppController($http, $templateCache, $sce) {
  18863. * var self = this;
  18864. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  18865. * self.userComments = response.data;
  18866. * });
  18867. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  18868. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  18869. * 'sanitization.&quot;">Hover over this text.</span>');
  18870. * }]);
  18871. * </file>
  18872. *
  18873. * <file name="test_data.json">
  18874. * [
  18875. * { "name": "Alice",
  18876. * "htmlComment":
  18877. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  18878. * },
  18879. * { "name": "Bob",
  18880. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  18881. * }
  18882. * ]
  18883. * </file>
  18884. *
  18885. * <file name="protractor.js" type="protractor">
  18886. * describe('SCE doc demo', function() {
  18887. * it('should sanitize untrusted values', function() {
  18888. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  18889. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  18890. * });
  18891. *
  18892. * it('should NOT sanitize explicitly trusted values', function() {
  18893. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  18894. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  18895. * 'sanitization.&quot;">Hover over this text.</span>');
  18896. * });
  18897. * });
  18898. * </file>
  18899. * </example>
  18900. *
  18901. *
  18902. *
  18903. * ## Can I disable SCE completely?
  18904. *
  18905. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  18906. * for little coding overhead. It will be much harder to take an SCE disabled application and
  18907. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  18908. * for cases where you have a lot of existing code that was written before SCE was introduced and
  18909. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  18910. * you are writing a library, you will cause security bugs applications using it.
  18911. *
  18912. * That said, here's how you can completely disable SCE:
  18913. *
  18914. * ```
  18915. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  18916. * // Completely disable SCE. For demonstration purposes only!
  18917. * // Do not use in new projects or libraries.
  18918. * $sceProvider.enabled(false);
  18919. * });
  18920. * ```
  18921. *
  18922. */
  18923. function $SceProvider() {
  18924. var enabled = true;
  18925. /**
  18926. * @ngdoc method
  18927. * @name $sceProvider#enabled
  18928. * @kind function
  18929. *
  18930. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  18931. * @return {boolean} True if SCE is enabled, false otherwise.
  18932. *
  18933. * @description
  18934. * Enables/disables SCE and returns the current value.
  18935. */
  18936. this.enabled = function(value) {
  18937. if (arguments.length) {
  18938. enabled = !!value;
  18939. }
  18940. return enabled;
  18941. };
  18942. /* Design notes on the default implementation for SCE.
  18943. *
  18944. * The API contract for the SCE delegate
  18945. * -------------------------------------
  18946. * The SCE delegate object must provide the following 3 methods:
  18947. *
  18948. * - trustAs(contextEnum, value)
  18949. * This method is used to tell the SCE service that the provided value is OK to use in the
  18950. * contexts specified by contextEnum. It must return an object that will be accepted by
  18951. * getTrusted() for a compatible contextEnum and return this value.
  18952. *
  18953. * - valueOf(value)
  18954. * For values that were not produced by trustAs(), return them as is. For values that were
  18955. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  18956. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  18957. * such a value.
  18958. *
  18959. * - getTrusted(contextEnum, value)
  18960. * This function should return the value that is safe to use in the context specified by
  18961. * contextEnum or throw and exception otherwise.
  18962. *
  18963. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  18964. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  18965. * instance, an implementation could maintain a registry of all trusted objects by context. In
  18966. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  18967. * return the same object passed in if it was found in the registry under a compatible context or
  18968. * throw an exception otherwise. An implementation might only wrap values some of the time based
  18969. * on some criteria. getTrusted() might return a value and not throw an exception for special
  18970. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  18971. *
  18972. *
  18973. * A note on the inheritance model for SCE contexts
  18974. * ------------------------------------------------
  18975. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  18976. * is purely an implementation details.
  18977. *
  18978. * The contract is simply this:
  18979. *
  18980. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  18981. * will also succeed.
  18982. *
  18983. * Inheritance happens to capture this in a natural way. In some future, we may not use
  18984. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  18985. * be aware of this detail.
  18986. */
  18987. this.$get = ['$parse', '$sceDelegate', function(
  18988. $parse, $sceDelegate) {
  18989. // Support: IE 9-11 only
  18990. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  18991. // the "expression(javascript expression)" syntax which is insecure.
  18992. if (enabled && msie < 8) {
  18993. throw $sceMinErr('iequirks',
  18994. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  18995. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  18996. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  18997. }
  18998. var sce = shallowCopy(SCE_CONTEXTS);
  18999. /**
  19000. * @ngdoc method
  19001. * @name $sce#isEnabled
  19002. * @kind function
  19003. *
  19004. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  19005. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  19006. *
  19007. * @description
  19008. * Returns a boolean indicating if SCE is enabled.
  19009. */
  19010. sce.isEnabled = function() {
  19011. return enabled;
  19012. };
  19013. sce.trustAs = $sceDelegate.trustAs;
  19014. sce.getTrusted = $sceDelegate.getTrusted;
  19015. sce.valueOf = $sceDelegate.valueOf;
  19016. if (!enabled) {
  19017. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  19018. sce.valueOf = identity;
  19019. }
  19020. /**
  19021. * @ngdoc method
  19022. * @name $sce#parseAs
  19023. *
  19024. * @description
  19025. * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link
  19026. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  19027. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  19028. * *result*)}
  19029. *
  19030. * @param {string} type The SCE context in which this result will be used.
  19031. * @param {string} expression String expression to compile.
  19032. * @return {function(context, locals)} A function which represents the compiled expression:
  19033. *
  19034. * * `context` – `{object}` – an object against which any expressions embedded in the
  19035. * strings are evaluated against (typically a scope object).
  19036. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19037. * in `context`.
  19038. */
  19039. sce.parseAs = function sceParseAs(type, expr) {
  19040. var parsed = $parse(expr);
  19041. if (parsed.literal && parsed.constant) {
  19042. return parsed;
  19043. } else {
  19044. return $parse(expr, function(value) {
  19045. return sce.getTrusted(type, value);
  19046. });
  19047. }
  19048. };
  19049. /**
  19050. * @ngdoc method
  19051. * @name $sce#trustAs
  19052. *
  19053. * @description
  19054. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  19055. * wrapped object that represents your value, and the trust you have in its safety for the given
  19056. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  19057. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  19058. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  19059. *
  19060. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  19061. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  19062. *
  19063. * @param {*} value The value that that should be considered trusted.
  19064. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  19065. * in the context you specified.
  19066. */
  19067. /**
  19068. * @ngdoc method
  19069. * @name $sce#trustAsHtml
  19070. *
  19071. * @description
  19072. * Shorthand method. `$sce.trustAsHtml(value)` →
  19073. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  19074. *
  19075. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  19076. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  19077. * in `$sce.HTML` context (like `ng-bind-html`).
  19078. */
  19079. /**
  19080. * @ngdoc method
  19081. * @name $sce#trustAsCss
  19082. *
  19083. * @description
  19084. * Shorthand method. `$sce.trustAsCss(value)` →
  19085. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  19086. *
  19087. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  19088. * @return {*} A wrapped version of value that can be used as a trusted variant
  19089. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  19090. * almost no reasons to use this function so far.
  19091. */
  19092. /**
  19093. * @ngdoc method
  19094. * @name $sce#trustAsUrl
  19095. *
  19096. * @description
  19097. * Shorthand method. `$sce.trustAsUrl(value)` →
  19098. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  19099. *
  19100. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  19101. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  19102. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  19103. * to use this function so far.
  19104. */
  19105. /**
  19106. * @ngdoc method
  19107. * @name $sce#trustAsResourceUrl
  19108. *
  19109. * @description
  19110. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  19111. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  19112. *
  19113. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  19114. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  19115. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  19116. * bindings, ...)
  19117. */
  19118. /**
  19119. * @ngdoc method
  19120. * @name $sce#trustAsJs
  19121. *
  19122. * @description
  19123. * Shorthand method. `$sce.trustAsJs(value)` →
  19124. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  19125. *
  19126. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  19127. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  19128. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  19129. * use this function so far.
  19130. */
  19131. /**
  19132. * @ngdoc method
  19133. * @name $sce#getTrusted
  19134. *
  19135. * @description
  19136. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  19137. * takes any input, and either returns a value that's safe to use in the specified context,
  19138. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  19139. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  19140. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  19141. * safe value (e.g., no sanitization is available or possible.)
  19142. *
  19143. * @param {string} type The context in which this value is to be used.
  19144. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  19145. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  19146. * @return {*} A version of the value that's safe to use in the given context, or throws an
  19147. * exception if this is impossible.
  19148. */
  19149. /**
  19150. * @ngdoc method
  19151. * @name $sce#getTrustedHtml
  19152. *
  19153. * @description
  19154. * Shorthand method. `$sce.getTrustedHtml(value)` →
  19155. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  19156. *
  19157. * @param {*} value The value to pass to `$sce.getTrusted`.
  19158. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  19159. */
  19160. /**
  19161. * @ngdoc method
  19162. * @name $sce#getTrustedCss
  19163. *
  19164. * @description
  19165. * Shorthand method. `$sce.getTrustedCss(value)` →
  19166. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  19167. *
  19168. * @param {*} value The value to pass to `$sce.getTrusted`.
  19169. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  19170. */
  19171. /**
  19172. * @ngdoc method
  19173. * @name $sce#getTrustedUrl
  19174. *
  19175. * @description
  19176. * Shorthand method. `$sce.getTrustedUrl(value)` →
  19177. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  19178. *
  19179. * @param {*} value The value to pass to `$sce.getTrusted`.
  19180. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  19181. */
  19182. /**
  19183. * @ngdoc method
  19184. * @name $sce#getTrustedResourceUrl
  19185. *
  19186. * @description
  19187. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  19188. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  19189. *
  19190. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  19191. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  19192. */
  19193. /**
  19194. * @ngdoc method
  19195. * @name $sce#getTrustedJs
  19196. *
  19197. * @description
  19198. * Shorthand method. `$sce.getTrustedJs(value)` →
  19199. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  19200. *
  19201. * @param {*} value The value to pass to `$sce.getTrusted`.
  19202. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  19203. */
  19204. /**
  19205. * @ngdoc method
  19206. * @name $sce#parseAsHtml
  19207. *
  19208. * @description
  19209. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  19210. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  19211. *
  19212. * @param {string} expression String expression to compile.
  19213. * @return {function(context, locals)} A function which represents the compiled expression:
  19214. *
  19215. * * `context` – `{object}` – an object against which any expressions embedded in the
  19216. * strings are evaluated against (typically a scope object).
  19217. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19218. * in `context`.
  19219. */
  19220. /**
  19221. * @ngdoc method
  19222. * @name $sce#parseAsCss
  19223. *
  19224. * @description
  19225. * Shorthand method. `$sce.parseAsCss(value)` →
  19226. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  19227. *
  19228. * @param {string} expression String expression to compile.
  19229. * @return {function(context, locals)} A function which represents the compiled expression:
  19230. *
  19231. * * `context` – `{object}` – an object against which any expressions embedded in the
  19232. * strings are evaluated against (typically a scope object).
  19233. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19234. * in `context`.
  19235. */
  19236. /**
  19237. * @ngdoc method
  19238. * @name $sce#parseAsUrl
  19239. *
  19240. * @description
  19241. * Shorthand method. `$sce.parseAsUrl(value)` →
  19242. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  19243. *
  19244. * @param {string} expression String expression to compile.
  19245. * @return {function(context, locals)} A function which represents the compiled expression:
  19246. *
  19247. * * `context` – `{object}` – an object against which any expressions embedded in the
  19248. * strings are evaluated against (typically a scope object).
  19249. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19250. * in `context`.
  19251. */
  19252. /**
  19253. * @ngdoc method
  19254. * @name $sce#parseAsResourceUrl
  19255. *
  19256. * @description
  19257. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  19258. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  19259. *
  19260. * @param {string} expression String expression to compile.
  19261. * @return {function(context, locals)} A function which represents the compiled expression:
  19262. *
  19263. * * `context` – `{object}` – an object against which any expressions embedded in the
  19264. * strings are evaluated against (typically a scope object).
  19265. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19266. * in `context`.
  19267. */
  19268. /**
  19269. * @ngdoc method
  19270. * @name $sce#parseAsJs
  19271. *
  19272. * @description
  19273. * Shorthand method. `$sce.parseAsJs(value)` →
  19274. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  19275. *
  19276. * @param {string} expression String expression to compile.
  19277. * @return {function(context, locals)} A function which represents the compiled expression:
  19278. *
  19279. * * `context` – `{object}` – an object against which any expressions embedded in the
  19280. * strings are evaluated against (typically a scope object).
  19281. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19282. * in `context`.
  19283. */
  19284. // Shorthand delegations.
  19285. var parse = sce.parseAs,
  19286. getTrusted = sce.getTrusted,
  19287. trustAs = sce.trustAs;
  19288. forEach(SCE_CONTEXTS, function(enumValue, name) {
  19289. var lName = lowercase(name);
  19290. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  19291. return parse(enumValue, expr);
  19292. };
  19293. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  19294. return getTrusted(enumValue, value);
  19295. };
  19296. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  19297. return trustAs(enumValue, value);
  19298. };
  19299. });
  19300. return sce;
  19301. }];
  19302. }
  19303. /* exported $SnifferProvider */
  19304. /**
  19305. * !!! This is an undocumented "private" service !!!
  19306. *
  19307. * @name $sniffer
  19308. * @requires $window
  19309. * @requires $document
  19310. * @this
  19311. *
  19312. * @property {boolean} history Does the browser support html5 history api ?
  19313. * @property {boolean} transitions Does the browser support CSS transition events ?
  19314. * @property {boolean} animations Does the browser support CSS animation events ?
  19315. *
  19316. * @description
  19317. * This is very simple implementation of testing browser's features.
  19318. */
  19319. function $SnifferProvider() {
  19320. this.$get = ['$window', '$document', function($window, $document) {
  19321. var eventSupport = {},
  19322. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  19323. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  19324. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  19325. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  19326. // (see https://developer.chrome.com/apps/manifest/sandbox).
  19327. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  19328. isNw = $window.nw && $window.nw.process,
  19329. isChromePackagedApp =
  19330. !isNw &&
  19331. $window.chrome &&
  19332. ($window.chrome.app && $window.chrome.app.runtime ||
  19333. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  19334. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  19335. android =
  19336. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  19337. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  19338. document = $document[0] || {},
  19339. bodyStyle = document.body && document.body.style,
  19340. transitions = false,
  19341. animations = false;
  19342. if (bodyStyle) {
  19343. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  19344. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  19345. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  19346. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  19347. }
  19348. return {
  19349. // Android has history.pushState, but it does not update location correctly
  19350. // so let's not use the history API at all.
  19351. // http://code.google.com/p/android/issues/detail?id=17471
  19352. // https://github.com/angular/angular.js/issues/904
  19353. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  19354. // so let's not use the history API also
  19355. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  19356. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  19357. hasEvent: function(event) {
  19358. // Support: IE 9-11 only
  19359. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  19360. // it. In particular the event is not fired when backspace or delete key are pressed or
  19361. // when cut operation is performed.
  19362. // IE10+ implements 'input' event but it erroneously fires under various situations,
  19363. // e.g. when placeholder changes, or a form is focused.
  19364. if (event === 'input' && msie) return false;
  19365. if (isUndefined(eventSupport[event])) {
  19366. var divElm = document.createElement('div');
  19367. eventSupport[event] = 'on' + event in divElm;
  19368. }
  19369. return eventSupport[event];
  19370. },
  19371. csp: csp(),
  19372. transitions: transitions,
  19373. animations: animations,
  19374. android: android
  19375. };
  19376. }];
  19377. }
  19378. /**
  19379. * ! This is a private undocumented service !
  19380. *
  19381. * @name $$taskTrackerFactory
  19382. * @description
  19383. * A function to create `TaskTracker` instances.
  19384. *
  19385. * A `TaskTracker` can keep track of pending tasks (grouped by type) and can notify interested
  19386. * parties when all pending tasks (or tasks of a specific type) have been completed.
  19387. *
  19388. * @param {$log} log - A logger instance (such as `$log`). Used to log error during callback
  19389. * execution.
  19390. *
  19391. * @this
  19392. */
  19393. function $$TaskTrackerFactoryProvider() {
  19394. this.$get = valueFn(function(log) { return new TaskTracker(log); });
  19395. }
  19396. function TaskTracker(log) {
  19397. var self = this;
  19398. var taskCounts = {};
  19399. var taskCallbacks = [];
  19400. var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$';
  19401. var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$';
  19402. /**
  19403. * Execute the specified function and decrement the appropriate `taskCounts` counter.
  19404. * If the counter reaches 0, all corresponding `taskCallbacks` are executed.
  19405. *
  19406. * @param {Function} fn - The function to execute.
  19407. * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task that is being completed.
  19408. */
  19409. self.completeTask = completeTask;
  19410. /**
  19411. * Increase the task count for the specified task type (or the default task type if non is
  19412. * specified).
  19413. *
  19414. * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task whose count will be increased.
  19415. */
  19416. self.incTaskCount = incTaskCount;
  19417. /**
  19418. * Execute the specified callback when all pending tasks have been completed.
  19419. *
  19420. * If there are no pending tasks, the callback is executed immediately. You can optionally limit
  19421. * the tasks that will be waited for to a specific type, by passing a `taskType`.
  19422. *
  19423. * @param {function} callback - The function to call when there are no pending tasks.
  19424. * @param {string=} [taskType=ALL_TASKS_TYPE] - The type of tasks that will be waited for.
  19425. */
  19426. self.notifyWhenNoPendingTasks = notifyWhenNoPendingTasks;
  19427. function completeTask(fn, taskType) {
  19428. taskType = taskType || DEFAULT_TASK_TYPE;
  19429. try {
  19430. fn();
  19431. } finally {
  19432. decTaskCount(taskType);
  19433. var countForType = taskCounts[taskType];
  19434. var countForAll = taskCounts[ALL_TASKS_TYPE];
  19435. // If at least one of the queues (`ALL_TASKS_TYPE` or `taskType`) is empty, run callbacks.
  19436. if (!countForAll || !countForType) {
  19437. var getNextCallback = !countForAll ? getLastCallback : getLastCallbackForType;
  19438. var nextCb;
  19439. while ((nextCb = getNextCallback(taskType))) {
  19440. try {
  19441. nextCb();
  19442. } catch (e) {
  19443. log.error(e);
  19444. }
  19445. }
  19446. }
  19447. }
  19448. }
  19449. function decTaskCount(taskType) {
  19450. taskType = taskType || DEFAULT_TASK_TYPE;
  19451. if (taskCounts[taskType]) {
  19452. taskCounts[taskType]--;
  19453. taskCounts[ALL_TASKS_TYPE]--;
  19454. }
  19455. }
  19456. function getLastCallback() {
  19457. var cbInfo = taskCallbacks.pop();
  19458. return cbInfo && cbInfo.cb;
  19459. }
  19460. function getLastCallbackForType(taskType) {
  19461. for (var i = taskCallbacks.length - 1; i >= 0; --i) {
  19462. var cbInfo = taskCallbacks[i];
  19463. if (cbInfo.type === taskType) {
  19464. taskCallbacks.splice(i, 1);
  19465. return cbInfo.cb;
  19466. }
  19467. }
  19468. }
  19469. function incTaskCount(taskType) {
  19470. taskType = taskType || DEFAULT_TASK_TYPE;
  19471. taskCounts[taskType] = (taskCounts[taskType] || 0) + 1;
  19472. taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1;
  19473. }
  19474. function notifyWhenNoPendingTasks(callback, taskType) {
  19475. taskType = taskType || ALL_TASKS_TYPE;
  19476. if (!taskCounts[taskType]) {
  19477. callback();
  19478. } else {
  19479. taskCallbacks.push({type: taskType, cb: callback});
  19480. }
  19481. }
  19482. }
  19483. var $templateRequestMinErr = minErr('$templateRequest');
  19484. /**
  19485. * @ngdoc provider
  19486. * @name $templateRequestProvider
  19487. * @this
  19488. *
  19489. * @description
  19490. * Used to configure the options passed to the {@link $http} service when making a template request.
  19491. *
  19492. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  19493. * requesting a template.
  19494. */
  19495. function $TemplateRequestProvider() {
  19496. var httpOptions;
  19497. /**
  19498. * @ngdoc method
  19499. * @name $templateRequestProvider#httpOptions
  19500. * @description
  19501. * The options to be passed to the {@link $http} service when making the request.
  19502. * You can use this to override options such as the "Accept" header for template requests.
  19503. *
  19504. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  19505. * options if not overridden here.
  19506. *
  19507. * @param {string=} value new value for the {@link $http} options.
  19508. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  19509. */
  19510. this.httpOptions = function(val) {
  19511. if (val) {
  19512. httpOptions = val;
  19513. return this;
  19514. }
  19515. return httpOptions;
  19516. };
  19517. /**
  19518. * @ngdoc service
  19519. * @name $templateRequest
  19520. *
  19521. * @description
  19522. * The `$templateRequest` service runs security checks then downloads the provided template using
  19523. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  19524. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  19525. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  19526. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  19527. * when `tpl` is of type string and `$templateCache` has the matching entry.
  19528. *
  19529. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  19530. * can configure this via {@link $templateRequestProvider#httpOptions}.
  19531. *
  19532. * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such
  19533. * as {@link ngInclude} to download and cache templates.
  19534. *
  19535. * 3rd party modules should use `$templateRequest` if their services or directives are loading
  19536. * templates.
  19537. *
  19538. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  19539. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  19540. *
  19541. * @return {Promise} a promise for the HTTP response data of the given URL.
  19542. *
  19543. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  19544. */
  19545. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  19546. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  19547. function handleRequestFn(tpl, ignoreRequestError) {
  19548. handleRequestFn.totalPendingRequests++;
  19549. // We consider the template cache holds only trusted templates, so
  19550. // there's no need to go through adding the template again to the trusted
  19551. // resources for keys that already are included in there. This also makes
  19552. // AngularJS accept any script directive, no matter its name. However, we
  19553. // still need to unwrap trusted types.
  19554. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  19555. tpl = $sce.getTrustedResourceUrl(tpl);
  19556. }
  19557. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  19558. if (isArray(transformResponse)) {
  19559. transformResponse = transformResponse.filter(function(transformer) {
  19560. return transformer !== defaultHttpResponseTransform;
  19561. });
  19562. } else if (transformResponse === defaultHttpResponseTransform) {
  19563. transformResponse = null;
  19564. }
  19565. return $http.get(tpl, extend({
  19566. cache: $templateCache,
  19567. transformResponse: transformResponse
  19568. }, httpOptions))
  19569. .finally(function() {
  19570. handleRequestFn.totalPendingRequests--;
  19571. })
  19572. .then(function(response) {
  19573. return $templateCache.put(tpl, response.data);
  19574. }, handleError);
  19575. function handleError(resp) {
  19576. if (!ignoreRequestError) {
  19577. resp = $templateRequestMinErr('tpload',
  19578. 'Failed to load template: {0} (HTTP status: {1} {2})',
  19579. tpl, resp.status, resp.statusText);
  19580. $exceptionHandler(resp);
  19581. }
  19582. return $q.reject(resp);
  19583. }
  19584. }
  19585. handleRequestFn.totalPendingRequests = 0;
  19586. return handleRequestFn;
  19587. }
  19588. ];
  19589. }
  19590. /** @this */
  19591. function $$TestabilityProvider() {
  19592. this.$get = ['$rootScope', '$browser', '$location',
  19593. function($rootScope, $browser, $location) {
  19594. /**
  19595. * @name $testability
  19596. *
  19597. * @description
  19598. * The private $$testability service provides a collection of methods for use when debugging
  19599. * or by automated test and debugging tools.
  19600. */
  19601. var testability = {};
  19602. /**
  19603. * @name $$testability#findBindings
  19604. *
  19605. * @description
  19606. * Returns an array of elements that are bound (via ng-bind or {{}})
  19607. * to expressions matching the input.
  19608. *
  19609. * @param {Element} element The element root to search from.
  19610. * @param {string} expression The binding expression to match.
  19611. * @param {boolean} opt_exactMatch If true, only returns exact matches
  19612. * for the expression. Filters and whitespace are ignored.
  19613. */
  19614. testability.findBindings = function(element, expression, opt_exactMatch) {
  19615. var bindings = element.getElementsByClassName('ng-binding');
  19616. var matches = [];
  19617. forEach(bindings, function(binding) {
  19618. var dataBinding = angular.element(binding).data('$binding');
  19619. if (dataBinding) {
  19620. forEach(dataBinding, function(bindingName) {
  19621. if (opt_exactMatch) {
  19622. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  19623. if (matcher.test(bindingName)) {
  19624. matches.push(binding);
  19625. }
  19626. } else {
  19627. if (bindingName.indexOf(expression) !== -1) {
  19628. matches.push(binding);
  19629. }
  19630. }
  19631. });
  19632. }
  19633. });
  19634. return matches;
  19635. };
  19636. /**
  19637. * @name $$testability#findModels
  19638. *
  19639. * @description
  19640. * Returns an array of elements that are two-way found via ng-model to
  19641. * expressions matching the input.
  19642. *
  19643. * @param {Element} element The element root to search from.
  19644. * @param {string} expression The model expression to match.
  19645. * @param {boolean} opt_exactMatch If true, only returns exact matches
  19646. * for the expression.
  19647. */
  19648. testability.findModels = function(element, expression, opt_exactMatch) {
  19649. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  19650. for (var p = 0; p < prefixes.length; ++p) {
  19651. var attributeEquals = opt_exactMatch ? '=' : '*=';
  19652. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  19653. var elements = element.querySelectorAll(selector);
  19654. if (elements.length) {
  19655. return elements;
  19656. }
  19657. }
  19658. };
  19659. /**
  19660. * @name $$testability#getLocation
  19661. *
  19662. * @description
  19663. * Shortcut for getting the location in a browser agnostic way. Returns
  19664. * the path, search, and hash. (e.g. /path?a=b#hash)
  19665. */
  19666. testability.getLocation = function() {
  19667. return $location.url();
  19668. };
  19669. /**
  19670. * @name $$testability#setLocation
  19671. *
  19672. * @description
  19673. * Shortcut for navigating to a location without doing a full page reload.
  19674. *
  19675. * @param {string} url The location url (path, search and hash,
  19676. * e.g. /path?a=b#hash) to go to.
  19677. */
  19678. testability.setLocation = function(url) {
  19679. if (url !== $location.url()) {
  19680. $location.url(url);
  19681. $rootScope.$digest();
  19682. }
  19683. };
  19684. /**
  19685. * @name $$testability#whenStable
  19686. *
  19687. * @description
  19688. * Calls the callback when all pending tasks are completed.
  19689. *
  19690. * Types of tasks waited for include:
  19691. * - Pending timeouts (via {@link $timeout}).
  19692. * - Pending HTTP requests (via {@link $http}).
  19693. * - In-progress route transitions (via {@link $route}).
  19694. * - Pending tasks scheduled via {@link $rootScope#$applyAsync}.
  19695. * - Pending tasks scheduled via {@link $rootScope#$evalAsync}.
  19696. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises).
  19697. *
  19698. * @param {function} callback
  19699. */
  19700. testability.whenStable = function(callback) {
  19701. $browser.notifyWhenNoOutstandingRequests(callback);
  19702. };
  19703. return testability;
  19704. }];
  19705. }
  19706. var $timeoutMinErr = minErr('$timeout');
  19707. /** @this */
  19708. function $TimeoutProvider() {
  19709. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  19710. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  19711. var deferreds = {};
  19712. /**
  19713. * @ngdoc service
  19714. * @name $timeout
  19715. *
  19716. * @description
  19717. * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  19718. * block and delegates any exceptions to
  19719. * {@link ng.$exceptionHandler $exceptionHandler} service.
  19720. *
  19721. * The return value of calling `$timeout` is a promise, which will be resolved when
  19722. * the delay has passed and the timeout function, if provided, is executed.
  19723. *
  19724. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  19725. *
  19726. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  19727. * synchronously flush the queue of deferred functions.
  19728. *
  19729. * If you only want a promise that will be resolved after some specified delay
  19730. * then you can call `$timeout` without the `fn` function.
  19731. *
  19732. * @param {function()=} fn A function, whose execution should be delayed.
  19733. * @param {number=} [delay=0] Delay in milliseconds.
  19734. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  19735. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  19736. * @param {...*=} Pass additional parameters to the executed function.
  19737. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  19738. * will be resolved with the return value of the `fn` function.
  19739. *
  19740. */
  19741. function timeout(fn, delay, invokeApply) {
  19742. if (!isFunction(fn)) {
  19743. invokeApply = delay;
  19744. delay = fn;
  19745. fn = noop;
  19746. }
  19747. var args = sliceArgs(arguments, 3),
  19748. skipApply = (isDefined(invokeApply) && !invokeApply),
  19749. deferred = (skipApply ? $$q : $q).defer(),
  19750. promise = deferred.promise,
  19751. timeoutId;
  19752. timeoutId = $browser.defer(function() {
  19753. try {
  19754. deferred.resolve(fn.apply(null, args));
  19755. } catch (e) {
  19756. deferred.reject(e);
  19757. $exceptionHandler(e);
  19758. } finally {
  19759. delete deferreds[promise.$$timeoutId];
  19760. }
  19761. if (!skipApply) $rootScope.$apply();
  19762. }, delay, '$timeout');
  19763. promise.$$timeoutId = timeoutId;
  19764. deferreds[timeoutId] = deferred;
  19765. return promise;
  19766. }
  19767. /**
  19768. * @ngdoc method
  19769. * @name $timeout#cancel
  19770. *
  19771. * @description
  19772. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  19773. * resolved with a rejection.
  19774. *
  19775. * @param {Promise=} promise Promise returned by the `$timeout` function.
  19776. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  19777. * canceled.
  19778. */
  19779. timeout.cancel = function(promise) {
  19780. if (!promise) return false;
  19781. if (!promise.hasOwnProperty('$$timeoutId')) {
  19782. throw $timeoutMinErr('badprom',
  19783. '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.');
  19784. }
  19785. if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false;
  19786. var id = promise.$$timeoutId;
  19787. var deferred = deferreds[id];
  19788. // Timeout cancels should not report an unhandled promise.
  19789. markQExceptionHandled(deferred.promise);
  19790. deferred.reject('canceled');
  19791. delete deferreds[id];
  19792. return $browser.defer.cancel(id);
  19793. };
  19794. return timeout;
  19795. }];
  19796. }
  19797. // NOTE: The usage of window and document instead of $window and $document here is
  19798. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  19799. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  19800. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  19801. // doesn't know about mocked locations and resolves URLs to the real document - which is
  19802. // exactly the behavior needed here. There is little value is mocking these out for this
  19803. // service.
  19804. var urlParsingNode = window.document.createElement('a');
  19805. var originUrl = urlResolve(window.location.href);
  19806. var baseUrlParsingNode;
  19807. urlParsingNode.href = 'http://[::1]';
  19808. // Support: IE 9-11 only, Edge 16-17 only (fixed in 18 Preview)
  19809. // IE/Edge don't wrap IPv6 addresses' hostnames in square brackets
  19810. // when parsed out of an anchor element.
  19811. var ipv6InBrackets = urlParsingNode.hostname === '[::1]';
  19812. /**
  19813. *
  19814. * Implementation Notes for non-IE browsers
  19815. * ----------------------------------------
  19816. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  19817. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  19818. * URL will be resolved into an absolute URL in the context of the application document.
  19819. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  19820. * properties are all populated to reflect the normalized URL. This approach has wide
  19821. * compatibility - Safari 1+, Mozilla 1+ etc. See
  19822. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  19823. *
  19824. * Implementation Notes for IE
  19825. * ---------------------------
  19826. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  19827. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  19828. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  19829. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  19830. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  19831. * properties such as protocol, hostname, port, etc.
  19832. *
  19833. * References:
  19834. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  19835. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  19836. * http://url.spec.whatwg.org/#urlutils
  19837. * https://github.com/angular/angular.js/pull/2902
  19838. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  19839. *
  19840. * @kind function
  19841. * @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned
  19842. * unchanged.
  19843. * @description Normalizes and parses a URL.
  19844. * @returns {object} Returns the normalized URL as a dictionary.
  19845. *
  19846. * | member name | Description |
  19847. * |---------------|------------------------------------------------------------------------|
  19848. * | href | A normalized version of the provided URL if it was not an absolute URL |
  19849. * | protocol | The protocol without the trailing colon |
  19850. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  19851. * | search | The search params, minus the question mark |
  19852. * | hash | The hash string, minus the hash symbol |
  19853. * | hostname | The hostname |
  19854. * | port | The port, without ":" |
  19855. * | pathname | The pathname, beginning with "/" |
  19856. *
  19857. */
  19858. function urlResolve(url) {
  19859. if (!isString(url)) return url;
  19860. var href = url;
  19861. // Support: IE 9-11 only
  19862. if (msie) {
  19863. // Normalize before parse. Refer Implementation Notes on why this is
  19864. // done in two steps on IE.
  19865. urlParsingNode.setAttribute('href', href);
  19866. href = urlParsingNode.href;
  19867. }
  19868. urlParsingNode.setAttribute('href', href);
  19869. var hostname = urlParsingNode.hostname;
  19870. if (!ipv6InBrackets && hostname.indexOf(':') > -1) {
  19871. hostname = '[' + hostname + ']';
  19872. }
  19873. return {
  19874. href: urlParsingNode.href,
  19875. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  19876. host: urlParsingNode.host,
  19877. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  19878. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  19879. hostname: hostname,
  19880. port: urlParsingNode.port,
  19881. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  19882. ? urlParsingNode.pathname
  19883. : '/' + urlParsingNode.pathname
  19884. };
  19885. }
  19886. /**
  19887. * Parse a request URL and determine whether this is a same-origin request as the application
  19888. * document.
  19889. *
  19890. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  19891. * or a parsed URL object.
  19892. * @returns {boolean} Whether the request is for the same origin as the application document.
  19893. */
  19894. function urlIsSameOrigin(requestUrl) {
  19895. return urlsAreSameOrigin(requestUrl, originUrl);
  19896. }
  19897. /**
  19898. * Parse a request URL and determine whether it is same-origin as the current document base URL.
  19899. *
  19900. * Note: The base URL is usually the same as the document location (`location.href`) but can
  19901. * be overriden by using the `<base>` tag.
  19902. *
  19903. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  19904. * or a parsed URL object.
  19905. * @returns {boolean} Whether the URL is same-origin as the document base URL.
  19906. */
  19907. function urlIsSameOriginAsBaseUrl(requestUrl) {
  19908. return urlsAreSameOrigin(requestUrl, getBaseUrl());
  19909. }
  19910. /**
  19911. * Create a function that can check a URL's origin against a list of allowed/trusted origins.
  19912. * The current location's origin is implicitly trusted.
  19913. *
  19914. * @param {string[]} trustedOriginUrls - A list of URLs (strings), whose origins are trusted.
  19915. *
  19916. * @returns {Function} - A function that receives a URL (string or parsed URL object) and returns
  19917. * whether it is of an allowed origin.
  19918. */
  19919. function urlIsAllowedOriginFactory(trustedOriginUrls) {
  19920. var parsedAllowedOriginUrls = [originUrl].concat(trustedOriginUrls.map(urlResolve));
  19921. /**
  19922. * Check whether the specified URL (string or parsed URL object) has an origin that is allowed
  19923. * based on a list of trusted-origin URLs. The current location's origin is implicitly
  19924. * trusted.
  19925. *
  19926. * @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be
  19927. * resolved or a parsed URL object).
  19928. *
  19929. * @returns {boolean} - Whether the specified URL is of an allowed origin.
  19930. */
  19931. return function urlIsAllowedOrigin(requestUrl) {
  19932. var parsedUrl = urlResolve(requestUrl);
  19933. return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl));
  19934. };
  19935. }
  19936. /**
  19937. * Determine if two URLs share the same origin.
  19938. *
  19939. * @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of
  19940. * a dictionary object returned by `urlResolve()`.
  19941. * @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form
  19942. * of a dictionary object returned by `urlResolve()`.
  19943. *
  19944. * @returns {boolean} - True if both URLs have the same origin, and false otherwise.
  19945. */
  19946. function urlsAreSameOrigin(url1, url2) {
  19947. url1 = urlResolve(url1);
  19948. url2 = urlResolve(url2);
  19949. return (url1.protocol === url2.protocol &&
  19950. url1.host === url2.host);
  19951. }
  19952. /**
  19953. * Returns the current document base URL.
  19954. * @returns {string}
  19955. */
  19956. function getBaseUrl() {
  19957. if (window.document.baseURI) {
  19958. return window.document.baseURI;
  19959. }
  19960. // `document.baseURI` is available everywhere except IE
  19961. if (!baseUrlParsingNode) {
  19962. baseUrlParsingNode = window.document.createElement('a');
  19963. baseUrlParsingNode.href = '.';
  19964. // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not
  19965. // suitable here because we need to track changes to the base URL.
  19966. baseUrlParsingNode = baseUrlParsingNode.cloneNode(false);
  19967. }
  19968. return baseUrlParsingNode.href;
  19969. }
  19970. /**
  19971. * @ngdoc service
  19972. * @name $window
  19973. * @this
  19974. *
  19975. * @description
  19976. * A reference to the browser's `window` object. While `window`
  19977. * is globally available in JavaScript, it causes testability problems, because
  19978. * it is a global variable. In AngularJS we always refer to it through the
  19979. * `$window` service, so it may be overridden, removed or mocked for testing.
  19980. *
  19981. * Expressions, like the one defined for the `ngClick` directive in the example
  19982. * below, are evaluated with respect to the current scope. Therefore, there is
  19983. * no risk of inadvertently coding in a dependency on a global value in such an
  19984. * expression.
  19985. *
  19986. * @example
  19987. <example module="windowExample" name="window-service">
  19988. <file name="index.html">
  19989. <script>
  19990. angular.module('windowExample', [])
  19991. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  19992. $scope.greeting = 'Hello, World!';
  19993. $scope.doGreeting = function(greeting) {
  19994. $window.alert(greeting);
  19995. };
  19996. }]);
  19997. </script>
  19998. <div ng-controller="ExampleController">
  19999. <input type="text" ng-model="greeting" aria-label="greeting" />
  20000. <button ng-click="doGreeting(greeting)">ALERT</button>
  20001. </div>
  20002. </file>
  20003. <file name="protractor.js" type="protractor">
  20004. it('should display the greeting in the input box', function() {
  20005. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  20006. // If we click the button it will block the test runner
  20007. // element(':button').click();
  20008. });
  20009. </file>
  20010. </example>
  20011. */
  20012. function $WindowProvider() {
  20013. this.$get = valueFn(window);
  20014. }
  20015. /**
  20016. * @name $$cookieReader
  20017. * @requires $document
  20018. *
  20019. * @description
  20020. * This is a private service for reading cookies used by $http and ngCookies
  20021. *
  20022. * @return {Object} a key/value map of the current cookies
  20023. */
  20024. function $$CookieReader($document) {
  20025. var rawDocument = $document[0] || {};
  20026. var lastCookies = {};
  20027. var lastCookieString = '';
  20028. function safeGetCookie(rawDocument) {
  20029. try {
  20030. return rawDocument.cookie || '';
  20031. } catch (e) {
  20032. return '';
  20033. }
  20034. }
  20035. function safeDecodeURIComponent(str) {
  20036. try {
  20037. return decodeURIComponent(str);
  20038. } catch (e) {
  20039. return str;
  20040. }
  20041. }
  20042. return function() {
  20043. var cookieArray, cookie, i, index, name;
  20044. var currentCookieString = safeGetCookie(rawDocument);
  20045. if (currentCookieString !== lastCookieString) {
  20046. lastCookieString = currentCookieString;
  20047. cookieArray = lastCookieString.split('; ');
  20048. lastCookies = {};
  20049. for (i = 0; i < cookieArray.length; i++) {
  20050. cookie = cookieArray[i];
  20051. index = cookie.indexOf('=');
  20052. if (index > 0) { //ignore nameless cookies
  20053. name = safeDecodeURIComponent(cookie.substring(0, index));
  20054. // the first value that is seen for a cookie is the most
  20055. // specific one. values for the same cookie name that
  20056. // follow are for less specific paths.
  20057. if (isUndefined(lastCookies[name])) {
  20058. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  20059. }
  20060. }
  20061. }
  20062. }
  20063. return lastCookies;
  20064. };
  20065. }
  20066. $$CookieReader.$inject = ['$document'];
  20067. /** @this */
  20068. function $$CookieReaderProvider() {
  20069. this.$get = $$CookieReader;
  20070. }
  20071. /* global currencyFilter: true,
  20072. dateFilter: true,
  20073. filterFilter: true,
  20074. jsonFilter: true,
  20075. limitToFilter: true,
  20076. lowercaseFilter: true,
  20077. numberFilter: true,
  20078. orderByFilter: true,
  20079. uppercaseFilter: true,
  20080. */
  20081. /**
  20082. * @ngdoc provider
  20083. * @name $filterProvider
  20084. * @description
  20085. *
  20086. * Filters are just functions which transform input to an output. However filters need to be
  20087. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  20088. * annotated with dependencies and is responsible for creating a filter function.
  20089. *
  20090. * <div class="alert alert-warning">
  20091. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  20092. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  20093. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  20094. * (`myapp_subsection_filterx`).
  20095. * </div>
  20096. *
  20097. * ```js
  20098. * // Filter registration
  20099. * function MyModule($provide, $filterProvider) {
  20100. * // create a service to demonstrate injection (not always needed)
  20101. * $provide.value('greet', function(name){
  20102. * return 'Hello ' + name + '!';
  20103. * });
  20104. *
  20105. * // register a filter factory which uses the
  20106. * // greet service to demonstrate DI.
  20107. * $filterProvider.register('greet', function(greet){
  20108. * // return the filter function which uses the greet service
  20109. * // to generate salutation
  20110. * return function(text) {
  20111. * // filters need to be forgiving so check input validity
  20112. * return text && greet(text) || text;
  20113. * };
  20114. * });
  20115. * }
  20116. * ```
  20117. *
  20118. * The filter function is registered with the `$injector` under the filter name suffix with
  20119. * `Filter`.
  20120. *
  20121. * ```js
  20122. * it('should be the same instance', inject(
  20123. * function($filterProvider) {
  20124. * $filterProvider.register('reverse', function(){
  20125. * return ...;
  20126. * });
  20127. * },
  20128. * function($filter, reverseFilter) {
  20129. * expect($filter('reverse')).toBe(reverseFilter);
  20130. * });
  20131. * ```
  20132. *
  20133. *
  20134. * For more information about how AngularJS filters work, and how to create your own filters, see
  20135. * {@link guide/filter Filters} in the AngularJS Developer Guide.
  20136. */
  20137. /**
  20138. * @ngdoc service
  20139. * @name $filter
  20140. * @kind function
  20141. * @description
  20142. * Filters are used for formatting data displayed to the user.
  20143. *
  20144. * They can be used in view templates, controllers or services. AngularJS comes
  20145. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  20146. * define your own as well.
  20147. *
  20148. * The general syntax in templates is as follows:
  20149. *
  20150. * ```html
  20151. * {{ expression [| filter_name[:parameter_value] ... ] }}
  20152. * ```
  20153. *
  20154. * @param {String} name Name of the filter function to retrieve
  20155. * @return {Function} the filter function
  20156. * @example
  20157. <example name="$filter" module="filterExample">
  20158. <file name="index.html">
  20159. <div ng-controller="MainCtrl">
  20160. <h3>{{ originalText }}</h3>
  20161. <h3>{{ filteredText }}</h3>
  20162. </div>
  20163. </file>
  20164. <file name="script.js">
  20165. angular.module('filterExample', [])
  20166. .controller('MainCtrl', function($scope, $filter) {
  20167. $scope.originalText = 'hello';
  20168. $scope.filteredText = $filter('uppercase')($scope.originalText);
  20169. });
  20170. </file>
  20171. </example>
  20172. */
  20173. $FilterProvider.$inject = ['$provide'];
  20174. /** @this */
  20175. function $FilterProvider($provide) {
  20176. var suffix = 'Filter';
  20177. /**
  20178. * @ngdoc method
  20179. * @name $filterProvider#register
  20180. * @param {string|Object} name Name of the filter function, or an object map of filters where
  20181. * the keys are the filter names and the values are the filter factories.
  20182. *
  20183. * <div class="alert alert-warning">
  20184. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  20185. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  20186. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  20187. * (`myapp_subsection_filterx`).
  20188. * </div>
  20189. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  20190. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  20191. * of the registered filter instances.
  20192. */
  20193. function register(name, factory) {
  20194. if (isObject(name)) {
  20195. var filters = {};
  20196. forEach(name, function(filter, key) {
  20197. filters[key] = register(key, filter);
  20198. });
  20199. return filters;
  20200. } else {
  20201. return $provide.factory(name + suffix, factory);
  20202. }
  20203. }
  20204. this.register = register;
  20205. this.$get = ['$injector', function($injector) {
  20206. return function(name) {
  20207. return $injector.get(name + suffix);
  20208. };
  20209. }];
  20210. ////////////////////////////////////////
  20211. /* global
  20212. currencyFilter: false,
  20213. dateFilter: false,
  20214. filterFilter: false,
  20215. jsonFilter: false,
  20216. limitToFilter: false,
  20217. lowercaseFilter: false,
  20218. numberFilter: false,
  20219. orderByFilter: false,
  20220. uppercaseFilter: false
  20221. */
  20222. register('currency', currencyFilter);
  20223. register('date', dateFilter);
  20224. register('filter', filterFilter);
  20225. register('json', jsonFilter);
  20226. register('limitTo', limitToFilter);
  20227. register('lowercase', lowercaseFilter);
  20228. register('number', numberFilter);
  20229. register('orderBy', orderByFilter);
  20230. register('uppercase', uppercaseFilter);
  20231. }
  20232. /**
  20233. * @ngdoc filter
  20234. * @name filter
  20235. * @kind function
  20236. *
  20237. * @description
  20238. * Selects a subset of items from `array` and returns it as a new array.
  20239. *
  20240. * @param {Array} array The source array.
  20241. * <div class="alert alert-info">
  20242. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  20243. * </div>
  20244. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  20245. * `array`.
  20246. *
  20247. * Can be one of:
  20248. *
  20249. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  20250. * objects with string properties in `array` that match this string will be returned. This also
  20251. * applies to nested object properties.
  20252. * The predicate can be negated by prefixing the string with `!`.
  20253. *
  20254. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  20255. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  20256. * which have property `name` containing "M" and property `phone` containing "1". A special
  20257. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  20258. * against any property of the object or its nested object properties. That's equivalent to the
  20259. * simple substring match with a `string` as described above. The special property name can be
  20260. * overwritten, using the `anyPropertyKey` parameter.
  20261. * The predicate can be negated by prefixing the string with `!`.
  20262. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  20263. * not containing "M".
  20264. *
  20265. * Note that a named property will match properties on the same level only, while the special
  20266. * `$` property will match properties on the same level or deeper. E.g. an array item like
  20267. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  20268. * **will** be matched by `{$: 'John'}`.
  20269. *
  20270. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  20271. * The function is called for each element of the array, with the element, its index, and
  20272. * the entire array itself as arguments.
  20273. *
  20274. * The final result is an array of those elements that the predicate returned true for.
  20275. *
  20276. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  20277. * determining if values retrieved using `expression` (when it is not a function) should be
  20278. * considered a match based on the expected value (from the filter expression) and actual
  20279. * value (from the object in the array).
  20280. *
  20281. * Can be one of:
  20282. *
  20283. * - `function(actual, expected)`:
  20284. * The function will be given the object value and the predicate value to compare and
  20285. * should return true if both values should be considered equal.
  20286. *
  20287. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  20288. * This is essentially strict comparison of expected and actual.
  20289. *
  20290. * - `false`: A short hand for a function which will look for a substring match in a case
  20291. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  20292. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  20293. *
  20294. *
  20295. * Defaults to `false`.
  20296. *
  20297. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  20298. * By default `$`.
  20299. *
  20300. * @example
  20301. <example name="filter-filter">
  20302. <file name="index.html">
  20303. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  20304. {name:'Mary', phone:'800-BIG-MARY'},
  20305. {name:'Mike', phone:'555-4321'},
  20306. {name:'Adam', phone:'555-5678'},
  20307. {name:'Julie', phone:'555-8765'},
  20308. {name:'Juliette', phone:'555-5678'}]"></div>
  20309. <label>Search: <input ng-model="searchText"></label>
  20310. <table id="searchTextResults">
  20311. <tr><th>Name</th><th>Phone</th></tr>
  20312. <tr ng-repeat="friend in friends | filter:searchText">
  20313. <td>{{friend.name}}</td>
  20314. <td>{{friend.phone}}</td>
  20315. </tr>
  20316. </table>
  20317. <hr>
  20318. <label>Any: <input ng-model="search.$"></label> <br>
  20319. <label>Name only <input ng-model="search.name"></label><br>
  20320. <label>Phone only <input ng-model="search.phone"></label><br>
  20321. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  20322. <table id="searchObjResults">
  20323. <tr><th>Name</th><th>Phone</th></tr>
  20324. <tr ng-repeat="friendObj in friends | filter:search:strict">
  20325. <td>{{friendObj.name}}</td>
  20326. <td>{{friendObj.phone}}</td>
  20327. </tr>
  20328. </table>
  20329. </file>
  20330. <file name="protractor.js" type="protractor">
  20331. var expectFriendNames = function(expectedNames, key) {
  20332. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  20333. arr.forEach(function(wd, i) {
  20334. expect(wd.getText()).toMatch(expectedNames[i]);
  20335. });
  20336. });
  20337. };
  20338. it('should search across all fields when filtering with a string', function() {
  20339. var searchText = element(by.model('searchText'));
  20340. searchText.clear();
  20341. searchText.sendKeys('m');
  20342. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  20343. searchText.clear();
  20344. searchText.sendKeys('76');
  20345. expectFriendNames(['John', 'Julie'], 'friend');
  20346. });
  20347. it('should search in specific fields when filtering with a predicate object', function() {
  20348. var searchAny = element(by.model('search.$'));
  20349. searchAny.clear();
  20350. searchAny.sendKeys('i');
  20351. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  20352. });
  20353. it('should use a equal comparison when comparator is true', function() {
  20354. var searchName = element(by.model('search.name'));
  20355. var strict = element(by.model('strict'));
  20356. searchName.clear();
  20357. searchName.sendKeys('Julie');
  20358. strict.click();
  20359. expectFriendNames(['Julie'], 'friendObj');
  20360. });
  20361. </file>
  20362. </example>
  20363. */
  20364. function filterFilter() {
  20365. return function(array, expression, comparator, anyPropertyKey) {
  20366. if (!isArrayLike(array)) {
  20367. if (array == null) {
  20368. return array;
  20369. } else {
  20370. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  20371. }
  20372. }
  20373. anyPropertyKey = anyPropertyKey || '$';
  20374. var expressionType = getTypeForFilter(expression);
  20375. var predicateFn;
  20376. var matchAgainstAnyProp;
  20377. switch (expressionType) {
  20378. case 'function':
  20379. predicateFn = expression;
  20380. break;
  20381. case 'boolean':
  20382. case 'null':
  20383. case 'number':
  20384. case 'string':
  20385. matchAgainstAnyProp = true;
  20386. // falls through
  20387. case 'object':
  20388. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  20389. break;
  20390. default:
  20391. return array;
  20392. }
  20393. return Array.prototype.filter.call(array, predicateFn);
  20394. };
  20395. }
  20396. // Helper functions for `filterFilter`
  20397. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  20398. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  20399. var predicateFn;
  20400. if (comparator === true) {
  20401. comparator = equals;
  20402. } else if (!isFunction(comparator)) {
  20403. comparator = function(actual, expected) {
  20404. if (isUndefined(actual)) {
  20405. // No substring matching against `undefined`
  20406. return false;
  20407. }
  20408. if ((actual === null) || (expected === null)) {
  20409. // No substring matching against `null`; only match against `null`
  20410. return actual === expected;
  20411. }
  20412. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  20413. // Should not compare primitives against objects, unless they have custom `toString` method
  20414. return false;
  20415. }
  20416. actual = lowercase('' + actual);
  20417. expected = lowercase('' + expected);
  20418. return actual.indexOf(expected) !== -1;
  20419. };
  20420. }
  20421. predicateFn = function(item) {
  20422. if (shouldMatchPrimitives && !isObject(item)) {
  20423. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  20424. }
  20425. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  20426. };
  20427. return predicateFn;
  20428. }
  20429. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  20430. var actualType = getTypeForFilter(actual);
  20431. var expectedType = getTypeForFilter(expected);
  20432. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  20433. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  20434. } else if (isArray(actual)) {
  20435. // In case `actual` is an array, consider it a match
  20436. // if ANY of it's items matches `expected`
  20437. return actual.some(function(item) {
  20438. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  20439. });
  20440. }
  20441. switch (actualType) {
  20442. case 'object':
  20443. var key;
  20444. if (matchAgainstAnyProp) {
  20445. for (key in actual) {
  20446. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  20447. // See: https://github.com/angular/angular.js/issues/15644
  20448. if (key.charAt && (key.charAt(0) !== '$') &&
  20449. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  20450. return true;
  20451. }
  20452. }
  20453. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  20454. } else if (expectedType === 'object') {
  20455. for (key in expected) {
  20456. var expectedVal = expected[key];
  20457. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  20458. continue;
  20459. }
  20460. var matchAnyProperty = key === anyPropertyKey;
  20461. var actualVal = matchAnyProperty ? actual : actual[key];
  20462. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  20463. return false;
  20464. }
  20465. }
  20466. return true;
  20467. } else {
  20468. return comparator(actual, expected);
  20469. }
  20470. case 'function':
  20471. return false;
  20472. default:
  20473. return comparator(actual, expected);
  20474. }
  20475. }
  20476. // Used for easily differentiating between `null` and actual `object`
  20477. function getTypeForFilter(val) {
  20478. return (val === null) ? 'null' : typeof val;
  20479. }
  20480. var MAX_DIGITS = 22;
  20481. var DECIMAL_SEP = '.';
  20482. var ZERO_CHAR = '0';
  20483. /**
  20484. * @ngdoc filter
  20485. * @name currency
  20486. * @kind function
  20487. *
  20488. * @description
  20489. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  20490. * symbol for current locale is used.
  20491. *
  20492. * @param {number} amount Input to filter.
  20493. * @param {string=} symbol Currency symbol or identifier to be displayed.
  20494. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  20495. * @returns {string} Formatted number.
  20496. *
  20497. *
  20498. * @example
  20499. <example module="currencyExample" name="currency-filter">
  20500. <file name="index.html">
  20501. <script>
  20502. angular.module('currencyExample', [])
  20503. .controller('ExampleController', ['$scope', function($scope) {
  20504. $scope.amount = 1234.56;
  20505. }]);
  20506. </script>
  20507. <div ng-controller="ExampleController">
  20508. <input type="number" ng-model="amount" aria-label="amount"> <br>
  20509. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  20510. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  20511. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  20512. </div>
  20513. </file>
  20514. <file name="protractor.js" type="protractor">
  20515. it('should init with 1234.56', function() {
  20516. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  20517. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  20518. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  20519. });
  20520. it('should update', function() {
  20521. if (browser.params.browser === 'safari') {
  20522. // Safari does not understand the minus key. See
  20523. // https://github.com/angular/protractor/issues/481
  20524. return;
  20525. }
  20526. element(by.model('amount')).clear();
  20527. element(by.model('amount')).sendKeys('-1234');
  20528. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  20529. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  20530. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  20531. });
  20532. </file>
  20533. </example>
  20534. */
  20535. currencyFilter.$inject = ['$locale'];
  20536. function currencyFilter($locale) {
  20537. var formats = $locale.NUMBER_FORMATS;
  20538. return function(amount, currencySymbol, fractionSize) {
  20539. if (isUndefined(currencySymbol)) {
  20540. currencySymbol = formats.CURRENCY_SYM;
  20541. }
  20542. if (isUndefined(fractionSize)) {
  20543. fractionSize = formats.PATTERNS[1].maxFrac;
  20544. }
  20545. // If the currency symbol is empty, trim whitespace around the symbol
  20546. var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g;
  20547. // if null or undefined pass it through
  20548. return (amount == null)
  20549. ? amount
  20550. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  20551. replace(currencySymbolRe, currencySymbol);
  20552. };
  20553. }
  20554. /**
  20555. * @ngdoc filter
  20556. * @name number
  20557. * @kind function
  20558. *
  20559. * @description
  20560. * Formats a number as text.
  20561. *
  20562. * If the input is null or undefined, it will just be returned.
  20563. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  20564. * If the input is not a number an empty string is returned.
  20565. *
  20566. *
  20567. * @param {number|string} number Number to format.
  20568. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  20569. * If this is not provided then the fraction size is computed from the current locale's number
  20570. * formatting pattern. In the case of the default locale, it will be 3.
  20571. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  20572. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  20573. * include "," group separators after each third digit).
  20574. *
  20575. * @example
  20576. <example module="numberFilterExample" name="number-filter">
  20577. <file name="index.html">
  20578. <script>
  20579. angular.module('numberFilterExample', [])
  20580. .controller('ExampleController', ['$scope', function($scope) {
  20581. $scope.val = 1234.56789;
  20582. }]);
  20583. </script>
  20584. <div ng-controller="ExampleController">
  20585. <label>Enter number: <input ng-model='val'></label><br>
  20586. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  20587. No fractions: <span>{{val | number:0}}</span><br>
  20588. Negative number: <span>{{-val | number:4}}</span>
  20589. </div>
  20590. </file>
  20591. <file name="protractor.js" type="protractor">
  20592. it('should format numbers', function() {
  20593. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  20594. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  20595. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  20596. });
  20597. it('should update', function() {
  20598. element(by.model('val')).clear();
  20599. element(by.model('val')).sendKeys('3374.333');
  20600. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  20601. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  20602. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  20603. });
  20604. </file>
  20605. </example>
  20606. */
  20607. numberFilter.$inject = ['$locale'];
  20608. function numberFilter($locale) {
  20609. var formats = $locale.NUMBER_FORMATS;
  20610. return function(number, fractionSize) {
  20611. // if null or undefined pass it through
  20612. return (number == null)
  20613. ? number
  20614. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  20615. fractionSize);
  20616. };
  20617. }
  20618. /**
  20619. * Parse a number (as a string) into three components that can be used
  20620. * for formatting the number.
  20621. *
  20622. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  20623. *
  20624. * @param {string} numStr The number to parse
  20625. * @return {object} An object describing this number, containing the following keys:
  20626. * - d : an array of digits containing leading zeros as necessary
  20627. * - i : the number of the digits in `d` that are to the left of the decimal point
  20628. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  20629. *
  20630. */
  20631. function parse(numStr) {
  20632. var exponent = 0, digits, numberOfIntegerDigits;
  20633. var i, j, zeros;
  20634. // Decimal point?
  20635. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  20636. numStr = numStr.replace(DECIMAL_SEP, '');
  20637. }
  20638. // Exponential form?
  20639. if ((i = numStr.search(/e/i)) > 0) {
  20640. // Work out the exponent.
  20641. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  20642. numberOfIntegerDigits += +numStr.slice(i + 1);
  20643. numStr = numStr.substring(0, i);
  20644. } else if (numberOfIntegerDigits < 0) {
  20645. // There was no decimal point or exponent so it is an integer.
  20646. numberOfIntegerDigits = numStr.length;
  20647. }
  20648. // Count the number of leading zeros.
  20649. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  20650. if (i === (zeros = numStr.length)) {
  20651. // The digits are all zero.
  20652. digits = [0];
  20653. numberOfIntegerDigits = 1;
  20654. } else {
  20655. // Count the number of trailing zeros
  20656. zeros--;
  20657. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  20658. // Trailing zeros are insignificant so ignore them
  20659. numberOfIntegerDigits -= i;
  20660. digits = [];
  20661. // Convert string to array of digits without leading/trailing zeros.
  20662. for (j = 0; i <= zeros; i++, j++) {
  20663. digits[j] = +numStr.charAt(i);
  20664. }
  20665. }
  20666. // If the number overflows the maximum allowed digits then use an exponent.
  20667. if (numberOfIntegerDigits > MAX_DIGITS) {
  20668. digits = digits.splice(0, MAX_DIGITS - 1);
  20669. exponent = numberOfIntegerDigits - 1;
  20670. numberOfIntegerDigits = 1;
  20671. }
  20672. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  20673. }
  20674. /**
  20675. * Round the parsed number to the specified number of decimal places
  20676. * This function changed the parsedNumber in-place
  20677. */
  20678. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  20679. var digits = parsedNumber.d;
  20680. var fractionLen = digits.length - parsedNumber.i;
  20681. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  20682. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  20683. // The index of the digit to where rounding is to occur
  20684. var roundAt = fractionSize + parsedNumber.i;
  20685. var digit = digits[roundAt];
  20686. if (roundAt > 0) {
  20687. // Drop fractional digits beyond `roundAt`
  20688. digits.splice(Math.max(parsedNumber.i, roundAt));
  20689. // Set non-fractional digits beyond `roundAt` to 0
  20690. for (var j = roundAt; j < digits.length; j++) {
  20691. digits[j] = 0;
  20692. }
  20693. } else {
  20694. // We rounded to zero so reset the parsedNumber
  20695. fractionLen = Math.max(0, fractionLen);
  20696. parsedNumber.i = 1;
  20697. digits.length = Math.max(1, roundAt = fractionSize + 1);
  20698. digits[0] = 0;
  20699. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  20700. }
  20701. if (digit >= 5) {
  20702. if (roundAt - 1 < 0) {
  20703. for (var k = 0; k > roundAt; k--) {
  20704. digits.unshift(0);
  20705. parsedNumber.i++;
  20706. }
  20707. digits.unshift(1);
  20708. parsedNumber.i++;
  20709. } else {
  20710. digits[roundAt - 1]++;
  20711. }
  20712. }
  20713. // Pad out with zeros to get the required fraction length
  20714. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  20715. // Do any carrying, e.g. a digit was rounded up to 10
  20716. var carry = digits.reduceRight(function(carry, d, i, digits) {
  20717. d = d + carry;
  20718. digits[i] = d % 10;
  20719. return Math.floor(d / 10);
  20720. }, 0);
  20721. if (carry) {
  20722. digits.unshift(carry);
  20723. parsedNumber.i++;
  20724. }
  20725. }
  20726. /**
  20727. * Format a number into a string
  20728. * @param {number} number The number to format
  20729. * @param {{
  20730. * minFrac, // the minimum number of digits required in the fraction part of the number
  20731. * maxFrac, // the maximum number of digits required in the fraction part of the number
  20732. * gSize, // number of digits in each group of separated digits
  20733. * lgSize, // number of digits in the last group of digits before the decimal separator
  20734. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  20735. * posPre, // the string to go in front of a positive number
  20736. * negSuf, // the string to go after a negative number (e.g. `)`)
  20737. * posSuf // the string to go after a positive number
  20738. * }} pattern
  20739. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  20740. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  20741. * @param {[type]} fractionSize The size of the fractional part of the number
  20742. * @return {string} The number formatted as a string
  20743. */
  20744. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  20745. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  20746. var isInfinity = !isFinite(number);
  20747. var isZero = false;
  20748. var numStr = Math.abs(number) + '',
  20749. formattedText = '',
  20750. parsedNumber;
  20751. if (isInfinity) {
  20752. formattedText = '\u221e';
  20753. } else {
  20754. parsedNumber = parse(numStr);
  20755. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  20756. var digits = parsedNumber.d;
  20757. var integerLen = parsedNumber.i;
  20758. var exponent = parsedNumber.e;
  20759. var decimals = [];
  20760. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  20761. // pad zeros for small numbers
  20762. while (integerLen < 0) {
  20763. digits.unshift(0);
  20764. integerLen++;
  20765. }
  20766. // extract decimals digits
  20767. if (integerLen > 0) {
  20768. decimals = digits.splice(integerLen, digits.length);
  20769. } else {
  20770. decimals = digits;
  20771. digits = [0];
  20772. }
  20773. // format the integer digits with grouping separators
  20774. var groups = [];
  20775. if (digits.length >= pattern.lgSize) {
  20776. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  20777. }
  20778. while (digits.length > pattern.gSize) {
  20779. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  20780. }
  20781. if (digits.length) {
  20782. groups.unshift(digits.join(''));
  20783. }
  20784. formattedText = groups.join(groupSep);
  20785. // append the decimal digits
  20786. if (decimals.length) {
  20787. formattedText += decimalSep + decimals.join('');
  20788. }
  20789. if (exponent) {
  20790. formattedText += 'e+' + exponent;
  20791. }
  20792. }
  20793. if (number < 0 && !isZero) {
  20794. return pattern.negPre + formattedText + pattern.negSuf;
  20795. } else {
  20796. return pattern.posPre + formattedText + pattern.posSuf;
  20797. }
  20798. }
  20799. function padNumber(num, digits, trim, negWrap) {
  20800. var neg = '';
  20801. if (num < 0 || (negWrap && num <= 0)) {
  20802. if (negWrap) {
  20803. num = -num + 1;
  20804. } else {
  20805. num = -num;
  20806. neg = '-';
  20807. }
  20808. }
  20809. num = '' + num;
  20810. while (num.length < digits) num = ZERO_CHAR + num;
  20811. if (trim) {
  20812. num = num.substr(num.length - digits);
  20813. }
  20814. return neg + num;
  20815. }
  20816. function dateGetter(name, size, offset, trim, negWrap) {
  20817. offset = offset || 0;
  20818. return function(date) {
  20819. var value = date['get' + name]();
  20820. if (offset > 0 || value > -offset) {
  20821. value += offset;
  20822. }
  20823. if (value === 0 && offset === -12) value = 12;
  20824. return padNumber(value, size, trim, negWrap);
  20825. };
  20826. }
  20827. function dateStrGetter(name, shortForm, standAlone) {
  20828. return function(date, formats) {
  20829. var value = date['get' + name]();
  20830. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  20831. var get = uppercase(propPrefix + name);
  20832. return formats[get][value];
  20833. };
  20834. }
  20835. function timeZoneGetter(date, formats, offset) {
  20836. var zone = -1 * offset;
  20837. var paddedZone = (zone >= 0) ? '+' : '';
  20838. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  20839. padNumber(Math.abs(zone % 60), 2);
  20840. return paddedZone;
  20841. }
  20842. function getFirstThursdayOfYear(year) {
  20843. // 0 = index of January
  20844. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  20845. // 4 = index of Thursday (+1 to account for 1st = 5)
  20846. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  20847. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  20848. }
  20849. function getThursdayThisWeek(datetime) {
  20850. return new Date(datetime.getFullYear(), datetime.getMonth(),
  20851. // 4 = index of Thursday
  20852. datetime.getDate() + (4 - datetime.getDay()));
  20853. }
  20854. function weekGetter(size) {
  20855. return function(date) {
  20856. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  20857. thisThurs = getThursdayThisWeek(date);
  20858. var diff = +thisThurs - +firstThurs,
  20859. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  20860. return padNumber(result, size);
  20861. };
  20862. }
  20863. function ampmGetter(date, formats) {
  20864. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  20865. }
  20866. function eraGetter(date, formats) {
  20867. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  20868. }
  20869. function longEraGetter(date, formats) {
  20870. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  20871. }
  20872. var DATE_FORMATS = {
  20873. yyyy: dateGetter('FullYear', 4, 0, false, true),
  20874. yy: dateGetter('FullYear', 2, 0, true, true),
  20875. y: dateGetter('FullYear', 1, 0, false, true),
  20876. MMMM: dateStrGetter('Month'),
  20877. MMM: dateStrGetter('Month', true),
  20878. MM: dateGetter('Month', 2, 1),
  20879. M: dateGetter('Month', 1, 1),
  20880. LLLL: dateStrGetter('Month', false, true),
  20881. dd: dateGetter('Date', 2),
  20882. d: dateGetter('Date', 1),
  20883. HH: dateGetter('Hours', 2),
  20884. H: dateGetter('Hours', 1),
  20885. hh: dateGetter('Hours', 2, -12),
  20886. h: dateGetter('Hours', 1, -12),
  20887. mm: dateGetter('Minutes', 2),
  20888. m: dateGetter('Minutes', 1),
  20889. ss: dateGetter('Seconds', 2),
  20890. s: dateGetter('Seconds', 1),
  20891. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  20892. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  20893. sss: dateGetter('Milliseconds', 3),
  20894. EEEE: dateStrGetter('Day'),
  20895. EEE: dateStrGetter('Day', true),
  20896. a: ampmGetter,
  20897. Z: timeZoneGetter,
  20898. ww: weekGetter(2),
  20899. w: weekGetter(1),
  20900. G: eraGetter,
  20901. GG: eraGetter,
  20902. GGG: eraGetter,
  20903. GGGG: longEraGetter
  20904. };
  20905. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  20906. NUMBER_STRING = /^-?\d+$/;
  20907. /**
  20908. * @ngdoc filter
  20909. * @name date
  20910. * @kind function
  20911. *
  20912. * @description
  20913. * Formats `date` to a string based on the requested `format`.
  20914. *
  20915. * `format` string can be composed of the following elements:
  20916. *
  20917. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  20918. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  20919. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  20920. * * `'MMMM'`: Month in year (January-December)
  20921. * * `'MMM'`: Month in year (Jan-Dec)
  20922. * * `'MM'`: Month in year, padded (01-12)
  20923. * * `'M'`: Month in year (1-12)
  20924. * * `'LLLL'`: Stand-alone month in year (January-December)
  20925. * * `'dd'`: Day in month, padded (01-31)
  20926. * * `'d'`: Day in month (1-31)
  20927. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  20928. * * `'EEE'`: Day in Week, (Sun-Sat)
  20929. * * `'HH'`: Hour in day, padded (00-23)
  20930. * * `'H'`: Hour in day (0-23)
  20931. * * `'hh'`: Hour in AM/PM, padded (01-12)
  20932. * * `'h'`: Hour in AM/PM, (1-12)
  20933. * * `'mm'`: Minute in hour, padded (00-59)
  20934. * * `'m'`: Minute in hour (0-59)
  20935. * * `'ss'`: Second in minute, padded (00-59)
  20936. * * `'s'`: Second in minute (0-59)
  20937. * * `'sss'`: Millisecond in second, padded (000-999)
  20938. * * `'a'`: AM/PM marker
  20939. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  20940. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  20941. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  20942. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  20943. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  20944. *
  20945. * `format` string can also be one of the following predefined
  20946. * {@link guide/i18n localizable formats}:
  20947. *
  20948. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  20949. * (e.g. Sep 3, 2010 12:05:08 PM)
  20950. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  20951. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  20952. * (e.g. Friday, September 3, 2010)
  20953. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  20954. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  20955. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  20956. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  20957. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  20958. *
  20959. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  20960. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  20961. * (e.g. `"h 'o''clock'"`).
  20962. *
  20963. * Any other characters in the `format` string will be output as-is.
  20964. *
  20965. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  20966. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  20967. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  20968. * specified in the string input, the time is considered to be in the local timezone.
  20969. * @param {string=} format Formatting rules (see Description). If not specified,
  20970. * `mediumDate` is used.
  20971. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  20972. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  20973. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  20974. * If not specified, the timezone of the browser will be used.
  20975. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  20976. *
  20977. * @example
  20978. <example name="filter-date">
  20979. <file name="index.html">
  20980. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  20981. <span>{{1288323623006 | date:'medium'}}</span><br>
  20982. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  20983. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  20984. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  20985. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  20986. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  20987. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  20988. </file>
  20989. <file name="protractor.js" type="protractor">
  20990. it('should format date', function() {
  20991. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  20992. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  20993. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  20994. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  20995. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  20996. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  20997. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  20998. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  20999. });
  21000. </file>
  21001. </example>
  21002. */
  21003. dateFilter.$inject = ['$locale'];
  21004. function dateFilter($locale) {
  21005. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  21006. // 1 2 3 4 5 6 7 8 9 10 11
  21007. function jsonStringToDate(string) {
  21008. var match;
  21009. if ((match = string.match(R_ISO8601_STR))) {
  21010. var date = new Date(0),
  21011. tzHour = 0,
  21012. tzMin = 0,
  21013. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  21014. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  21015. if (match[9]) {
  21016. tzHour = toInt(match[9] + match[10]);
  21017. tzMin = toInt(match[9] + match[11]);
  21018. }
  21019. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  21020. var h = toInt(match[4] || 0) - tzHour;
  21021. var m = toInt(match[5] || 0) - tzMin;
  21022. var s = toInt(match[6] || 0);
  21023. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  21024. timeSetter.call(date, h, m, s, ms);
  21025. return date;
  21026. }
  21027. return string;
  21028. }
  21029. return function(date, format, timezone) {
  21030. var text = '',
  21031. parts = [],
  21032. fn, match;
  21033. format = format || 'mediumDate';
  21034. format = $locale.DATETIME_FORMATS[format] || format;
  21035. if (isString(date)) {
  21036. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  21037. }
  21038. if (isNumber(date)) {
  21039. date = new Date(date);
  21040. }
  21041. if (!isDate(date) || !isFinite(date.getTime())) {
  21042. return date;
  21043. }
  21044. while (format) {
  21045. match = DATE_FORMATS_SPLIT.exec(format);
  21046. if (match) {
  21047. parts = concat(parts, match, 1);
  21048. format = parts.pop();
  21049. } else {
  21050. parts.push(format);
  21051. format = null;
  21052. }
  21053. }
  21054. var dateTimezoneOffset = date.getTimezoneOffset();
  21055. if (timezone) {
  21056. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  21057. date = convertTimezoneToLocal(date, timezone, true);
  21058. }
  21059. forEach(parts, function(value) {
  21060. fn = DATE_FORMATS[value];
  21061. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  21062. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  21063. });
  21064. return text;
  21065. };
  21066. }
  21067. /**
  21068. * @ngdoc filter
  21069. * @name json
  21070. * @kind function
  21071. *
  21072. * @description
  21073. * Allows you to convert a JavaScript object into JSON string.
  21074. *
  21075. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  21076. * the binding is automatically converted to JSON.
  21077. *
  21078. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  21079. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  21080. * @returns {string} JSON string.
  21081. *
  21082. *
  21083. * @example
  21084. <example name="filter-json">
  21085. <file name="index.html">
  21086. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  21087. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  21088. </file>
  21089. <file name="protractor.js" type="protractor">
  21090. it('should jsonify filtered objects', function() {
  21091. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  21092. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  21093. });
  21094. </file>
  21095. </example>
  21096. *
  21097. */
  21098. function jsonFilter() {
  21099. return function(object, spacing) {
  21100. if (isUndefined(spacing)) {
  21101. spacing = 2;
  21102. }
  21103. return toJson(object, spacing);
  21104. };
  21105. }
  21106. /**
  21107. * @ngdoc filter
  21108. * @name lowercase
  21109. * @kind function
  21110. * @description
  21111. * Converts string to lowercase.
  21112. *
  21113. * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.
  21114. *
  21115. * @see angular.lowercase
  21116. */
  21117. var lowercaseFilter = valueFn(lowercase);
  21118. /**
  21119. * @ngdoc filter
  21120. * @name uppercase
  21121. * @kind function
  21122. * @description
  21123. * Converts string to uppercase.
  21124. * @example
  21125. <example module="uppercaseFilterExample" name="filter-uppercase">
  21126. <file name="index.html">
  21127. <script>
  21128. angular.module('uppercaseFilterExample', [])
  21129. .controller('ExampleController', ['$scope', function($scope) {
  21130. $scope.title = 'This is a title';
  21131. }]);
  21132. </script>
  21133. <div ng-controller="ExampleController">
  21134. <!-- This title should be formatted normally -->
  21135. <h1>{{title}}</h1>
  21136. <!-- This title should be capitalized -->
  21137. <h1>{{title | uppercase}}</h1>
  21138. </div>
  21139. </file>
  21140. </example>
  21141. */
  21142. var uppercaseFilter = valueFn(uppercase);
  21143. /**
  21144. * @ngdoc filter
  21145. * @name limitTo
  21146. * @kind function
  21147. *
  21148. * @description
  21149. * Creates a new array or string containing only a specified number of elements. The elements are
  21150. * taken from either the beginning or the end of the source array, string or number, as specified by
  21151. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  21152. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  21153. * it is converted to a string.
  21154. *
  21155. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  21156. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  21157. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  21158. * If the number is negative, `limit` number of items from the end of the source array/string
  21159. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  21160. * the input will be returned unchanged.
  21161. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  21162. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  21163. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  21164. * less than `limit` elements.
  21165. *
  21166. * @example
  21167. <example module="limitToExample" name="limit-to-filter">
  21168. <file name="index.html">
  21169. <script>
  21170. angular.module('limitToExample', [])
  21171. .controller('ExampleController', ['$scope', function($scope) {
  21172. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  21173. $scope.letters = "abcdefghi";
  21174. $scope.longNumber = 2345432342;
  21175. $scope.numLimit = 3;
  21176. $scope.letterLimit = 3;
  21177. $scope.longNumberLimit = 3;
  21178. }]);
  21179. </script>
  21180. <div ng-controller="ExampleController">
  21181. <label>
  21182. Limit {{numbers}} to:
  21183. <input type="number" step="1" ng-model="numLimit">
  21184. </label>
  21185. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  21186. <label>
  21187. Limit {{letters}} to:
  21188. <input type="number" step="1" ng-model="letterLimit">
  21189. </label>
  21190. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  21191. <label>
  21192. Limit {{longNumber}} to:
  21193. <input type="number" step="1" ng-model="longNumberLimit">
  21194. </label>
  21195. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  21196. </div>
  21197. </file>
  21198. <file name="protractor.js" type="protractor">
  21199. var numLimitInput = element(by.model('numLimit'));
  21200. var letterLimitInput = element(by.model('letterLimit'));
  21201. var longNumberLimitInput = element(by.model('longNumberLimit'));
  21202. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  21203. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  21204. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  21205. it('should limit the number array to first three items', function() {
  21206. expect(numLimitInput.getAttribute('value')).toBe('3');
  21207. expect(letterLimitInput.getAttribute('value')).toBe('3');
  21208. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  21209. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  21210. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  21211. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  21212. });
  21213. // There is a bug in safari and protractor that doesn't like the minus key
  21214. // it('should update the output when -3 is entered', function() {
  21215. // numLimitInput.clear();
  21216. // numLimitInput.sendKeys('-3');
  21217. // letterLimitInput.clear();
  21218. // letterLimitInput.sendKeys('-3');
  21219. // longNumberLimitInput.clear();
  21220. // longNumberLimitInput.sendKeys('-3');
  21221. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  21222. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  21223. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  21224. // });
  21225. it('should not exceed the maximum size of input array', function() {
  21226. numLimitInput.clear();
  21227. numLimitInput.sendKeys('100');
  21228. letterLimitInput.clear();
  21229. letterLimitInput.sendKeys('100');
  21230. longNumberLimitInput.clear();
  21231. longNumberLimitInput.sendKeys('100');
  21232. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  21233. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  21234. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  21235. });
  21236. </file>
  21237. </example>
  21238. */
  21239. function limitToFilter() {
  21240. return function(input, limit, begin) {
  21241. if (Math.abs(Number(limit)) === Infinity) {
  21242. limit = Number(limit);
  21243. } else {
  21244. limit = toInt(limit);
  21245. }
  21246. if (isNumberNaN(limit)) return input;
  21247. if (isNumber(input)) input = input.toString();
  21248. if (!isArrayLike(input)) return input;
  21249. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  21250. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  21251. if (limit >= 0) {
  21252. return sliceFn(input, begin, begin + limit);
  21253. } else {
  21254. if (begin === 0) {
  21255. return sliceFn(input, limit, input.length);
  21256. } else {
  21257. return sliceFn(input, Math.max(0, begin + limit), begin);
  21258. }
  21259. }
  21260. };
  21261. }
  21262. function sliceFn(input, begin, end) {
  21263. if (isString(input)) return input.slice(begin, end);
  21264. return slice.call(input, begin, end);
  21265. }
  21266. /**
  21267. * @ngdoc filter
  21268. * @name orderBy
  21269. * @kind function
  21270. *
  21271. * @description
  21272. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  21273. * function based on the values computed using the `expression` predicate.
  21274. *
  21275. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  21276. * `[{id: 'bar'}, {id: 'foo'}]`.
  21277. *
  21278. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  21279. * String, etc).
  21280. *
  21281. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  21282. * for the preceding one. The `expression` is evaluated against each item and the output is used
  21283. * for comparing with other items.
  21284. *
  21285. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  21286. * ascending order.
  21287. *
  21288. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  21289. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  21290. * strings alphabetically).
  21291. *
  21292. * ### Under the hood
  21293. *
  21294. * Ordering the specified `collection` happens in two phases:
  21295. *
  21296. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  21297. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  21298. * through a predicate that extracts the value of the `label` property, would be transformed to:
  21299. * ```
  21300. * {
  21301. * value: 'foo',
  21302. * type: 'string',
  21303. * index: ...
  21304. * }
  21305. * ```
  21306. * **Note:** `null` values use `'null'` as their type.
  21307. * 2. The comparator function is used to sort the items, based on the derived values, types and
  21308. * indices.
  21309. *
  21310. * If you use a custom comparator, it will be called with pairs of objects of the form
  21311. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  21312. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  21313. * second, or `1` otherwise.
  21314. *
  21315. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  21316. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  21317. * dummy predicate that returns the item's index as `value`.
  21318. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  21319. *
  21320. * If a custom comparator still can't distinguish between two items, then they will be sorted based
  21321. * on their index using the built-in comparator.
  21322. *
  21323. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  21324. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  21325. * it to the comparator. The following rules govern the conversion:
  21326. *
  21327. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  21328. * used instead.<br />
  21329. * (If the object has a `valueOf()` method that returns another object, then the returned object
  21330. * will be used in subsequent steps.)
  21331. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  21332. * returns a primitive, its return value will be used instead.<br />
  21333. * (If the object has a `toString()` method that returns another object, then the returned object
  21334. * will be used in subsequent steps.)
  21335. * 3. No conversion; the object itself is used.
  21336. *
  21337. * ### The default comparator
  21338. *
  21339. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  21340. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  21341. * using their index in the original collection, sorts values of different types by type and puts
  21342. * `undefined` and `null` values at the end of the sorted list.
  21343. *
  21344. * More specifically, it follows these steps to determine the relative order of items:
  21345. *
  21346. * 1. If the compared values are of different types:
  21347. * - If one of the values is undefined, consider it "greater than" the other.
  21348. * - Else if one of the values is null, consider it "greater than" the other.
  21349. * - Else compare the types themselves alphabetically.
  21350. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  21351. * locale-insensitive way.
  21352. * 3. If both values are objects, compare their indices instead.
  21353. * 4. Otherwise, return:
  21354. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  21355. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  21356. * - `1`, otherwise.
  21357. *
  21358. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  21359. * saved as numbers and not strings.
  21360. * **Note:** For the purpose of sorting, `null` and `undefined` are considered "greater than"
  21361. * any other value (with undefined "greater than" null). This effectively means that `null`
  21362. * and `undefined` values end up at the end of a list sorted in ascending order.
  21363. * **Note:** `null` values use `'null'` as their type to be able to distinguish them from objects.
  21364. *
  21365. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  21366. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  21367. * predicates) to be used by the comparator to determine the order of elements.
  21368. *
  21369. * Can be one of:
  21370. *
  21371. * - `Function`: A getter function. This function will be called with each item as argument and
  21372. * the return value will be used for sorting.
  21373. * - `string`: An AngularJS expression. This expression will be evaluated against each item and the
  21374. * result will be used for sorting. For example, use `'label'` to sort by a property called
  21375. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  21376. * property.<br />
  21377. * (The result of a constant expression is interpreted as a property name to be used for
  21378. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  21379. * property called `special name`.)<br />
  21380. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  21381. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  21382. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  21383. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  21384. * relative order of two items, the next predicate is used as a tie-breaker.
  21385. *
  21386. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  21387. *
  21388. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  21389. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  21390. * value pairs. If omitted, the built-in comparator will be used.
  21391. *
  21392. * @returns {Array} - The sorted array.
  21393. *
  21394. *
  21395. * @example
  21396. * ### Ordering a table with `ngRepeat`
  21397. *
  21398. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  21399. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  21400. * it defaults to the built-in comparator.
  21401. *
  21402. <example name="orderBy-static" module="orderByExample1">
  21403. <file name="index.html">
  21404. <div ng-controller="ExampleController">
  21405. <table class="friends">
  21406. <tr>
  21407. <th>Name</th>
  21408. <th>Phone Number</th>
  21409. <th>Age</th>
  21410. </tr>
  21411. <tr ng-repeat="friend in friends | orderBy:'-age'">
  21412. <td>{{friend.name}}</td>
  21413. <td>{{friend.phone}}</td>
  21414. <td>{{friend.age}}</td>
  21415. </tr>
  21416. </table>
  21417. </div>
  21418. </file>
  21419. <file name="script.js">
  21420. angular.module('orderByExample1', [])
  21421. .controller('ExampleController', ['$scope', function($scope) {
  21422. $scope.friends = [
  21423. {name: 'John', phone: '555-1212', age: 10},
  21424. {name: 'Mary', phone: '555-9876', age: 19},
  21425. {name: 'Mike', phone: '555-4321', age: 21},
  21426. {name: 'Adam', phone: '555-5678', age: 35},
  21427. {name: 'Julie', phone: '555-8765', age: 29}
  21428. ];
  21429. }]);
  21430. </file>
  21431. <file name="style.css">
  21432. .friends {
  21433. border-collapse: collapse;
  21434. }
  21435. .friends th {
  21436. border-bottom: 1px solid;
  21437. }
  21438. .friends td, .friends th {
  21439. border-left: 1px solid;
  21440. padding: 5px 10px;
  21441. }
  21442. .friends td:first-child, .friends th:first-child {
  21443. border-left: none;
  21444. }
  21445. </file>
  21446. <file name="protractor.js" type="protractor">
  21447. // Element locators
  21448. var names = element.all(by.repeater('friends').column('friend.name'));
  21449. it('should sort friends by age in reverse order', function() {
  21450. expect(names.get(0).getText()).toBe('Adam');
  21451. expect(names.get(1).getText()).toBe('Julie');
  21452. expect(names.get(2).getText()).toBe('Mike');
  21453. expect(names.get(3).getText()).toBe('Mary');
  21454. expect(names.get(4).getText()).toBe('John');
  21455. });
  21456. </file>
  21457. </example>
  21458. * <hr />
  21459. *
  21460. * @example
  21461. * ### Changing parameters dynamically
  21462. *
  21463. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  21464. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  21465. *
  21466. <example name="orderBy-dynamic" module="orderByExample2">
  21467. <file name="index.html">
  21468. <div ng-controller="ExampleController">
  21469. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  21470. <hr/>
  21471. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  21472. <hr/>
  21473. <table class="friends">
  21474. <tr>
  21475. <th>
  21476. <button ng-click="sortBy('name')">Name</button>
  21477. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  21478. </th>
  21479. <th>
  21480. <button ng-click="sortBy('phone')">Phone Number</button>
  21481. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  21482. </th>
  21483. <th>
  21484. <button ng-click="sortBy('age')">Age</button>
  21485. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  21486. </th>
  21487. </tr>
  21488. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  21489. <td>{{friend.name}}</td>
  21490. <td>{{friend.phone}}</td>
  21491. <td>{{friend.age}}</td>
  21492. </tr>
  21493. </table>
  21494. </div>
  21495. </file>
  21496. <file name="script.js">
  21497. angular.module('orderByExample2', [])
  21498. .controller('ExampleController', ['$scope', function($scope) {
  21499. var friends = [
  21500. {name: 'John', phone: '555-1212', age: 10},
  21501. {name: 'Mary', phone: '555-9876', age: 19},
  21502. {name: 'Mike', phone: '555-4321', age: 21},
  21503. {name: 'Adam', phone: '555-5678', age: 35},
  21504. {name: 'Julie', phone: '555-8765', age: 29}
  21505. ];
  21506. $scope.propertyName = 'age';
  21507. $scope.reverse = true;
  21508. $scope.friends = friends;
  21509. $scope.sortBy = function(propertyName) {
  21510. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  21511. $scope.propertyName = propertyName;
  21512. };
  21513. }]);
  21514. </file>
  21515. <file name="style.css">
  21516. .friends {
  21517. border-collapse: collapse;
  21518. }
  21519. .friends th {
  21520. border-bottom: 1px solid;
  21521. }
  21522. .friends td, .friends th {
  21523. border-left: 1px solid;
  21524. padding: 5px 10px;
  21525. }
  21526. .friends td:first-child, .friends th:first-child {
  21527. border-left: none;
  21528. }
  21529. .sortorder:after {
  21530. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  21531. }
  21532. .sortorder.reverse:after {
  21533. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  21534. }
  21535. </file>
  21536. <file name="protractor.js" type="protractor">
  21537. // Element locators
  21538. var unsortButton = element(by.partialButtonText('unsorted'));
  21539. var nameHeader = element(by.partialButtonText('Name'));
  21540. var phoneHeader = element(by.partialButtonText('Phone'));
  21541. var ageHeader = element(by.partialButtonText('Age'));
  21542. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  21543. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  21544. it('should sort friends by some property, when clicking on the column header', function() {
  21545. expect(firstName.getText()).toBe('Adam');
  21546. expect(lastName.getText()).toBe('John');
  21547. phoneHeader.click();
  21548. expect(firstName.getText()).toBe('John');
  21549. expect(lastName.getText()).toBe('Mary');
  21550. nameHeader.click();
  21551. expect(firstName.getText()).toBe('Adam');
  21552. expect(lastName.getText()).toBe('Mike');
  21553. ageHeader.click();
  21554. expect(firstName.getText()).toBe('John');
  21555. expect(lastName.getText()).toBe('Adam');
  21556. });
  21557. it('should sort friends in reverse order, when clicking on the same column', function() {
  21558. expect(firstName.getText()).toBe('Adam');
  21559. expect(lastName.getText()).toBe('John');
  21560. ageHeader.click();
  21561. expect(firstName.getText()).toBe('John');
  21562. expect(lastName.getText()).toBe('Adam');
  21563. ageHeader.click();
  21564. expect(firstName.getText()).toBe('Adam');
  21565. expect(lastName.getText()).toBe('John');
  21566. });
  21567. it('should restore the original order, when clicking "Set to unsorted"', function() {
  21568. expect(firstName.getText()).toBe('Adam');
  21569. expect(lastName.getText()).toBe('John');
  21570. unsortButton.click();
  21571. expect(firstName.getText()).toBe('John');
  21572. expect(lastName.getText()).toBe('Julie');
  21573. });
  21574. </file>
  21575. </example>
  21576. * <hr />
  21577. *
  21578. * @example
  21579. * ### Using `orderBy` inside a controller
  21580. *
  21581. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  21582. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  21583. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  21584. *
  21585. <example name="orderBy-call-manually" module="orderByExample3">
  21586. <file name="index.html">
  21587. <div ng-controller="ExampleController">
  21588. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  21589. <hr/>
  21590. <button ng-click="sortBy(null)">Set to unsorted</button>
  21591. <hr/>
  21592. <table class="friends">
  21593. <tr>
  21594. <th>
  21595. <button ng-click="sortBy('name')">Name</button>
  21596. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  21597. </th>
  21598. <th>
  21599. <button ng-click="sortBy('phone')">Phone Number</button>
  21600. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  21601. </th>
  21602. <th>
  21603. <button ng-click="sortBy('age')">Age</button>
  21604. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  21605. </th>
  21606. </tr>
  21607. <tr ng-repeat="friend in friends">
  21608. <td>{{friend.name}}</td>
  21609. <td>{{friend.phone}}</td>
  21610. <td>{{friend.age}}</td>
  21611. </tr>
  21612. </table>
  21613. </div>
  21614. </file>
  21615. <file name="script.js">
  21616. angular.module('orderByExample3', [])
  21617. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  21618. var friends = [
  21619. {name: 'John', phone: '555-1212', age: 10},
  21620. {name: 'Mary', phone: '555-9876', age: 19},
  21621. {name: 'Mike', phone: '555-4321', age: 21},
  21622. {name: 'Adam', phone: '555-5678', age: 35},
  21623. {name: 'Julie', phone: '555-8765', age: 29}
  21624. ];
  21625. $scope.propertyName = 'age';
  21626. $scope.reverse = true;
  21627. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  21628. $scope.sortBy = function(propertyName) {
  21629. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  21630. ? !$scope.reverse : false;
  21631. $scope.propertyName = propertyName;
  21632. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  21633. };
  21634. }]);
  21635. </file>
  21636. <file name="style.css">
  21637. .friends {
  21638. border-collapse: collapse;
  21639. }
  21640. .friends th {
  21641. border-bottom: 1px solid;
  21642. }
  21643. .friends td, .friends th {
  21644. border-left: 1px solid;
  21645. padding: 5px 10px;
  21646. }
  21647. .friends td:first-child, .friends th:first-child {
  21648. border-left: none;
  21649. }
  21650. .sortorder:after {
  21651. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  21652. }
  21653. .sortorder.reverse:after {
  21654. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  21655. }
  21656. </file>
  21657. <file name="protractor.js" type="protractor">
  21658. // Element locators
  21659. var unsortButton = element(by.partialButtonText('unsorted'));
  21660. var nameHeader = element(by.partialButtonText('Name'));
  21661. var phoneHeader = element(by.partialButtonText('Phone'));
  21662. var ageHeader = element(by.partialButtonText('Age'));
  21663. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  21664. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  21665. it('should sort friends by some property, when clicking on the column header', function() {
  21666. expect(firstName.getText()).toBe('Adam');
  21667. expect(lastName.getText()).toBe('John');
  21668. phoneHeader.click();
  21669. expect(firstName.getText()).toBe('John');
  21670. expect(lastName.getText()).toBe('Mary');
  21671. nameHeader.click();
  21672. expect(firstName.getText()).toBe('Adam');
  21673. expect(lastName.getText()).toBe('Mike');
  21674. ageHeader.click();
  21675. expect(firstName.getText()).toBe('John');
  21676. expect(lastName.getText()).toBe('Adam');
  21677. });
  21678. it('should sort friends in reverse order, when clicking on the same column', function() {
  21679. expect(firstName.getText()).toBe('Adam');
  21680. expect(lastName.getText()).toBe('John');
  21681. ageHeader.click();
  21682. expect(firstName.getText()).toBe('John');
  21683. expect(lastName.getText()).toBe('Adam');
  21684. ageHeader.click();
  21685. expect(firstName.getText()).toBe('Adam');
  21686. expect(lastName.getText()).toBe('John');
  21687. });
  21688. it('should restore the original order, when clicking "Set to unsorted"', function() {
  21689. expect(firstName.getText()).toBe('Adam');
  21690. expect(lastName.getText()).toBe('John');
  21691. unsortButton.click();
  21692. expect(firstName.getText()).toBe('John');
  21693. expect(lastName.getText()).toBe('Julie');
  21694. });
  21695. </file>
  21696. </example>
  21697. * <hr />
  21698. *
  21699. * @example
  21700. * ### Using a custom comparator
  21701. *
  21702. * If you have very specific requirements about the way items are sorted, you can pass your own
  21703. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  21704. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  21705. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  21706. *
  21707. <example name="orderBy-custom-comparator" module="orderByExample4">
  21708. <file name="index.html">
  21709. <div ng-controller="ExampleController">
  21710. <div class="friends-container custom-comparator">
  21711. <h3>Locale-sensitive Comparator</h3>
  21712. <table class="friends">
  21713. <tr>
  21714. <th>Name</th>
  21715. <th>Favorite Letter</th>
  21716. </tr>
  21717. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  21718. <td>{{friend.name}}</td>
  21719. <td>{{friend.favoriteLetter}}</td>
  21720. </tr>
  21721. </table>
  21722. </div>
  21723. <div class="friends-container default-comparator">
  21724. <h3>Default Comparator</h3>
  21725. <table class="friends">
  21726. <tr>
  21727. <th>Name</th>
  21728. <th>Favorite Letter</th>
  21729. </tr>
  21730. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  21731. <td>{{friend.name}}</td>
  21732. <td>{{friend.favoriteLetter}}</td>
  21733. </tr>
  21734. </table>
  21735. </div>
  21736. </div>
  21737. </file>
  21738. <file name="script.js">
  21739. angular.module('orderByExample4', [])
  21740. .controller('ExampleController', ['$scope', function($scope) {
  21741. $scope.friends = [
  21742. {name: 'John', favoriteLetter: 'Ä'},
  21743. {name: 'Mary', favoriteLetter: 'Ü'},
  21744. {name: 'Mike', favoriteLetter: 'Ö'},
  21745. {name: 'Adam', favoriteLetter: 'H'},
  21746. {name: 'Julie', favoriteLetter: 'Z'}
  21747. ];
  21748. $scope.localeSensitiveComparator = function(v1, v2) {
  21749. // If we don't get strings, just compare by index
  21750. if (v1.type !== 'string' || v2.type !== 'string') {
  21751. return (v1.index < v2.index) ? -1 : 1;
  21752. }
  21753. // Compare strings alphabetically, taking locale into account
  21754. return v1.value.localeCompare(v2.value);
  21755. };
  21756. }]);
  21757. </file>
  21758. <file name="style.css">
  21759. .friends-container {
  21760. display: inline-block;
  21761. margin: 0 30px;
  21762. }
  21763. .friends {
  21764. border-collapse: collapse;
  21765. }
  21766. .friends th {
  21767. border-bottom: 1px solid;
  21768. }
  21769. .friends td, .friends th {
  21770. border-left: 1px solid;
  21771. padding: 5px 10px;
  21772. }
  21773. .friends td:first-child, .friends th:first-child {
  21774. border-left: none;
  21775. }
  21776. </file>
  21777. <file name="protractor.js" type="protractor">
  21778. // Element locators
  21779. var container = element(by.css('.custom-comparator'));
  21780. var names = container.all(by.repeater('friends').column('friend.name'));
  21781. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  21782. expect(names.get(0).getText()).toBe('John');
  21783. expect(names.get(1).getText()).toBe('Adam');
  21784. expect(names.get(2).getText()).toBe('Mike');
  21785. expect(names.get(3).getText()).toBe('Mary');
  21786. expect(names.get(4).getText()).toBe('Julie');
  21787. });
  21788. </file>
  21789. </example>
  21790. *
  21791. */
  21792. orderByFilter.$inject = ['$parse'];
  21793. function orderByFilter($parse) {
  21794. return function(array, sortPredicate, reverseOrder, compareFn) {
  21795. if (array == null) return array;
  21796. if (!isArrayLike(array)) {
  21797. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  21798. }
  21799. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  21800. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  21801. var predicates = processPredicates(sortPredicate);
  21802. var descending = reverseOrder ? -1 : 1;
  21803. // Define the `compare()` function. Use a default comparator if none is specified.
  21804. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  21805. // The next three lines are a version of a Swartzian Transform idiom from Perl
  21806. // (sometimes called the Decorate-Sort-Undecorate idiom)
  21807. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  21808. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  21809. compareValues.sort(doComparison);
  21810. array = compareValues.map(function(item) { return item.value; });
  21811. return array;
  21812. function getComparisonObject(value, index) {
  21813. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  21814. // This will be used to keep the sort stable when none of the input predicates can
  21815. // distinguish between two elements.
  21816. return {
  21817. value: value,
  21818. tieBreaker: {value: index, type: 'number', index: index},
  21819. predicateValues: predicates.map(function(predicate) {
  21820. return getPredicateValue(predicate.get(value), index);
  21821. })
  21822. };
  21823. }
  21824. function doComparison(v1, v2) {
  21825. for (var i = 0, ii = predicates.length; i < ii; i++) {
  21826. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  21827. if (result) {
  21828. return result * predicates[i].descending * descending;
  21829. }
  21830. }
  21831. return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
  21832. }
  21833. };
  21834. function processPredicates(sortPredicates) {
  21835. return sortPredicates.map(function(predicate) {
  21836. var descending = 1, get = identity;
  21837. if (isFunction(predicate)) {
  21838. get = predicate;
  21839. } else if (isString(predicate)) {
  21840. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  21841. descending = predicate.charAt(0) === '-' ? -1 : 1;
  21842. predicate = predicate.substring(1);
  21843. }
  21844. if (predicate !== '') {
  21845. get = $parse(predicate);
  21846. if (get.constant) {
  21847. var key = get();
  21848. get = function(value) { return value[key]; };
  21849. }
  21850. }
  21851. }
  21852. return {get: get, descending: descending};
  21853. });
  21854. }
  21855. function isPrimitive(value) {
  21856. switch (typeof value) {
  21857. case 'number': /* falls through */
  21858. case 'boolean': /* falls through */
  21859. case 'string':
  21860. return true;
  21861. default:
  21862. return false;
  21863. }
  21864. }
  21865. function objectValue(value) {
  21866. // If `valueOf` is a valid function use that
  21867. if (isFunction(value.valueOf)) {
  21868. value = value.valueOf();
  21869. if (isPrimitive(value)) return value;
  21870. }
  21871. // If `toString` is a valid function and not the one from `Object.prototype` use that
  21872. if (hasCustomToString(value)) {
  21873. value = value.toString();
  21874. if (isPrimitive(value)) return value;
  21875. }
  21876. return value;
  21877. }
  21878. function getPredicateValue(value, index) {
  21879. var type = typeof value;
  21880. if (value === null) {
  21881. type = 'null';
  21882. } else if (type === 'object') {
  21883. value = objectValue(value);
  21884. }
  21885. return {value: value, type: type, index: index};
  21886. }
  21887. function defaultCompare(v1, v2) {
  21888. var result = 0;
  21889. var type1 = v1.type;
  21890. var type2 = v2.type;
  21891. if (type1 === type2) {
  21892. var value1 = v1.value;
  21893. var value2 = v2.value;
  21894. if (type1 === 'string') {
  21895. // Compare strings case-insensitively
  21896. value1 = value1.toLowerCase();
  21897. value2 = value2.toLowerCase();
  21898. } else if (type1 === 'object') {
  21899. // For basic objects, use the position of the object
  21900. // in the collection instead of the value
  21901. if (isObject(value1)) value1 = v1.index;
  21902. if (isObject(value2)) value2 = v2.index;
  21903. }
  21904. if (value1 !== value2) {
  21905. result = value1 < value2 ? -1 : 1;
  21906. }
  21907. } else {
  21908. result = (type1 === 'undefined') ? 1 :
  21909. (type2 === 'undefined') ? -1 :
  21910. (type1 === 'null') ? 1 :
  21911. (type2 === 'null') ? -1 :
  21912. (type1 < type2) ? -1 : 1;
  21913. }
  21914. return result;
  21915. }
  21916. }
  21917. function ngDirective(directive) {
  21918. if (isFunction(directive)) {
  21919. directive = {
  21920. link: directive
  21921. };
  21922. }
  21923. directive.restrict = directive.restrict || 'AC';
  21924. return valueFn(directive);
  21925. }
  21926. /**
  21927. * @ngdoc directive
  21928. * @name a
  21929. * @restrict E
  21930. *
  21931. * @description
  21932. * Modifies the default behavior of the html a tag so that the default action is prevented when
  21933. * the href attribute is empty.
  21934. *
  21935. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  21936. */
  21937. var htmlAnchorDirective = valueFn({
  21938. restrict: 'E',
  21939. compile: function(element, attr) {
  21940. if (!attr.href && !attr.xlinkHref) {
  21941. return function(scope, element) {
  21942. // If the linked element is not an anchor tag anymore, do nothing
  21943. if (element[0].nodeName.toLowerCase() !== 'a') return;
  21944. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  21945. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  21946. 'xlink:href' : 'href';
  21947. element.on('click', function(event) {
  21948. // if we have no href url, then don't navigate anywhere.
  21949. if (!element.attr(href)) {
  21950. event.preventDefault();
  21951. }
  21952. });
  21953. };
  21954. }
  21955. }
  21956. });
  21957. /**
  21958. * @ngdoc directive
  21959. * @name ngHref
  21960. * @restrict A
  21961. * @priority 99
  21962. *
  21963. * @description
  21964. * Using AngularJS markup like `{{hash}}` in an href attribute will
  21965. * make the link go to the wrong URL if the user clicks it before
  21966. * AngularJS has a chance to replace the `{{hash}}` markup with its
  21967. * value. Until AngularJS replaces the markup the link will be broken
  21968. * and will most likely return a 404 error. The `ngHref` directive
  21969. * solves this problem.
  21970. *
  21971. * The wrong way to write it:
  21972. * ```html
  21973. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  21974. * ```
  21975. *
  21976. * The correct way to write it:
  21977. * ```html
  21978. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  21979. * ```
  21980. *
  21981. * @element A
  21982. * @param {template} ngHref any string which can contain `{{}}` markup.
  21983. *
  21984. * @example
  21985. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  21986. * in links and their different behaviors:
  21987. <example name="ng-href">
  21988. <file name="index.html">
  21989. <input ng-model="value" /><br />
  21990. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  21991. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  21992. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  21993. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  21994. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  21995. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  21996. </file>
  21997. <file name="protractor.js" type="protractor">
  21998. it('should execute ng-click but not reload when href without value', function() {
  21999. element(by.id('link-1')).click();
  22000. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  22001. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  22002. });
  22003. it('should execute ng-click but not reload when href empty string', function() {
  22004. element(by.id('link-2')).click();
  22005. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  22006. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  22007. });
  22008. it('should execute ng-click and change url when ng-href specified', function() {
  22009. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  22010. element(by.id('link-3')).click();
  22011. // At this point, we navigate away from an AngularJS page, so we need
  22012. // to use browser.driver to get the base webdriver.
  22013. browser.wait(function() {
  22014. return browser.driver.getCurrentUrl().then(function(url) {
  22015. return url.match(/\/123$/);
  22016. });
  22017. }, 5000, 'page should navigate to /123');
  22018. });
  22019. it('should execute ng-click but not reload when href empty string and name specified', function() {
  22020. element(by.id('link-4')).click();
  22021. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  22022. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  22023. });
  22024. it('should execute ng-click but not reload when no href but name specified', function() {
  22025. element(by.id('link-5')).click();
  22026. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  22027. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  22028. });
  22029. it('should only change url when only ng-href', function() {
  22030. element(by.model('value')).clear();
  22031. element(by.model('value')).sendKeys('6');
  22032. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  22033. element(by.id('link-6')).click();
  22034. // At this point, we navigate away from an AngularJS page, so we need
  22035. // to use browser.driver to get the base webdriver.
  22036. browser.wait(function() {
  22037. return browser.driver.getCurrentUrl().then(function(url) {
  22038. return url.match(/\/6$/);
  22039. });
  22040. }, 5000, 'page should navigate to /6');
  22041. });
  22042. </file>
  22043. </example>
  22044. */
  22045. /**
  22046. * @ngdoc directive
  22047. * @name ngSrc
  22048. * @restrict A
  22049. * @priority 99
  22050. *
  22051. * @description
  22052. * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't
  22053. * work right: The browser will fetch from the URL with the literal
  22054. * text `{{hash}}` until AngularJS replaces the expression inside
  22055. * `{{hash}}`. The `ngSrc` directive solves this problem.
  22056. *
  22057. * The buggy way to write it:
  22058. * ```html
  22059. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  22060. * ```
  22061. *
  22062. * The correct way to write it:
  22063. * ```html
  22064. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  22065. * ```
  22066. *
  22067. * @element IMG
  22068. * @param {template} ngSrc any string which can contain `{{}}` markup.
  22069. */
  22070. /**
  22071. * @ngdoc directive
  22072. * @name ngSrcset
  22073. * @restrict A
  22074. * @priority 99
  22075. *
  22076. * @description
  22077. * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't
  22078. * work right: The browser will fetch from the URL with the literal
  22079. * text `{{hash}}` until AngularJS replaces the expression inside
  22080. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  22081. *
  22082. * The buggy way to write it:
  22083. * ```html
  22084. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  22085. * ```
  22086. *
  22087. * The correct way to write it:
  22088. * ```html
  22089. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  22090. * ```
  22091. *
  22092. * @element IMG
  22093. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  22094. */
  22095. /**
  22096. * @ngdoc directive
  22097. * @name ngDisabled
  22098. * @restrict A
  22099. * @priority 100
  22100. *
  22101. * @description
  22102. *
  22103. * This directive sets the `disabled` attribute on the element (typically a form control,
  22104. * e.g. `input`, `button`, `select` etc.) if the
  22105. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  22106. *
  22107. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  22108. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22109. *
  22110. * @example
  22111. <example name="ng-disabled">
  22112. <file name="index.html">
  22113. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  22114. <button ng-model="button" ng-disabled="checked">Button</button>
  22115. </file>
  22116. <file name="protractor.js" type="protractor">
  22117. it('should toggle button', function() {
  22118. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  22119. element(by.model('checked')).click();
  22120. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  22121. });
  22122. </file>
  22123. </example>
  22124. *
  22125. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  22126. * then the `disabled` attribute will be set on the element
  22127. */
  22128. /**
  22129. * @ngdoc directive
  22130. * @name ngChecked
  22131. * @restrict A
  22132. * @priority 100
  22133. *
  22134. * @description
  22135. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  22136. *
  22137. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  22138. * as this can lead to unexpected behavior.
  22139. *
  22140. * A special directive is necessary because we cannot use interpolation inside the `checked`
  22141. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22142. *
  22143. * @example
  22144. <example name="ng-checked">
  22145. <file name="index.html">
  22146. <label>Check me to check both: <input type="checkbox" ng-model="leader"></label><br/>
  22147. <input id="checkFollower" type="checkbox" ng-checked="leader" aria-label="Follower input">
  22148. </file>
  22149. <file name="protractor.js" type="protractor">
  22150. it('should check both checkBoxes', function() {
  22151. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy();
  22152. element(by.model('leader')).click();
  22153. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy();
  22154. });
  22155. </file>
  22156. </example>
  22157. *
  22158. * @element INPUT
  22159. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  22160. * then the `checked` attribute will be set on the element
  22161. */
  22162. /**
  22163. * @ngdoc directive
  22164. * @name ngReadonly
  22165. * @restrict A
  22166. * @priority 100
  22167. *
  22168. * @description
  22169. *
  22170. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  22171. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  22172. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  22173. *
  22174. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  22175. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22176. *
  22177. * @example
  22178. <example name="ng-readonly">
  22179. <file name="index.html">
  22180. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  22181. <input type="text" ng-readonly="checked" value="I'm AngularJS" aria-label="Readonly field" />
  22182. </file>
  22183. <file name="protractor.js" type="protractor">
  22184. it('should toggle readonly attr', function() {
  22185. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  22186. element(by.model('checked')).click();
  22187. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  22188. });
  22189. </file>
  22190. </example>
  22191. *
  22192. * @element INPUT
  22193. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  22194. * then special attribute "readonly" will be set on the element
  22195. */
  22196. /**
  22197. * @ngdoc directive
  22198. * @name ngSelected
  22199. * @restrict A
  22200. * @priority 100
  22201. *
  22202. * @description
  22203. *
  22204. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  22205. *
  22206. * A special directive is necessary because we cannot use interpolation inside the `selected`
  22207. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22208. *
  22209. * <div class="alert alert-warning">
  22210. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  22211. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  22212. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  22213. * selected options.
  22214. * </div>
  22215. *
  22216. * @example
  22217. <example name="ng-selected">
  22218. <file name="index.html">
  22219. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  22220. <select aria-label="ngSelected demo">
  22221. <option>Hello!</option>
  22222. <option id="greet" ng-selected="selected">Greetings!</option>
  22223. </select>
  22224. </file>
  22225. <file name="protractor.js" type="protractor">
  22226. it('should select Greetings!', function() {
  22227. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  22228. element(by.model('selected')).click();
  22229. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  22230. });
  22231. </file>
  22232. </example>
  22233. *
  22234. * @element OPTION
  22235. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  22236. * then special attribute "selected" will be set on the element
  22237. */
  22238. /**
  22239. * @ngdoc directive
  22240. * @name ngOpen
  22241. * @restrict A
  22242. * @priority 100
  22243. *
  22244. * @description
  22245. *
  22246. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  22247. *
  22248. * A special directive is necessary because we cannot use interpolation inside the `open`
  22249. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22250. *
  22251. * ## A note about browser compatibility
  22252. *
  22253. * Internet Explorer and Edge do not support the `details` element, it is
  22254. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  22255. *
  22256. * @example
  22257. <example name="ng-open">
  22258. <file name="index.html">
  22259. <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/>
  22260. <details id="details" ng-open="open">
  22261. <summary>List</summary>
  22262. <ul>
  22263. <li>Apple</li>
  22264. <li>Orange</li>
  22265. <li>Durian</li>
  22266. </ul>
  22267. </details>
  22268. </file>
  22269. <file name="protractor.js" type="protractor">
  22270. it('should toggle open', function() {
  22271. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  22272. element(by.model('open')).click();
  22273. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  22274. });
  22275. </file>
  22276. </example>
  22277. *
  22278. * @element DETAILS
  22279. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  22280. * then special attribute "open" will be set on the element
  22281. */
  22282. var ngAttributeAliasDirectives = {};
  22283. // boolean attrs are evaluated
  22284. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  22285. // binding to multiple is not supported
  22286. if (propName === 'multiple') return;
  22287. function defaultLinkFn(scope, element, attr) {
  22288. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  22289. attr.$set(attrName, !!value);
  22290. });
  22291. }
  22292. var normalized = directiveNormalize('ng-' + attrName);
  22293. var linkFn = defaultLinkFn;
  22294. if (propName === 'checked') {
  22295. linkFn = function(scope, element, attr) {
  22296. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  22297. if (attr.ngModel !== attr[normalized]) {
  22298. defaultLinkFn(scope, element, attr);
  22299. }
  22300. };
  22301. }
  22302. ngAttributeAliasDirectives[normalized] = function() {
  22303. return {
  22304. restrict: 'A',
  22305. priority: 100,
  22306. link: linkFn
  22307. };
  22308. };
  22309. });
  22310. // aliased input attrs are evaluated
  22311. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  22312. ngAttributeAliasDirectives[ngAttr] = function() {
  22313. return {
  22314. priority: 100,
  22315. link: function(scope, element, attr) {
  22316. //special case ngPattern when a literal regular expression value
  22317. //is used as the expression (this way we don't have to watch anything).
  22318. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  22319. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  22320. if (match) {
  22321. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  22322. return;
  22323. }
  22324. }
  22325. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  22326. attr.$set(ngAttr, value);
  22327. });
  22328. }
  22329. };
  22330. };
  22331. });
  22332. // ng-src, ng-srcset, ng-href are interpolated
  22333. forEach(['src', 'srcset', 'href'], function(attrName) {
  22334. var normalized = directiveNormalize('ng-' + attrName);
  22335. ngAttributeAliasDirectives[normalized] = ['$sce', function($sce) {
  22336. return {
  22337. priority: 99, // it needs to run after the attributes are interpolated
  22338. link: function(scope, element, attr) {
  22339. var propName = attrName,
  22340. name = attrName;
  22341. if (attrName === 'href' &&
  22342. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  22343. name = 'xlinkHref';
  22344. attr.$attr[name] = 'xlink:href';
  22345. propName = null;
  22346. }
  22347. // We need to sanitize the url at least once, in case it is a constant
  22348. // non-interpolated attribute.
  22349. attr.$set(normalized, $sce.getTrustedMediaUrl(attr[normalized]));
  22350. attr.$observe(normalized, function(value) {
  22351. if (!value) {
  22352. if (attrName === 'href') {
  22353. attr.$set(name, null);
  22354. }
  22355. return;
  22356. }
  22357. attr.$set(name, value);
  22358. // Support: IE 9-11 only
  22359. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  22360. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  22361. // to set the property as well to achieve the desired effect.
  22362. // We use attr[attrName] value since $set might have sanitized the url.
  22363. if (msie && propName) element.prop(propName, attr[name]);
  22364. });
  22365. }
  22366. };
  22367. }];
  22368. });
  22369. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  22370. */
  22371. var nullFormCtrl = {
  22372. $addControl: noop,
  22373. $getControls: valueFn([]),
  22374. $$renameControl: nullFormRenameControl,
  22375. $removeControl: noop,
  22376. $setValidity: noop,
  22377. $setDirty: noop,
  22378. $setPristine: noop,
  22379. $setSubmitted: noop,
  22380. $$setSubmitted: noop
  22381. },
  22382. PENDING_CLASS = 'ng-pending',
  22383. SUBMITTED_CLASS = 'ng-submitted';
  22384. function nullFormRenameControl(control, name) {
  22385. control.$name = name;
  22386. }
  22387. /**
  22388. * @ngdoc type
  22389. * @name form.FormController
  22390. *
  22391. * @property {boolean} $pristine True if user has not interacted with the form yet.
  22392. * @property {boolean} $dirty True if user has already interacted with the form.
  22393. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  22394. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  22395. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  22396. *
  22397. * @property {Object} $pending An object hash, containing references to controls or forms with
  22398. * pending validators, where:
  22399. *
  22400. * - keys are validations tokens (error names).
  22401. * - values are arrays of controls or forms that have a pending validator for the given error name.
  22402. *
  22403. * See {@link form.FormController#$error $error} for a list of built-in validation tokens.
  22404. *
  22405. * @property {Object} $error An object hash, containing references to controls or forms with failing
  22406. * validators, where:
  22407. *
  22408. * - keys are validation tokens (error names),
  22409. * - values are arrays of controls or forms that have a failing validator for the given error name.
  22410. *
  22411. * Built-in validation tokens:
  22412. * - `email`
  22413. * - `max`
  22414. * - `maxlength`
  22415. * - `min`
  22416. * - `minlength`
  22417. * - `number`
  22418. * - `pattern`
  22419. * - `required`
  22420. * - `url`
  22421. * - `date`
  22422. * - `datetimelocal`
  22423. * - `time`
  22424. * - `week`
  22425. * - `month`
  22426. *
  22427. * @description
  22428. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  22429. * such as being valid/invalid or dirty/pristine.
  22430. *
  22431. * Each {@link ng.directive:form form} directive creates an instance
  22432. * of `FormController`.
  22433. *
  22434. */
  22435. //asks for $scope to fool the BC controller module
  22436. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  22437. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  22438. this.$$controls = [];
  22439. // init state
  22440. this.$error = {};
  22441. this.$$success = {};
  22442. this.$pending = undefined;
  22443. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  22444. this.$dirty = false;
  22445. this.$pristine = true;
  22446. this.$valid = true;
  22447. this.$invalid = false;
  22448. this.$submitted = false;
  22449. this.$$parentForm = nullFormCtrl;
  22450. this.$$element = $element;
  22451. this.$$animate = $animate;
  22452. setupValidity(this);
  22453. }
  22454. FormController.prototype = {
  22455. /**
  22456. * @ngdoc method
  22457. * @name form.FormController#$rollbackViewValue
  22458. *
  22459. * @description
  22460. * Rollback all form controls pending updates to the `$modelValue`.
  22461. *
  22462. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22463. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  22464. * a form that uses `ng-model-options` to pend updates.
  22465. */
  22466. $rollbackViewValue: function() {
  22467. forEach(this.$$controls, function(control) {
  22468. control.$rollbackViewValue();
  22469. });
  22470. },
  22471. /**
  22472. * @ngdoc method
  22473. * @name form.FormController#$commitViewValue
  22474. *
  22475. * @description
  22476. * Commit all form controls pending updates to the `$modelValue`.
  22477. *
  22478. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22479. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  22480. * usually handles calling this in response to input events.
  22481. */
  22482. $commitViewValue: function() {
  22483. forEach(this.$$controls, function(control) {
  22484. control.$commitViewValue();
  22485. });
  22486. },
  22487. /**
  22488. * @ngdoc method
  22489. * @name form.FormController#$addControl
  22490. * @param {object} control control object, either a {@link form.FormController} or an
  22491. * {@link ngModel.NgModelController}
  22492. *
  22493. * @description
  22494. * Register a control with the form. Input elements using ngModelController do this automatically
  22495. * when they are linked.
  22496. *
  22497. * Note that the current state of the control will not be reflected on the new parent form. This
  22498. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  22499. * state.
  22500. *
  22501. * However, if the method is used programmatically, for example by adding dynamically created controls,
  22502. * or controls that have been previously removed without destroying their corresponding DOM element,
  22503. * it's the developers responsibility to make sure the current state propagates to the parent form.
  22504. *
  22505. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  22506. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  22507. */
  22508. $addControl: function(control) {
  22509. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  22510. // and not added to the scope. Now we throw an error.
  22511. assertNotHasOwnProperty(control.$name, 'input');
  22512. this.$$controls.push(control);
  22513. if (control.$name) {
  22514. this[control.$name] = control;
  22515. }
  22516. control.$$parentForm = this;
  22517. },
  22518. /**
  22519. * @ngdoc method
  22520. * @name form.FormController#$getControls
  22521. * @returns {Array} the controls that are currently part of this form
  22522. *
  22523. * @description
  22524. * This method returns a **shallow copy** of the controls that are currently part of this form.
  22525. * The controls can be instances of {@link form.FormController `FormController`}
  22526. * ({@link ngForm "child-forms"}) and of {@link ngModel.NgModelController `NgModelController`}.
  22527. * If you need access to the controls of child-forms, you have to call `$getControls()`
  22528. * recursively on them.
  22529. * This can be used for example to iterate over all controls to validate them.
  22530. *
  22531. * The controls can be accessed normally, but adding to, or removing controls from the array has
  22532. * no effect on the form. Instead, use {@link form.FormController#$addControl `$addControl()`} and
  22533. * {@link form.FormController#$removeControl `$removeControl()`} for this use-case.
  22534. * Likewise, adding a control to, or removing a control from the form is not reflected
  22535. * in the shallow copy. That means you should get a fresh copy from `$getControls()` every time
  22536. * you need access to the controls.
  22537. */
  22538. $getControls: function() {
  22539. return shallowCopy(this.$$controls);
  22540. },
  22541. // Private API: rename a form control
  22542. $$renameControl: function(control, newName) {
  22543. var oldName = control.$name;
  22544. if (this[oldName] === control) {
  22545. delete this[oldName];
  22546. }
  22547. this[newName] = control;
  22548. control.$name = newName;
  22549. },
  22550. /**
  22551. * @ngdoc method
  22552. * @name form.FormController#$removeControl
  22553. * @param {object} control control object, either a {@link form.FormController} or an
  22554. * {@link ngModel.NgModelController}
  22555. *
  22556. * @description
  22557. * Deregister a control from the form.
  22558. *
  22559. * Input elements using ngModelController do this automatically when they are destroyed.
  22560. *
  22561. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  22562. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  22563. * different from case to case. For example, removing the only `$dirty` control from a form may or
  22564. * may not mean that the form is still `$dirty`.
  22565. */
  22566. $removeControl: function(control) {
  22567. if (control.$name && this[control.$name] === control) {
  22568. delete this[control.$name];
  22569. }
  22570. forEach(this.$pending, function(value, name) {
  22571. // eslint-disable-next-line no-invalid-this
  22572. this.$setValidity(name, null, control);
  22573. }, this);
  22574. forEach(this.$error, function(value, name) {
  22575. // eslint-disable-next-line no-invalid-this
  22576. this.$setValidity(name, null, control);
  22577. }, this);
  22578. forEach(this.$$success, function(value, name) {
  22579. // eslint-disable-next-line no-invalid-this
  22580. this.$setValidity(name, null, control);
  22581. }, this);
  22582. arrayRemove(this.$$controls, control);
  22583. control.$$parentForm = nullFormCtrl;
  22584. },
  22585. /**
  22586. * @ngdoc method
  22587. * @name form.FormController#$setDirty
  22588. *
  22589. * @description
  22590. * Sets the form to a dirty state.
  22591. *
  22592. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  22593. * state (ng-dirty class). This method will also propagate to parent forms.
  22594. */
  22595. $setDirty: function() {
  22596. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  22597. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  22598. this.$dirty = true;
  22599. this.$pristine = false;
  22600. this.$$parentForm.$setDirty();
  22601. },
  22602. /**
  22603. * @ngdoc method
  22604. * @name form.FormController#$setPristine
  22605. *
  22606. * @description
  22607. * Sets the form to its pristine state.
  22608. *
  22609. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  22610. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  22611. * state to false.
  22612. *
  22613. * This method will also propagate to all the controls contained in this form.
  22614. *
  22615. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  22616. * saving or resetting it.
  22617. */
  22618. $setPristine: function() {
  22619. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  22620. this.$dirty = false;
  22621. this.$pristine = true;
  22622. this.$submitted = false;
  22623. forEach(this.$$controls, function(control) {
  22624. control.$setPristine();
  22625. });
  22626. },
  22627. /**
  22628. * @ngdoc method
  22629. * @name form.FormController#$setUntouched
  22630. *
  22631. * @description
  22632. * Sets the form to its untouched state.
  22633. *
  22634. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  22635. * untouched state (ng-untouched class).
  22636. *
  22637. * Setting a form controls back to their untouched state is often useful when setting the form
  22638. * back to its pristine state.
  22639. */
  22640. $setUntouched: function() {
  22641. forEach(this.$$controls, function(control) {
  22642. control.$setUntouched();
  22643. });
  22644. },
  22645. /**
  22646. * @ngdoc method
  22647. * @name form.FormController#$setSubmitted
  22648. *
  22649. * @description
  22650. * Sets the form to its `$submitted` state. This will also set `$submitted` on all child and
  22651. * parent forms of the form.
  22652. */
  22653. $setSubmitted: function() {
  22654. var rootForm = this;
  22655. while (rootForm.$$parentForm && (rootForm.$$parentForm !== nullFormCtrl)) {
  22656. rootForm = rootForm.$$parentForm;
  22657. }
  22658. rootForm.$$setSubmitted();
  22659. },
  22660. $$setSubmitted: function() {
  22661. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  22662. this.$submitted = true;
  22663. forEach(this.$$controls, function(control) {
  22664. if (control.$$setSubmitted) {
  22665. control.$$setSubmitted();
  22666. }
  22667. });
  22668. }
  22669. };
  22670. /**
  22671. * @ngdoc method
  22672. * @name form.FormController#$setValidity
  22673. *
  22674. * @description
  22675. * Change the validity state of the form, and notify the parent form (if any).
  22676. *
  22677. * Application developers will rarely need to call this method directly. It is used internally, by
  22678. * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a
  22679. * control's validity state to the parent `FormController`.
  22680. *
  22681. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be
  22682. * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for
  22683. * unfulfilled `$asyncValidators`), so that it is available for data-binding. The
  22684. * `validationErrorKey` should be in camelCase and will get converted into dash-case for
  22685. * class name. Example: `myError` will result in `ng-valid-my-error` and
  22686. * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.
  22687. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending
  22688. * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22689. * Skipped is used by AngularJS when validators do not run because of parse errors and when
  22690. * `$asyncValidators` do not run because any of the `$validators` failed.
  22691. * @param {NgModelController | FormController} controller - The controller whose validity state is
  22692. * triggering the change.
  22693. */
  22694. addSetValidityMethod({
  22695. clazz: FormController,
  22696. set: function(object, property, controller) {
  22697. var list = object[property];
  22698. if (!list) {
  22699. object[property] = [controller];
  22700. } else {
  22701. var index = list.indexOf(controller);
  22702. if (index === -1) {
  22703. list.push(controller);
  22704. }
  22705. }
  22706. },
  22707. unset: function(object, property, controller) {
  22708. var list = object[property];
  22709. if (!list) {
  22710. return;
  22711. }
  22712. arrayRemove(list, controller);
  22713. if (list.length === 0) {
  22714. delete object[property];
  22715. }
  22716. }
  22717. });
  22718. /**
  22719. * @ngdoc directive
  22720. * @name ngForm
  22721. * @restrict EAC
  22722. *
  22723. * @description
  22724. * Helper directive that makes it possible to create control groups inside a
  22725. * {@link ng.directive:form `form`} directive.
  22726. * These "child forms" can be used, for example, to determine the validity of a sub-group of
  22727. * controls.
  22728. *
  22729. * <div class="alert alert-danger">
  22730. * **Note**: `ngForm` cannot be used as a replacement for `<form>`, because it lacks its
  22731. * [built-in HTML functionality](https://html.spec.whatwg.org/#the-form-element).
  22732. * Specifically, you cannot submit `ngForm` like a `<form>` tag. That means,
  22733. * you cannot send data to the server with `ngForm`, or integrate it with
  22734. * {@link ng.directive:ngSubmit `ngSubmit`}.
  22735. * </div>
  22736. *
  22737. * @param {string=} ngForm|name Name of the form. If specified, the form controller will
  22738. * be published into the related scope, under this name.
  22739. *
  22740. */
  22741. /**
  22742. * @ngdoc directive
  22743. * @name form
  22744. * @restrict E
  22745. *
  22746. * @description
  22747. * Directive that instantiates
  22748. * {@link form.FormController FormController}.
  22749. *
  22750. * If the `name` attribute is specified, the form controller is published onto the current scope under
  22751. * this name.
  22752. *
  22753. * ## Alias: {@link ng.directive:ngForm `ngForm`}
  22754. *
  22755. * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child
  22756. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  22757. * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  22758. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  22759. * of controls needs to be determined.
  22760. *
  22761. * ## CSS classes
  22762. * - `ng-valid` is set if the form is valid.
  22763. * - `ng-invalid` is set if the form is invalid.
  22764. * - `ng-pending` is set if the form is pending.
  22765. * - `ng-pristine` is set if the form is pristine.
  22766. * - `ng-dirty` is set if the form is dirty.
  22767. * - `ng-submitted` is set if the form was submitted.
  22768. *
  22769. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  22770. *
  22771. *
  22772. * ## Submitting a form and preventing the default action
  22773. *
  22774. * Since the role of forms in client-side AngularJS applications is different than in classical
  22775. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  22776. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  22777. * to handle the form submission in an application-specific way.
  22778. *
  22779. * For this reason, AngularJS prevents the default action (form submission to the server) unless the
  22780. * `<form>` element has an `action` attribute specified.
  22781. *
  22782. * You can use one of the following two ways to specify what javascript method should be called when
  22783. * a form is submitted:
  22784. *
  22785. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  22786. * - {@link ng.directive:ngClick ngClick} directive on the first
  22787. * button or input field of type submit (input[type=submit])
  22788. *
  22789. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  22790. * or {@link ng.directive:ngClick ngClick} directives.
  22791. * This is because of the following form submission rules in the HTML specification:
  22792. *
  22793. * - If a form has only one input field then hitting enter in this field triggers form submit
  22794. * (`ngSubmit`)
  22795. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  22796. * doesn't trigger submit
  22797. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  22798. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  22799. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  22800. *
  22801. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  22802. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  22803. * to have access to the updated model.
  22804. *
  22805. * @animations
  22806. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  22807. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  22808. * other validations that are performed within the form. Animations in ngForm are similar to how
  22809. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  22810. * as JS animations.
  22811. *
  22812. * The following example shows a simple way to utilize CSS transitions to style a form element
  22813. * that has been rendered as invalid after it has been validated:
  22814. *
  22815. * <pre>
  22816. * //be sure to include ngAnimate as a module to hook into more
  22817. * //advanced animations
  22818. * .my-form {
  22819. * transition:0.5s linear all;
  22820. * background: white;
  22821. * }
  22822. * .my-form.ng-invalid {
  22823. * background: red;
  22824. * color:white;
  22825. * }
  22826. * </pre>
  22827. *
  22828. * @example
  22829. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  22830. <file name="index.html">
  22831. <script>
  22832. angular.module('formExample', [])
  22833. .controller('FormController', ['$scope', function($scope) {
  22834. $scope.userType = 'guest';
  22835. }]);
  22836. </script>
  22837. <style>
  22838. .my-form {
  22839. transition:all linear 0.5s;
  22840. background: transparent;
  22841. }
  22842. .my-form.ng-invalid {
  22843. background: red;
  22844. }
  22845. </style>
  22846. <form name="myForm" ng-controller="FormController" class="my-form">
  22847. userType: <input name="input" ng-model="userType" required>
  22848. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  22849. <code>userType = {{userType}}</code><br>
  22850. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  22851. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  22852. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  22853. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  22854. </form>
  22855. </file>
  22856. <file name="protractor.js" type="protractor">
  22857. it('should initialize to model', function() {
  22858. var userType = element(by.binding('userType'));
  22859. var valid = element(by.binding('myForm.input.$valid'));
  22860. expect(userType.getText()).toContain('guest');
  22861. expect(valid.getText()).toContain('true');
  22862. });
  22863. it('should be invalid if empty', function() {
  22864. var userType = element(by.binding('userType'));
  22865. var valid = element(by.binding('myForm.input.$valid'));
  22866. var userInput = element(by.model('userType'));
  22867. userInput.clear();
  22868. userInput.sendKeys('');
  22869. expect(userType.getText()).toEqual('userType =');
  22870. expect(valid.getText()).toContain('false');
  22871. });
  22872. </file>
  22873. </example>
  22874. *
  22875. * @param {string=} name Name of the form. If specified, the form controller will be published into
  22876. * related scope, under this name.
  22877. */
  22878. var formDirectiveFactory = function(isNgForm) {
  22879. return ['$timeout', '$parse', function($timeout, $parse) {
  22880. var formDirective = {
  22881. name: 'form',
  22882. restrict: isNgForm ? 'EAC' : 'E',
  22883. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  22884. controller: FormController,
  22885. compile: function ngFormCompile(formElement, attr) {
  22886. // Setup initial state of the control
  22887. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  22888. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  22889. return {
  22890. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  22891. var controller = ctrls[0];
  22892. // if `action` attr is not present on the form, prevent the default action (submission)
  22893. if (!('action' in attr)) {
  22894. // we can't use jq events because if a form is destroyed during submission the default
  22895. // action is not prevented. see #1238
  22896. //
  22897. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  22898. // page reload if the form was destroyed by submission of the form via a click handler
  22899. // on a button in the form. Looks like an IE9 specific bug.
  22900. var handleFormSubmission = function(event) {
  22901. scope.$apply(function() {
  22902. controller.$commitViewValue();
  22903. controller.$setSubmitted();
  22904. });
  22905. event.preventDefault();
  22906. };
  22907. formElement[0].addEventListener('submit', handleFormSubmission);
  22908. // unregister the preventDefault listener so that we don't not leak memory but in a
  22909. // way that will achieve the prevention of the default action.
  22910. formElement.on('$destroy', function() {
  22911. $timeout(function() {
  22912. formElement[0].removeEventListener('submit', handleFormSubmission);
  22913. }, 0, false);
  22914. });
  22915. }
  22916. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  22917. parentFormCtrl.$addControl(controller);
  22918. var setter = nameAttr ? getSetter(controller.$name) : noop;
  22919. if (nameAttr) {
  22920. setter(scope, controller);
  22921. attr.$observe(nameAttr, function(newValue) {
  22922. if (controller.$name === newValue) return;
  22923. setter(scope, undefined);
  22924. controller.$$parentForm.$$renameControl(controller, newValue);
  22925. setter = getSetter(controller.$name);
  22926. setter(scope, controller);
  22927. });
  22928. }
  22929. formElement.on('$destroy', function() {
  22930. controller.$$parentForm.$removeControl(controller);
  22931. setter(scope, undefined);
  22932. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  22933. });
  22934. }
  22935. };
  22936. }
  22937. };
  22938. return formDirective;
  22939. function getSetter(expression) {
  22940. if (expression === '') {
  22941. //create an assignable expression, so forms with an empty name can be renamed later
  22942. return $parse('this[""]').assign;
  22943. }
  22944. return $parse(expression).assign || noop;
  22945. }
  22946. }];
  22947. };
  22948. var formDirective = formDirectiveFactory();
  22949. var ngFormDirective = formDirectiveFactory(true);
  22950. // helper methods
  22951. function setupValidity(instance) {
  22952. instance.$$classCache = {};
  22953. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  22954. }
  22955. function addSetValidityMethod(context) {
  22956. var clazz = context.clazz,
  22957. set = context.set,
  22958. unset = context.unset;
  22959. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  22960. if (isUndefined(state)) {
  22961. createAndSet(this, '$pending', validationErrorKey, controller);
  22962. } else {
  22963. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  22964. }
  22965. if (!isBoolean(state)) {
  22966. unset(this.$error, validationErrorKey, controller);
  22967. unset(this.$$success, validationErrorKey, controller);
  22968. } else {
  22969. if (state) {
  22970. unset(this.$error, validationErrorKey, controller);
  22971. set(this.$$success, validationErrorKey, controller);
  22972. } else {
  22973. set(this.$error, validationErrorKey, controller);
  22974. unset(this.$$success, validationErrorKey, controller);
  22975. }
  22976. }
  22977. if (this.$pending) {
  22978. cachedToggleClass(this, PENDING_CLASS, true);
  22979. this.$valid = this.$invalid = undefined;
  22980. toggleValidationCss(this, '', null);
  22981. } else {
  22982. cachedToggleClass(this, PENDING_CLASS, false);
  22983. this.$valid = isObjectEmpty(this.$error);
  22984. this.$invalid = !this.$valid;
  22985. toggleValidationCss(this, '', this.$valid);
  22986. }
  22987. // re-read the state as the set/unset methods could have
  22988. // combined state in this.$error[validationError] (used for forms),
  22989. // where setting/unsetting only increments/decrements the value,
  22990. // and does not replace it.
  22991. var combinedState;
  22992. if (this.$pending && this.$pending[validationErrorKey]) {
  22993. combinedState = undefined;
  22994. } else if (this.$error[validationErrorKey]) {
  22995. combinedState = false;
  22996. } else if (this.$$success[validationErrorKey]) {
  22997. combinedState = true;
  22998. } else {
  22999. combinedState = null;
  23000. }
  23001. toggleValidationCss(this, validationErrorKey, combinedState);
  23002. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  23003. };
  23004. function createAndSet(ctrl, name, value, controller) {
  23005. if (!ctrl[name]) {
  23006. ctrl[name] = {};
  23007. }
  23008. set(ctrl[name], value, controller);
  23009. }
  23010. function unsetAndCleanup(ctrl, name, value, controller) {
  23011. if (ctrl[name]) {
  23012. unset(ctrl[name], value, controller);
  23013. }
  23014. if (isObjectEmpty(ctrl[name])) {
  23015. ctrl[name] = undefined;
  23016. }
  23017. }
  23018. function cachedToggleClass(ctrl, className, switchValue) {
  23019. if (switchValue && !ctrl.$$classCache[className]) {
  23020. ctrl.$$animate.addClass(ctrl.$$element, className);
  23021. ctrl.$$classCache[className] = true;
  23022. } else if (!switchValue && ctrl.$$classCache[className]) {
  23023. ctrl.$$animate.removeClass(ctrl.$$element, className);
  23024. ctrl.$$classCache[className] = false;
  23025. }
  23026. }
  23027. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  23028. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23029. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  23030. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  23031. }
  23032. }
  23033. function isObjectEmpty(obj) {
  23034. if (obj) {
  23035. for (var prop in obj) {
  23036. if (obj.hasOwnProperty(prop)) {
  23037. return false;
  23038. }
  23039. }
  23040. }
  23041. return true;
  23042. }
  23043. /* global
  23044. VALID_CLASS: false,
  23045. INVALID_CLASS: false,
  23046. PRISTINE_CLASS: false,
  23047. DIRTY_CLASS: false,
  23048. ngModelMinErr: false
  23049. */
  23050. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  23051. 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)$/;
  23052. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  23053. // Note: We are being more lenient, because browsers are too.
  23054. // 1. Scheme
  23055. // 2. Slashes
  23056. // 3. Username
  23057. // 4. Password
  23058. // 5. Hostname
  23059. // 6. Port
  23060. // 7. Path
  23061. // 8. Query
  23062. // 9. Fragment
  23063. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  23064. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  23065. // eslint-disable-next-line max-len
  23066. 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])?)*$/;
  23067. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  23068. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  23069. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  23070. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  23071. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  23072. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  23073. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  23074. var PARTIAL_VALIDATION_TYPES = createMap();
  23075. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  23076. PARTIAL_VALIDATION_TYPES[type] = true;
  23077. });
  23078. var inputType = {
  23079. /**
  23080. * @ngdoc input
  23081. * @name input[text]
  23082. *
  23083. * @description
  23084. * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements.
  23085. *
  23086. *
  23087. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23088. * @param {string=} name Property name of the form under which the control is published.
  23089. * @param {string=} required Adds `required` validation error key if the value is not entered.
  23090. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23091. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23092. * `required` when you want to data-bind to the `required` attribute.
  23093. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23094. * minlength.
  23095. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23096. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23097. * any length.
  23098. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23099. * that contains the regular expression body that will be converted to a regular expression
  23100. * as in the ngPattern directive.
  23101. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23102. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23103. * If the expression evaluates to a RegExp object, then this is used directly.
  23104. * If the expression evaluates to a string, then it will be converted to a RegExp
  23105. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23106. * `new RegExp('^abc$')`.<br />
  23107. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23108. * start at the index of the last search's match, thus not taking the whole input value into
  23109. * account.
  23110. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23111. * interaction with the input element.
  23112. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  23113. * This parameter is ignored for input[type=password] controls, which will never trim the
  23114. * input.
  23115. *
  23116. * @example
  23117. <example name="text-input-directive" module="textInputExample">
  23118. <file name="index.html">
  23119. <script>
  23120. angular.module('textInputExample', [])
  23121. .controller('ExampleController', ['$scope', function($scope) {
  23122. $scope.example = {
  23123. text: 'guest',
  23124. word: /^\s*\w*\s*$/
  23125. };
  23126. }]);
  23127. </script>
  23128. <form name="myForm" ng-controller="ExampleController">
  23129. <label>Single word:
  23130. <input type="text" name="input" ng-model="example.text"
  23131. ng-pattern="example.word" required ng-trim="false">
  23132. </label>
  23133. <div role="alert">
  23134. <span class="error" ng-show="myForm.input.$error.required">
  23135. Required!</span>
  23136. <span class="error" ng-show="myForm.input.$error.pattern">
  23137. Single word only!</span>
  23138. </div>
  23139. <code>text = {{example.text}}</code><br/>
  23140. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  23141. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  23142. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  23143. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  23144. </form>
  23145. </file>
  23146. <file name="protractor.js" type="protractor">
  23147. var text = element(by.binding('example.text'));
  23148. var valid = element(by.binding('myForm.input.$valid'));
  23149. var input = element(by.model('example.text'));
  23150. it('should initialize to model', function() {
  23151. expect(text.getText()).toContain('guest');
  23152. expect(valid.getText()).toContain('true');
  23153. });
  23154. it('should be invalid if empty', function() {
  23155. input.clear();
  23156. input.sendKeys('');
  23157. expect(text.getText()).toEqual('text =');
  23158. expect(valid.getText()).toContain('false');
  23159. });
  23160. it('should be invalid if multi word', function() {
  23161. input.clear();
  23162. input.sendKeys('hello world');
  23163. expect(valid.getText()).toContain('false');
  23164. });
  23165. </file>
  23166. </example>
  23167. */
  23168. 'text': textInputType,
  23169. /**
  23170. * @ngdoc input
  23171. * @name input[date]
  23172. *
  23173. * @description
  23174. * Input with date validation and transformation. In browsers that do not yet support
  23175. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  23176. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  23177. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  23178. * expected input format via a placeholder or label.
  23179. *
  23180. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23181. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23182. *
  23183. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23184. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23185. *
  23186. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23187. * @param {string=} name Property name of the form under which the control is published.
  23188. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  23189. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  23190. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  23191. * constraint validation.
  23192. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  23193. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  23194. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  23195. * constraint validation.
  23196. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  23197. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23198. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  23199. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23200. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23201. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23202. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23203. * `required` when you want to data-bind to the `required` attribute.
  23204. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23205. * interaction with the input element.
  23206. *
  23207. * @example
  23208. <example name="date-input-directive" module="dateInputExample">
  23209. <file name="index.html">
  23210. <script>
  23211. angular.module('dateInputExample', [])
  23212. .controller('DateController', ['$scope', function($scope) {
  23213. $scope.example = {
  23214. value: new Date(2013, 9, 22)
  23215. };
  23216. }]);
  23217. </script>
  23218. <form name="myForm" ng-controller="DateController as dateCtrl">
  23219. <label for="exampleInput">Pick a date in 2013:</label>
  23220. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  23221. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  23222. <div role="alert">
  23223. <span class="error" ng-show="myForm.input.$error.required">
  23224. Required!</span>
  23225. <span class="error" ng-show="myForm.input.$error.date">
  23226. Not a valid date!</span>
  23227. </div>
  23228. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  23229. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23230. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23231. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23232. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23233. </form>
  23234. </file>
  23235. <file name="protractor.js" type="protractor">
  23236. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  23237. var valid = element(by.binding('myForm.input.$valid'));
  23238. // currently protractor/webdriver does not support
  23239. // sending keys to all known HTML5 input controls
  23240. // for various browsers (see https://github.com/angular/protractor/issues/562).
  23241. function setInput(val) {
  23242. // set the value of the element and force validation.
  23243. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23244. "ipt.value = '" + val + "';" +
  23245. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23246. browser.executeScript(scr);
  23247. }
  23248. it('should initialize to model', function() {
  23249. expect(value.getText()).toContain('2013-10-22');
  23250. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23251. });
  23252. it('should be invalid if empty', function() {
  23253. setInput('');
  23254. expect(value.getText()).toEqual('value =');
  23255. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23256. });
  23257. it('should be invalid if over max', function() {
  23258. setInput('2015-01-01');
  23259. expect(value.getText()).toContain('');
  23260. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23261. });
  23262. </file>
  23263. </example>
  23264. */
  23265. 'date': createDateInputType('date', DATE_REGEXP,
  23266. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  23267. 'yyyy-MM-dd'),
  23268. /**
  23269. * @ngdoc input
  23270. * @name input[datetime-local]
  23271. *
  23272. * @description
  23273. * Input with datetime validation and transformation. In browsers that do not yet support
  23274. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23275. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  23276. *
  23277. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23278. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23279. *
  23280. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23281. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23282. *
  23283. * The format of the displayed time can be adjusted with the
  23284. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`
  23285. * and `timeStripZeroSeconds`.
  23286. *
  23287. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23288. * @param {string=} name Property name of the form under which the control is published.
  23289. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23290. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  23291. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  23292. * Note that `min` will also add native HTML5 constraint validation.
  23293. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23294. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  23295. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  23296. * Note that `max` will also add native HTML5 constraint validation.
  23297. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  23298. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23299. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  23300. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23301. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23302. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23303. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23304. * `required` when you want to data-bind to the `required` attribute.
  23305. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23306. * interaction with the input element.
  23307. *
  23308. * @example
  23309. <example name="datetimelocal-input-directive" module="dateExample">
  23310. <file name="index.html">
  23311. <script>
  23312. angular.module('dateExample', [])
  23313. .controller('DateController', ['$scope', function($scope) {
  23314. $scope.example = {
  23315. value: new Date(2010, 11, 28, 14, 57)
  23316. };
  23317. }]);
  23318. </script>
  23319. <form name="myForm" ng-controller="DateController as dateCtrl">
  23320. <label for="exampleInput">Pick a date between in 2013:</label>
  23321. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  23322. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  23323. <div role="alert">
  23324. <span class="error" ng-show="myForm.input.$error.required">
  23325. Required!</span>
  23326. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  23327. Not a valid date!</span>
  23328. </div>
  23329. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  23330. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23331. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23332. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23333. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23334. </form>
  23335. </file>
  23336. <file name="protractor.js" type="protractor">
  23337. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  23338. var valid = element(by.binding('myForm.input.$valid'));
  23339. // currently protractor/webdriver does not support
  23340. // sending keys to all known HTML5 input controls
  23341. // for various browsers (https://github.com/angular/protractor/issues/562).
  23342. function setInput(val) {
  23343. // set the value of the element and force validation.
  23344. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23345. "ipt.value = '" + val + "';" +
  23346. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23347. browser.executeScript(scr);
  23348. }
  23349. it('should initialize to model', function() {
  23350. expect(value.getText()).toContain('2010-12-28T14:57:00');
  23351. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23352. });
  23353. it('should be invalid if empty', function() {
  23354. setInput('');
  23355. expect(value.getText()).toEqual('value =');
  23356. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23357. });
  23358. it('should be invalid if over max', function() {
  23359. setInput('2015-01-01T23:59:00');
  23360. expect(value.getText()).toContain('');
  23361. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23362. });
  23363. </file>
  23364. </example>
  23365. */
  23366. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  23367. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  23368. 'yyyy-MM-ddTHH:mm:ss.sss'),
  23369. /**
  23370. * @ngdoc input
  23371. * @name input[time]
  23372. *
  23373. * @description
  23374. * Input with time validation and transformation. In browsers that do not yet support
  23375. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23376. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  23377. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  23378. *
  23379. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23380. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23381. *
  23382. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23383. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions}. By default,
  23384. * this is the timezone of the browser.
  23385. *
  23386. * The format of the displayed time can be adjusted with the
  23387. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`
  23388. * and `timeStripZeroSeconds`.
  23389. *
  23390. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23391. * @param {string=} name Property name of the form under which the control is published.
  23392. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23393. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  23394. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  23395. * native HTML5 constraint validation.
  23396. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23397. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  23398. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  23399. * native HTML5 constraint validation.
  23400. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  23401. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23402. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  23403. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23404. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23405. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23406. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23407. * `required` when you want to data-bind to the `required` attribute.
  23408. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23409. * interaction with the input element.
  23410. *
  23411. * @example
  23412. <example name="time-input-directive" module="timeExample">
  23413. <file name="index.html">
  23414. <script>
  23415. angular.module('timeExample', [])
  23416. .controller('DateController', ['$scope', function($scope) {
  23417. $scope.example = {
  23418. value: new Date(1970, 0, 1, 14, 57, 0)
  23419. };
  23420. }]);
  23421. </script>
  23422. <form name="myForm" ng-controller="DateController as dateCtrl">
  23423. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  23424. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  23425. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  23426. <div role="alert">
  23427. <span class="error" ng-show="myForm.input.$error.required">
  23428. Required!</span>
  23429. <span class="error" ng-show="myForm.input.$error.time">
  23430. Not a valid date!</span>
  23431. </div>
  23432. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  23433. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23434. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23435. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23436. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23437. </form>
  23438. </file>
  23439. <file name="protractor.js" type="protractor">
  23440. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  23441. var valid = element(by.binding('myForm.input.$valid'));
  23442. // currently protractor/webdriver does not support
  23443. // sending keys to all known HTML5 input controls
  23444. // for various browsers (https://github.com/angular/protractor/issues/562).
  23445. function setInput(val) {
  23446. // set the value of the element and force validation.
  23447. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23448. "ipt.value = '" + val + "';" +
  23449. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23450. browser.executeScript(scr);
  23451. }
  23452. it('should initialize to model', function() {
  23453. expect(value.getText()).toContain('14:57:00');
  23454. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23455. });
  23456. it('should be invalid if empty', function() {
  23457. setInput('');
  23458. expect(value.getText()).toEqual('value =');
  23459. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23460. });
  23461. it('should be invalid if over max', function() {
  23462. setInput('23:59:00');
  23463. expect(value.getText()).toContain('');
  23464. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23465. });
  23466. </file>
  23467. </example>
  23468. */
  23469. 'time': createDateInputType('time', TIME_REGEXP,
  23470. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  23471. 'HH:mm:ss.sss'),
  23472. /**
  23473. * @ngdoc input
  23474. * @name input[week]
  23475. *
  23476. * @description
  23477. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  23478. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23479. * week format (yyyy-W##), for example: `2013-W02`.
  23480. *
  23481. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23482. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23483. *
  23484. * The value of the resulting Date object will be set to Thursday at 00:00:00 of the requested week,
  23485. * due to ISO-8601 week numbering standards. Information on ISO's system for numbering the weeks of the
  23486. * year can be found at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates
  23487. *
  23488. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23489. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23490. *
  23491. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23492. * @param {string=} name Property name of the form under which the control is published.
  23493. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23494. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  23495. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  23496. * native HTML5 constraint validation.
  23497. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23498. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  23499. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  23500. * native HTML5 constraint validation.
  23501. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  23502. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23503. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  23504. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23505. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23506. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23507. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23508. * `required` when you want to data-bind to the `required` attribute.
  23509. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23510. * interaction with the input element.
  23511. *
  23512. * @example
  23513. <example name="week-input-directive" module="weekExample">
  23514. <file name="index.html">
  23515. <script>
  23516. angular.module('weekExample', [])
  23517. .controller('DateController', ['$scope', function($scope) {
  23518. $scope.example = {
  23519. value: new Date(2013, 0, 3)
  23520. };
  23521. }]);
  23522. </script>
  23523. <form name="myForm" ng-controller="DateController as dateCtrl">
  23524. <label>Pick a date between in 2013:
  23525. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  23526. placeholder="YYYY-W##" min="2012-W32"
  23527. max="2013-W52" required />
  23528. </label>
  23529. <div role="alert">
  23530. <span class="error" ng-show="myForm.input.$error.required">
  23531. Required!</span>
  23532. <span class="error" ng-show="myForm.input.$error.week">
  23533. Not a valid date!</span>
  23534. </div>
  23535. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  23536. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23537. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23538. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23539. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23540. </form>
  23541. </file>
  23542. <file name="protractor.js" type="protractor">
  23543. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  23544. var valid = element(by.binding('myForm.input.$valid'));
  23545. // currently protractor/webdriver does not support
  23546. // sending keys to all known HTML5 input controls
  23547. // for various browsers (https://github.com/angular/protractor/issues/562).
  23548. function setInput(val) {
  23549. // set the value of the element and force validation.
  23550. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23551. "ipt.value = '" + val + "';" +
  23552. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23553. browser.executeScript(scr);
  23554. }
  23555. it('should initialize to model', function() {
  23556. expect(value.getText()).toContain('2013-W01');
  23557. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23558. });
  23559. it('should be invalid if empty', function() {
  23560. setInput('');
  23561. expect(value.getText()).toEqual('value =');
  23562. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23563. });
  23564. it('should be invalid if over max', function() {
  23565. setInput('2015-W01');
  23566. expect(value.getText()).toContain('');
  23567. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23568. });
  23569. </file>
  23570. </example>
  23571. */
  23572. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  23573. /**
  23574. * @ngdoc input
  23575. * @name input[month]
  23576. *
  23577. * @description
  23578. * Input with month validation and transformation. In browsers that do not yet support
  23579. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23580. * month format (yyyy-MM), for example: `2009-01`.
  23581. *
  23582. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23583. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23584. * If the model is not set to the first of the month, the next view to model update will set it
  23585. * to the first of the month.
  23586. *
  23587. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23588. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23589. *
  23590. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23591. * @param {string=} name Property name of the form under which the control is published.
  23592. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23593. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  23594. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  23595. * native HTML5 constraint validation.
  23596. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23597. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  23598. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  23599. * native HTML5 constraint validation.
  23600. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  23601. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23602. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  23603. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23604. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23605. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23606. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23607. * `required` when you want to data-bind to the `required` attribute.
  23608. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23609. * interaction with the input element.
  23610. *
  23611. * @example
  23612. <example name="month-input-directive" module="monthExample">
  23613. <file name="index.html">
  23614. <script>
  23615. angular.module('monthExample', [])
  23616. .controller('DateController', ['$scope', function($scope) {
  23617. $scope.example = {
  23618. value: new Date(2013, 9, 1)
  23619. };
  23620. }]);
  23621. </script>
  23622. <form name="myForm" ng-controller="DateController as dateCtrl">
  23623. <label for="exampleInput">Pick a month in 2013:</label>
  23624. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  23625. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  23626. <div role="alert">
  23627. <span class="error" ng-show="myForm.input.$error.required">
  23628. Required!</span>
  23629. <span class="error" ng-show="myForm.input.$error.month">
  23630. Not a valid month!</span>
  23631. </div>
  23632. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  23633. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23634. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23635. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23636. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23637. </form>
  23638. </file>
  23639. <file name="protractor.js" type="protractor">
  23640. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  23641. var valid = element(by.binding('myForm.input.$valid'));
  23642. // currently protractor/webdriver does not support
  23643. // sending keys to all known HTML5 input controls
  23644. // for various browsers (https://github.com/angular/protractor/issues/562).
  23645. function setInput(val) {
  23646. // set the value of the element and force validation.
  23647. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23648. "ipt.value = '" + val + "';" +
  23649. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23650. browser.executeScript(scr);
  23651. }
  23652. it('should initialize to model', function() {
  23653. expect(value.getText()).toContain('2013-10');
  23654. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23655. });
  23656. it('should be invalid if empty', function() {
  23657. setInput('');
  23658. expect(value.getText()).toEqual('value =');
  23659. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23660. });
  23661. it('should be invalid if over max', function() {
  23662. setInput('2015-01');
  23663. expect(value.getText()).toContain('');
  23664. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23665. });
  23666. </file>
  23667. </example>
  23668. */
  23669. 'month': createDateInputType('month', MONTH_REGEXP,
  23670. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  23671. 'yyyy-MM'),
  23672. /**
  23673. * @ngdoc input
  23674. * @name input[number]
  23675. *
  23676. * @description
  23677. * Text input with number validation and transformation. Sets the `number` validation
  23678. * error if not a valid number.
  23679. *
  23680. * <div class="alert alert-warning">
  23681. * The model must always be of type `number` otherwise AngularJS will throw an error.
  23682. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  23683. * error docs for more information and an example of how to convert your model if necessary.
  23684. * </div>
  23685. *
  23686. *
  23687. *
  23688. * @knownIssue
  23689. *
  23690. * ### HTML5 constraint validation and `allowInvalid`
  23691. *
  23692. * In browsers that follow the
  23693. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  23694. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  23695. * If a non-number is entered in the input, the browser will report the value as an empty string,
  23696. * which means the view / model values in `ngModel` and subsequently the scope value
  23697. * will also be an empty string.
  23698. *
  23699. * @knownIssue
  23700. *
  23701. * ### Large numbers and `step` validation
  23702. *
  23703. * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to
  23704. * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built
  23705. * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by
  23706. * {@link guide/forms#modifying-built-in-validators overwriting the validators}
  23707. * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators}
  23708. * to an `input[text]` element. The source for `input[number]` type can be used as a starting
  23709. * point for both implementations.
  23710. *
  23711. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23712. * @param {string=} name Property name of the form under which the control is published.
  23713. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23714. * Can be interpolated.
  23715. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23716. * Can be interpolated.
  23717. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  23718. * but does not trigger HTML5 native validation. Takes an expression.
  23719. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  23720. * but does not trigger HTML5 native validation. Takes an expression.
  23721. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  23722. * Can be interpolated.
  23723. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  23724. * but does not trigger HTML5 native validation. Takes an expression.
  23725. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23726. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23727. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23728. * `required` when you want to data-bind to the `required` attribute.
  23729. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23730. * minlength.
  23731. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23732. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23733. * any length.
  23734. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23735. * that contains the regular expression body that will be converted to a regular expression
  23736. * as in the ngPattern directive.
  23737. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23738. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23739. * If the expression evaluates to a RegExp object, then this is used directly.
  23740. * If the expression evaluates to a string, then it will be converted to a RegExp
  23741. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23742. * `new RegExp('^abc$')`.<br />
  23743. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23744. * start at the index of the last search's match, thus not taking the whole input value into
  23745. * account.
  23746. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23747. * interaction with the input element.
  23748. *
  23749. * @example
  23750. <example name="number-input-directive" module="numberExample">
  23751. <file name="index.html">
  23752. <script>
  23753. angular.module('numberExample', [])
  23754. .controller('ExampleController', ['$scope', function($scope) {
  23755. $scope.example = {
  23756. value: 12
  23757. };
  23758. }]);
  23759. </script>
  23760. <form name="myForm" ng-controller="ExampleController">
  23761. <label>Number:
  23762. <input type="number" name="input" ng-model="example.value"
  23763. min="0" max="99" required>
  23764. </label>
  23765. <div role="alert">
  23766. <span class="error" ng-show="myForm.input.$error.required">
  23767. Required!</span>
  23768. <span class="error" ng-show="myForm.input.$error.number">
  23769. Not valid number!</span>
  23770. </div>
  23771. <tt>value = {{example.value}}</tt><br/>
  23772. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23773. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23774. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23775. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23776. </form>
  23777. </file>
  23778. <file name="protractor.js" type="protractor">
  23779. var value = element(by.binding('example.value'));
  23780. var valid = element(by.binding('myForm.input.$valid'));
  23781. var input = element(by.model('example.value'));
  23782. it('should initialize to model', function() {
  23783. expect(value.getText()).toContain('12');
  23784. expect(valid.getText()).toContain('true');
  23785. });
  23786. it('should be invalid if empty', function() {
  23787. input.clear();
  23788. input.sendKeys('');
  23789. expect(value.getText()).toEqual('value =');
  23790. expect(valid.getText()).toContain('false');
  23791. });
  23792. it('should be invalid if over max', function() {
  23793. input.clear();
  23794. input.sendKeys('123');
  23795. expect(value.getText()).toEqual('value =');
  23796. expect(valid.getText()).toContain('false');
  23797. });
  23798. </file>
  23799. </example>
  23800. */
  23801. 'number': numberInputType,
  23802. /**
  23803. * @ngdoc input
  23804. * @name input[url]
  23805. *
  23806. * @description
  23807. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  23808. * valid URL.
  23809. *
  23810. * <div class="alert alert-warning">
  23811. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  23812. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  23813. * the built-in validators (see the {@link guide/forms Forms guide})
  23814. * </div>
  23815. *
  23816. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23817. * @param {string=} name Property name of the form under which the control is published.
  23818. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23819. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23820. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23821. * `required` when you want to data-bind to the `required` attribute.
  23822. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23823. * minlength.
  23824. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23825. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23826. * any length.
  23827. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23828. * that contains the regular expression body that will be converted to a regular expression
  23829. * as in the ngPattern directive.
  23830. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23831. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23832. * If the expression evaluates to a RegExp object, then this is used directly.
  23833. * If the expression evaluates to a string, then it will be converted to a RegExp
  23834. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23835. * `new RegExp('^abc$')`.<br />
  23836. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23837. * start at the index of the last search's match, thus not taking the whole input value into
  23838. * account.
  23839. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23840. * interaction with the input element.
  23841. *
  23842. * @example
  23843. <example name="url-input-directive" module="urlExample">
  23844. <file name="index.html">
  23845. <script>
  23846. angular.module('urlExample', [])
  23847. .controller('ExampleController', ['$scope', function($scope) {
  23848. $scope.url = {
  23849. text: 'http://google.com'
  23850. };
  23851. }]);
  23852. </script>
  23853. <form name="myForm" ng-controller="ExampleController">
  23854. <label>URL:
  23855. <input type="url" name="input" ng-model="url.text" required>
  23856. <label>
  23857. <div role="alert">
  23858. <span class="error" ng-show="myForm.input.$error.required">
  23859. Required!</span>
  23860. <span class="error" ng-show="myForm.input.$error.url">
  23861. Not valid url!</span>
  23862. </div>
  23863. <tt>text = {{url.text}}</tt><br/>
  23864. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23865. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23866. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23867. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23868. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  23869. </form>
  23870. </file>
  23871. <file name="protractor.js" type="protractor">
  23872. var text = element(by.binding('url.text'));
  23873. var valid = element(by.binding('myForm.input.$valid'));
  23874. var input = element(by.model('url.text'));
  23875. it('should initialize to model', function() {
  23876. expect(text.getText()).toContain('http://google.com');
  23877. expect(valid.getText()).toContain('true');
  23878. });
  23879. it('should be invalid if empty', function() {
  23880. input.clear();
  23881. input.sendKeys('');
  23882. expect(text.getText()).toEqual('text =');
  23883. expect(valid.getText()).toContain('false');
  23884. });
  23885. it('should be invalid if not url', function() {
  23886. input.clear();
  23887. input.sendKeys('box');
  23888. expect(valid.getText()).toContain('false');
  23889. });
  23890. </file>
  23891. </example>
  23892. */
  23893. 'url': urlInputType,
  23894. /**
  23895. * @ngdoc input
  23896. * @name input[email]
  23897. *
  23898. * @description
  23899. * Text input with email validation. Sets the `email` validation error key if not a valid email
  23900. * address.
  23901. *
  23902. * <div class="alert alert-warning">
  23903. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  23904. * used in Chromium, which may not fulfill your app's requirements.
  23905. * If you need stricter (e.g. requiring a top-level domain), or more relaxed validation
  23906. * (e.g. allowing IPv6 address literals) you can use `ng-pattern` or
  23907. * modify the built-in validators (see the {@link guide/forms Forms guide}).
  23908. * </div>
  23909. *
  23910. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23911. * @param {string=} name Property name of the form under which the control is published.
  23912. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23913. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23914. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23915. * `required` when you want to data-bind to the `required` attribute.
  23916. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23917. * minlength.
  23918. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23919. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23920. * any length.
  23921. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23922. * that contains the regular expression body that will be converted to a regular expression
  23923. * as in the ngPattern directive.
  23924. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23925. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23926. * If the expression evaluates to a RegExp object, then this is used directly.
  23927. * If the expression evaluates to a string, then it will be converted to a RegExp
  23928. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23929. * `new RegExp('^abc$')`.<br />
  23930. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23931. * start at the index of the last search's match, thus not taking the whole input value into
  23932. * account.
  23933. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23934. * interaction with the input element.
  23935. *
  23936. * @example
  23937. <example name="email-input-directive" module="emailExample">
  23938. <file name="index.html">
  23939. <script>
  23940. angular.module('emailExample', [])
  23941. .controller('ExampleController', ['$scope', function($scope) {
  23942. $scope.email = {
  23943. text: 'me@example.com'
  23944. };
  23945. }]);
  23946. </script>
  23947. <form name="myForm" ng-controller="ExampleController">
  23948. <label>Email:
  23949. <input type="email" name="input" ng-model="email.text" required>
  23950. </label>
  23951. <div role="alert">
  23952. <span class="error" ng-show="myForm.input.$error.required">
  23953. Required!</span>
  23954. <span class="error" ng-show="myForm.input.$error.email">
  23955. Not valid email!</span>
  23956. </div>
  23957. <tt>text = {{email.text}}</tt><br/>
  23958. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23959. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23960. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23961. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23962. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  23963. </form>
  23964. </file>
  23965. <file name="protractor.js" type="protractor">
  23966. var text = element(by.binding('email.text'));
  23967. var valid = element(by.binding('myForm.input.$valid'));
  23968. var input = element(by.model('email.text'));
  23969. it('should initialize to model', function() {
  23970. expect(text.getText()).toContain('me@example.com');
  23971. expect(valid.getText()).toContain('true');
  23972. });
  23973. it('should be invalid if empty', function() {
  23974. input.clear();
  23975. input.sendKeys('');
  23976. expect(text.getText()).toEqual('text =');
  23977. expect(valid.getText()).toContain('false');
  23978. });
  23979. it('should be invalid if not email', function() {
  23980. input.clear();
  23981. input.sendKeys('xxx');
  23982. expect(valid.getText()).toContain('false');
  23983. });
  23984. </file>
  23985. </example>
  23986. */
  23987. 'email': emailInputType,
  23988. /**
  23989. * @ngdoc input
  23990. * @name input[radio]
  23991. *
  23992. * @description
  23993. * HTML radio button.
  23994. *
  23995. * **Note:**<br>
  23996. * All inputs controlled by {@link ngModel ngModel} (including those of type `radio`) will use the
  23997. * value of their `name` attribute to determine the property under which their
  23998. * {@link ngModel.NgModelController NgModelController} will be published on the parent
  23999. * {@link form.FormController FormController}. Thus, if you use the same `name` for multiple
  24000. * inputs of a form (e.g. a group of radio inputs), only _one_ `NgModelController` will be
  24001. * published on the parent `FormController` under that name. The rest of the controllers will
  24002. * continue to work as expected, but you won't be able to access them as properties on the parent
  24003. * `FormController`.
  24004. *
  24005. * <div class="alert alert-info">
  24006. * <p>
  24007. * In plain HTML forms, the `name` attribute is used to identify groups of radio inputs, so
  24008. * that the browser can manage their state (checked/unchecked) based on the state of other
  24009. * inputs in the same group.
  24010. * </p>
  24011. * <p>
  24012. * In AngularJS forms, this is not necessary. The input's state will be updated based on the
  24013. * value of the underlying model data.
  24014. * </p>
  24015. * </div>
  24016. *
  24017. * <div class="alert alert-success">
  24018. * If you omit the `name` attribute on a radio input, `ngModel` will automatically assign it a
  24019. * unique name.
  24020. * </div>
  24021. *
  24022. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24023. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  24024. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  24025. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  24026. * @param {string=} name Property name of the form under which the control is published.
  24027. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24028. * interaction with the input element.
  24029. * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio
  24030. * is selected. Should be used instead of the `value` attribute if you need
  24031. * a non-string `ngModel` (`boolean`, `array`, ...).
  24032. *
  24033. * @example
  24034. <example name="radio-input-directive" module="radioExample">
  24035. <file name="index.html">
  24036. <script>
  24037. angular.module('radioExample', [])
  24038. .controller('ExampleController', ['$scope', function($scope) {
  24039. $scope.color = {
  24040. name: 'blue'
  24041. };
  24042. $scope.specialValue = {
  24043. "id": "12345",
  24044. "value": "green"
  24045. };
  24046. }]);
  24047. </script>
  24048. <form name="myForm" ng-controller="ExampleController">
  24049. <label>
  24050. <input type="radio" ng-model="color.name" value="red">
  24051. Red
  24052. </label><br/>
  24053. <label>
  24054. <input type="radio" ng-model="color.name" ng-value="specialValue">
  24055. Green
  24056. </label><br/>
  24057. <label>
  24058. <input type="radio" ng-model="color.name" value="blue">
  24059. Blue
  24060. </label><br/>
  24061. <tt>color = {{color.name | json}}</tt><br/>
  24062. </form>
  24063. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  24064. </file>
  24065. <file name="protractor.js" type="protractor">
  24066. it('should change state', function() {
  24067. var inputs = element.all(by.model('color.name'));
  24068. var color = element(by.binding('color.name'));
  24069. expect(color.getText()).toContain('blue');
  24070. inputs.get(0).click();
  24071. expect(color.getText()).toContain('red');
  24072. inputs.get(1).click();
  24073. expect(color.getText()).toContain('green');
  24074. });
  24075. </file>
  24076. </example>
  24077. */
  24078. 'radio': radioInputType,
  24079. /**
  24080. * @ngdoc input
  24081. * @name input[range]
  24082. *
  24083. * @description
  24084. * Native range input with validation and transformation.
  24085. *
  24086. * The model for the range input must always be a `Number`.
  24087. *
  24088. * IE9 and other browsers that do not support the `range` type fall back
  24089. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  24090. * validation and number parsing are nevertheless supported.
  24091. *
  24092. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  24093. * in a way that never allows the input to hold an invalid value. That means:
  24094. * - any non-numerical value is set to `(max + min) / 2`.
  24095. * - any numerical value that is less than the current min val, or greater than the current max val
  24096. * is set to the min / max val respectively.
  24097. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  24098. * is used.
  24099. *
  24100. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  24101. * for more info.
  24102. *
  24103. * This has the following consequences for AngularJS:
  24104. *
  24105. * Since the element value should always reflect the current model value, a range input
  24106. * will set the bound ngModel expression to the value that the browser has set for the
  24107. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  24108. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  24109. * AngularJS will then set the model to `50`, to prevent input and model value being out of sync.
  24110. *
  24111. * That means the model for range will immediately be set to `50` after `ngModel` has been
  24112. * initialized. It also means a range input can never have the required error.
  24113. *
  24114. * This does not only affect changes to the model value, but also to the values of the `min`,
  24115. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  24116. * the input value, AngularJS will also update the model value.
  24117. *
  24118. * Automatic value adjustment also means that a range input element can never have the `required`,
  24119. * `min`, or `max` errors.
  24120. *
  24121. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  24122. * when the step value changes dynamically - they do not adjust the element value correctly, but
  24123. * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step`
  24124. * error on the input, and set the model to `undefined`.
  24125. *
  24126. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  24127. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  24128. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  24129. *
  24130. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24131. * @param {string=} name Property name of the form under which the control is published.
  24132. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  24133. * than `min`. Can be interpolated.
  24134. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  24135. * Can be interpolated.
  24136. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  24137. * Can be interpolated.
  24138. * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due
  24139. * to user interaction with the input element.
  24140. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  24141. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  24142. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  24143. *
  24144. * @example
  24145. <example name="range-input-directive" module="rangeExample">
  24146. <file name="index.html">
  24147. <script>
  24148. angular.module('rangeExample', [])
  24149. .controller('ExampleController', ['$scope', function($scope) {
  24150. $scope.value = 75;
  24151. $scope.min = 10;
  24152. $scope.max = 90;
  24153. }]);
  24154. </script>
  24155. <form name="myForm" ng-controller="ExampleController">
  24156. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  24157. <hr>
  24158. Model as number: <input type="number" ng-model="value"><br>
  24159. Min: <input type="number" ng-model="min"><br>
  24160. Max: <input type="number" ng-model="max"><br>
  24161. value = <code>{{value}}</code><br/>
  24162. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  24163. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  24164. </form>
  24165. </file>
  24166. </example>
  24167. * ## Range Input with ngMin & ngMax attributes
  24168. * @example
  24169. <example name="range-input-directive-ng" module="rangeExample">
  24170. <file name="index.html">
  24171. <script>
  24172. angular.module('rangeExample', [])
  24173. .controller('ExampleController', ['$scope', function($scope) {
  24174. $scope.value = 75;
  24175. $scope.min = 10;
  24176. $scope.max = 90;
  24177. }]);
  24178. </script>
  24179. <form name="myForm" ng-controller="ExampleController">
  24180. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  24181. <hr>
  24182. Model as number: <input type="number" ng-model="value"><br>
  24183. Min: <input type="number" ng-model="min"><br>
  24184. Max: <input type="number" ng-model="max"><br>
  24185. value = <code>{{value}}</code><br/>
  24186. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  24187. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  24188. </form>
  24189. </file>
  24190. </example>
  24191. */
  24192. 'range': rangeInputType,
  24193. /**
  24194. * @ngdoc input
  24195. * @name input[checkbox]
  24196. *
  24197. * @description
  24198. * HTML checkbox.
  24199. *
  24200. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24201. * @param {string=} name Property name of the form under which the control is published.
  24202. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  24203. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  24204. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24205. * interaction with the input element.
  24206. *
  24207. * @example
  24208. <example name="checkbox-input-directive" module="checkboxExample">
  24209. <file name="index.html">
  24210. <script>
  24211. angular.module('checkboxExample', [])
  24212. .controller('ExampleController', ['$scope', function($scope) {
  24213. $scope.checkboxModel = {
  24214. value1 : true,
  24215. value2 : 'YES'
  24216. };
  24217. }]);
  24218. </script>
  24219. <form name="myForm" ng-controller="ExampleController">
  24220. <label>Value1:
  24221. <input type="checkbox" ng-model="checkboxModel.value1">
  24222. </label><br/>
  24223. <label>Value2:
  24224. <input type="checkbox" ng-model="checkboxModel.value2"
  24225. ng-true-value="'YES'" ng-false-value="'NO'">
  24226. </label><br/>
  24227. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  24228. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  24229. </form>
  24230. </file>
  24231. <file name="protractor.js" type="protractor">
  24232. it('should change state', function() {
  24233. var value1 = element(by.binding('checkboxModel.value1'));
  24234. var value2 = element(by.binding('checkboxModel.value2'));
  24235. expect(value1.getText()).toContain('true');
  24236. expect(value2.getText()).toContain('YES');
  24237. element(by.model('checkboxModel.value1')).click();
  24238. element(by.model('checkboxModel.value2')).click();
  24239. expect(value1.getText()).toContain('false');
  24240. expect(value2.getText()).toContain('NO');
  24241. });
  24242. </file>
  24243. </example>
  24244. */
  24245. 'checkbox': checkboxInputType,
  24246. 'hidden': noop,
  24247. 'button': noop,
  24248. 'submit': noop,
  24249. 'reset': noop,
  24250. 'file': noop
  24251. };
  24252. function stringBasedInputType(ctrl) {
  24253. ctrl.$formatters.push(function(value) {
  24254. return ctrl.$isEmpty(value) ? value : value.toString();
  24255. });
  24256. }
  24257. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24258. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24259. stringBasedInputType(ctrl);
  24260. }
  24261. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24262. var type = lowercase(element[0].type);
  24263. // In composition mode, users are still inputting intermediate text buffer,
  24264. // hold the listener until composition is done.
  24265. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  24266. if (!$sniffer.android) {
  24267. var composing = false;
  24268. element.on('compositionstart', function() {
  24269. composing = true;
  24270. });
  24271. // Support: IE9+
  24272. element.on('compositionupdate', function(ev) {
  24273. // End composition when ev.data is empty string on 'compositionupdate' event.
  24274. // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate'
  24275. // instead of 'compositionend'.
  24276. if (isUndefined(ev.data) || ev.data === '') {
  24277. composing = false;
  24278. }
  24279. });
  24280. element.on('compositionend', function() {
  24281. composing = false;
  24282. listener();
  24283. });
  24284. }
  24285. var timeout;
  24286. var listener = function(ev) {
  24287. if (timeout) {
  24288. $browser.defer.cancel(timeout);
  24289. timeout = null;
  24290. }
  24291. if (composing) return;
  24292. var value = element.val(),
  24293. event = ev && ev.type;
  24294. // By default we will trim the value
  24295. // If the attribute ng-trim exists we will avoid trimming
  24296. // If input type is 'password', the value is never trimmed
  24297. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  24298. value = trim(value);
  24299. }
  24300. // If a control is suffering from bad input (due to native validators), browsers discard its
  24301. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  24302. // control's value is the same empty value twice in a row.
  24303. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  24304. ctrl.$setViewValue(value, event);
  24305. }
  24306. };
  24307. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  24308. // input event on backspace, delete or cut
  24309. if ($sniffer.hasEvent('input')) {
  24310. element.on('input', listener);
  24311. } else {
  24312. var deferListener = function(ev, input, origValue) {
  24313. if (!timeout) {
  24314. timeout = $browser.defer(function() {
  24315. timeout = null;
  24316. if (!input || input.value !== origValue) {
  24317. listener(ev);
  24318. }
  24319. });
  24320. }
  24321. };
  24322. element.on('keydown', /** @this */ function(event) {
  24323. var key = event.keyCode;
  24324. // ignore
  24325. // command modifiers arrows
  24326. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  24327. deferListener(event, this, this.value);
  24328. });
  24329. // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it
  24330. if ($sniffer.hasEvent('paste')) {
  24331. element.on('paste cut drop', deferListener);
  24332. }
  24333. }
  24334. // if user paste into input using mouse on older browser
  24335. // or form autocomplete on newer browser, we need "change" event to catch it
  24336. element.on('change', listener);
  24337. // Some native input types (date-family) have the ability to change validity without
  24338. // firing any input/change events.
  24339. // For these event types, when native validators are present and the browser supports the type,
  24340. // check for validity changes on various DOM events.
  24341. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  24342. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  24343. if (!timeout) {
  24344. var validity = this[VALIDITY_STATE_PROPERTY];
  24345. var origBadInput = validity.badInput;
  24346. var origTypeMismatch = validity.typeMismatch;
  24347. timeout = $browser.defer(function() {
  24348. timeout = null;
  24349. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  24350. listener(ev);
  24351. }
  24352. });
  24353. }
  24354. });
  24355. }
  24356. ctrl.$render = function() {
  24357. // Workaround for Firefox validation #12102.
  24358. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  24359. if (element.val() !== value) {
  24360. element.val(value);
  24361. }
  24362. };
  24363. }
  24364. function weekParser(isoWeek, existingDate) {
  24365. if (isDate(isoWeek)) {
  24366. return isoWeek;
  24367. }
  24368. if (isString(isoWeek)) {
  24369. WEEK_REGEXP.lastIndex = 0;
  24370. var parts = WEEK_REGEXP.exec(isoWeek);
  24371. if (parts) {
  24372. var year = +parts[1],
  24373. week = +parts[2],
  24374. hours = 0,
  24375. minutes = 0,
  24376. seconds = 0,
  24377. milliseconds = 0,
  24378. firstThurs = getFirstThursdayOfYear(year),
  24379. addDays = (week - 1) * 7;
  24380. if (existingDate) {
  24381. hours = existingDate.getHours();
  24382. minutes = existingDate.getMinutes();
  24383. seconds = existingDate.getSeconds();
  24384. milliseconds = existingDate.getMilliseconds();
  24385. }
  24386. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  24387. }
  24388. }
  24389. return NaN;
  24390. }
  24391. function createDateParser(regexp, mapping) {
  24392. return function(iso, previousDate) {
  24393. var parts, map;
  24394. if (isDate(iso)) {
  24395. return iso;
  24396. }
  24397. if (isString(iso)) {
  24398. // When a date is JSON'ified to wraps itself inside of an extra
  24399. // set of double quotes. This makes the date parsing code unable
  24400. // to match the date string and parse it as a date.
  24401. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  24402. iso = iso.substring(1, iso.length - 1);
  24403. }
  24404. if (ISO_DATE_REGEXP.test(iso)) {
  24405. return new Date(iso);
  24406. }
  24407. regexp.lastIndex = 0;
  24408. parts = regexp.exec(iso);
  24409. if (parts) {
  24410. parts.shift();
  24411. if (previousDate) {
  24412. map = {
  24413. yyyy: previousDate.getFullYear(),
  24414. MM: previousDate.getMonth() + 1,
  24415. dd: previousDate.getDate(),
  24416. HH: previousDate.getHours(),
  24417. mm: previousDate.getMinutes(),
  24418. ss: previousDate.getSeconds(),
  24419. sss: previousDate.getMilliseconds() / 1000
  24420. };
  24421. } else {
  24422. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  24423. }
  24424. forEach(parts, function(part, index) {
  24425. if (index < mapping.length) {
  24426. map[mapping[index]] = +part;
  24427. }
  24428. });
  24429. var date = new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  24430. if (map.yyyy < 100) {
  24431. // In the constructor, 2-digit years map to 1900-1999.
  24432. // Use `setFullYear()` to set the correct year.
  24433. date.setFullYear(map.yyyy);
  24434. }
  24435. return date;
  24436. }
  24437. }
  24438. return NaN;
  24439. };
  24440. }
  24441. function createDateInputType(type, regexp, parseDate, format) {
  24442. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  24443. badInputChecker(scope, element, attr, ctrl, type);
  24444. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24445. var isTimeType = type === 'time' || type === 'datetimelocal';
  24446. var previousDate;
  24447. var previousTimezone;
  24448. ctrl.$parsers.push(function(value) {
  24449. if (ctrl.$isEmpty(value)) return null;
  24450. if (regexp.test(value)) {
  24451. // Note: We cannot read ctrl.$modelValue, as there might be a different
  24452. // parser/formatter in the processing chain so that the model
  24453. // contains some different data format!
  24454. return parseDateAndConvertTimeZoneToLocal(value, previousDate);
  24455. }
  24456. ctrl.$$parserName = type;
  24457. return undefined;
  24458. });
  24459. ctrl.$formatters.push(function(value) {
  24460. if (value && !isDate(value)) {
  24461. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  24462. }
  24463. if (isValidDate(value)) {
  24464. previousDate = value;
  24465. var timezone = ctrl.$options.getOption('timezone');
  24466. if (timezone) {
  24467. previousTimezone = timezone;
  24468. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  24469. }
  24470. return formatter(value, timezone);
  24471. } else {
  24472. previousDate = null;
  24473. previousTimezone = null;
  24474. return '';
  24475. }
  24476. });
  24477. if (isDefined(attr.min) || attr.ngMin) {
  24478. var minVal = attr.min || $parse(attr.ngMin)(scope);
  24479. var parsedMinVal = parseObservedDateValue(minVal);
  24480. ctrl.$validators.min = function(value) {
  24481. return !isValidDate(value) || isUndefined(parsedMinVal) || parseDate(value) >= parsedMinVal;
  24482. };
  24483. attr.$observe('min', function(val) {
  24484. if (val !== minVal) {
  24485. parsedMinVal = parseObservedDateValue(val);
  24486. minVal = val;
  24487. ctrl.$validate();
  24488. }
  24489. });
  24490. }
  24491. if (isDefined(attr.max) || attr.ngMax) {
  24492. var maxVal = attr.max || $parse(attr.ngMax)(scope);
  24493. var parsedMaxVal = parseObservedDateValue(maxVal);
  24494. ctrl.$validators.max = function(value) {
  24495. return !isValidDate(value) || isUndefined(parsedMaxVal) || parseDate(value) <= parsedMaxVal;
  24496. };
  24497. attr.$observe('max', function(val) {
  24498. if (val !== maxVal) {
  24499. parsedMaxVal = parseObservedDateValue(val);
  24500. maxVal = val;
  24501. ctrl.$validate();
  24502. }
  24503. });
  24504. }
  24505. function isValidDate(value) {
  24506. // Invalid Date: getTime() returns NaN
  24507. return value && !(value.getTime && value.getTime() !== value.getTime());
  24508. }
  24509. function parseObservedDateValue(val) {
  24510. return isDefined(val) && !isDate(val) ? parseDateAndConvertTimeZoneToLocal(val) || undefined : val;
  24511. }
  24512. function parseDateAndConvertTimeZoneToLocal(value, previousDate) {
  24513. var timezone = ctrl.$options.getOption('timezone');
  24514. if (previousTimezone && previousTimezone !== timezone) {
  24515. // If the timezone has changed, adjust the previousDate to the default timezone
  24516. // so that the new date is converted with the correct timezone offset
  24517. previousDate = addDateMinutes(previousDate, timezoneToOffset(previousTimezone));
  24518. }
  24519. var parsedDate = parseDate(value, previousDate);
  24520. if (!isNaN(parsedDate) && timezone) {
  24521. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  24522. }
  24523. return parsedDate;
  24524. }
  24525. function formatter(value, timezone) {
  24526. var targetFormat = format;
  24527. if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) {
  24528. targetFormat = format
  24529. .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat'))
  24530. .replace(/:$/, '');
  24531. }
  24532. var formatted = $filter('date')(value, targetFormat, timezone);
  24533. if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) {
  24534. formatted = formatted.replace(/(?::00)?(?:\.000)?$/, '');
  24535. }
  24536. return formatted;
  24537. }
  24538. };
  24539. }
  24540. function badInputChecker(scope, element, attr, ctrl, parserName) {
  24541. var node = element[0];
  24542. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  24543. if (nativeValidation) {
  24544. ctrl.$parsers.push(function(value) {
  24545. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  24546. if (validity.badInput || validity.typeMismatch) {
  24547. ctrl.$$parserName = parserName;
  24548. return undefined;
  24549. }
  24550. return value;
  24551. });
  24552. }
  24553. }
  24554. function numberFormatterParser(ctrl) {
  24555. ctrl.$parsers.push(function(value) {
  24556. if (ctrl.$isEmpty(value)) return null;
  24557. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  24558. ctrl.$$parserName = 'number';
  24559. return undefined;
  24560. });
  24561. ctrl.$formatters.push(function(value) {
  24562. if (!ctrl.$isEmpty(value)) {
  24563. if (!isNumber(value)) {
  24564. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  24565. }
  24566. value = value.toString();
  24567. }
  24568. return value;
  24569. });
  24570. }
  24571. function parseNumberAttrVal(val) {
  24572. if (isDefined(val) && !isNumber(val)) {
  24573. val = parseFloat(val);
  24574. }
  24575. return !isNumberNaN(val) ? val : undefined;
  24576. }
  24577. function isNumberInteger(num) {
  24578. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  24579. // (minus the assumption that `num` is a number)
  24580. // eslint-disable-next-line no-bitwise
  24581. return (num | 0) === num;
  24582. }
  24583. function countDecimals(num) {
  24584. var numString = num.toString();
  24585. var decimalSymbolIndex = numString.indexOf('.');
  24586. if (decimalSymbolIndex === -1) {
  24587. if (-1 < num && num < 1) {
  24588. // It may be in the exponential notation format (`1e-X`)
  24589. var match = /e-(\d+)$/.exec(numString);
  24590. if (match) {
  24591. return Number(match[1]);
  24592. }
  24593. }
  24594. return 0;
  24595. }
  24596. return numString.length - decimalSymbolIndex - 1;
  24597. }
  24598. function isValidForStep(viewValue, stepBase, step) {
  24599. // At this point `stepBase` and `step` are expected to be non-NaN values
  24600. // and `viewValue` is expected to be a valid stringified number.
  24601. var value = Number(viewValue);
  24602. var isNonIntegerValue = !isNumberInteger(value);
  24603. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  24604. var isNonIntegerStep = !isNumberInteger(step);
  24605. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  24606. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  24607. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  24608. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  24609. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  24610. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  24611. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  24612. var multiplier = Math.pow(10, decimalCount);
  24613. value = value * multiplier;
  24614. stepBase = stepBase * multiplier;
  24615. step = step * multiplier;
  24616. if (isNonIntegerValue) value = Math.round(value);
  24617. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  24618. if (isNonIntegerStep) step = Math.round(step);
  24619. }
  24620. return (value - stepBase) % step === 0;
  24621. }
  24622. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  24623. badInputChecker(scope, element, attr, ctrl, 'number');
  24624. numberFormatterParser(ctrl);
  24625. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24626. var parsedMinVal;
  24627. if (isDefined(attr.min) || attr.ngMin) {
  24628. var minVal = attr.min || $parse(attr.ngMin)(scope);
  24629. parsedMinVal = parseNumberAttrVal(minVal);
  24630. ctrl.$validators.min = function(modelValue, viewValue) {
  24631. return ctrl.$isEmpty(viewValue) || isUndefined(parsedMinVal) || viewValue >= parsedMinVal;
  24632. };
  24633. attr.$observe('min', function(val) {
  24634. if (val !== minVal) {
  24635. parsedMinVal = parseNumberAttrVal(val);
  24636. minVal = val;
  24637. // TODO(matsko): implement validateLater to reduce number of validations
  24638. ctrl.$validate();
  24639. }
  24640. });
  24641. }
  24642. if (isDefined(attr.max) || attr.ngMax) {
  24643. var maxVal = attr.max || $parse(attr.ngMax)(scope);
  24644. var parsedMaxVal = parseNumberAttrVal(maxVal);
  24645. ctrl.$validators.max = function(modelValue, viewValue) {
  24646. return ctrl.$isEmpty(viewValue) || isUndefined(parsedMaxVal) || viewValue <= parsedMaxVal;
  24647. };
  24648. attr.$observe('max', function(val) {
  24649. if (val !== maxVal) {
  24650. parsedMaxVal = parseNumberAttrVal(val);
  24651. maxVal = val;
  24652. // TODO(matsko): implement validateLater to reduce number of validations
  24653. ctrl.$validate();
  24654. }
  24655. });
  24656. }
  24657. if (isDefined(attr.step) || attr.ngStep) {
  24658. var stepVal = attr.step || $parse(attr.ngStep)(scope);
  24659. var parsedStepVal = parseNumberAttrVal(stepVal);
  24660. ctrl.$validators.step = function(modelValue, viewValue) {
  24661. return ctrl.$isEmpty(viewValue) || isUndefined(parsedStepVal) ||
  24662. isValidForStep(viewValue, parsedMinVal || 0, parsedStepVal);
  24663. };
  24664. attr.$observe('step', function(val) {
  24665. // TODO(matsko): implement validateLater to reduce number of validations
  24666. if (val !== stepVal) {
  24667. parsedStepVal = parseNumberAttrVal(val);
  24668. stepVal = val;
  24669. ctrl.$validate();
  24670. }
  24671. });
  24672. }
  24673. }
  24674. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24675. badInputChecker(scope, element, attr, ctrl, 'range');
  24676. numberFormatterParser(ctrl);
  24677. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24678. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  24679. minVal = supportsRange ? 0 : undefined,
  24680. maxVal = supportsRange ? 100 : undefined,
  24681. stepVal = supportsRange ? 1 : undefined,
  24682. validity = element[0].validity,
  24683. hasMinAttr = isDefined(attr.min),
  24684. hasMaxAttr = isDefined(attr.max),
  24685. hasStepAttr = isDefined(attr.step);
  24686. var originalRender = ctrl.$render;
  24687. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  24688. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  24689. //$render would cause the min / max validators to be applied with the wrong value
  24690. function rangeRender() {
  24691. originalRender();
  24692. ctrl.$setViewValue(element.val());
  24693. } :
  24694. originalRender;
  24695. if (hasMinAttr) {
  24696. minVal = parseNumberAttrVal(attr.min);
  24697. ctrl.$validators.min = supportsRange ?
  24698. // Since all browsers set the input to a valid value, we don't need to check validity
  24699. function noopMinValidator() { return true; } :
  24700. // non-support browsers validate the min val
  24701. function minValidator(modelValue, viewValue) {
  24702. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  24703. };
  24704. setInitialValueAndObserver('min', minChange);
  24705. }
  24706. if (hasMaxAttr) {
  24707. maxVal = parseNumberAttrVal(attr.max);
  24708. ctrl.$validators.max = supportsRange ?
  24709. // Since all browsers set the input to a valid value, we don't need to check validity
  24710. function noopMaxValidator() { return true; } :
  24711. // non-support browsers validate the max val
  24712. function maxValidator(modelValue, viewValue) {
  24713. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  24714. };
  24715. setInitialValueAndObserver('max', maxChange);
  24716. }
  24717. if (hasStepAttr) {
  24718. stepVal = parseNumberAttrVal(attr.step);
  24719. ctrl.$validators.step = supportsRange ?
  24720. function nativeStepValidator() {
  24721. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  24722. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  24723. // validity error instead, so we can at least report an error in that case.
  24724. return !validity.stepMismatch;
  24725. } :
  24726. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  24727. function stepValidator(modelValue, viewValue) {
  24728. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  24729. isValidForStep(viewValue, minVal || 0, stepVal);
  24730. };
  24731. setInitialValueAndObserver('step', stepChange);
  24732. }
  24733. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  24734. // interpolated attributes set the attribute value only after a digest, but we need the
  24735. // attribute value when the input is first rendered, so that the browser can adjust the
  24736. // input value based on the min/max value
  24737. element.attr(htmlAttrName, attr[htmlAttrName]);
  24738. var oldVal = attr[htmlAttrName];
  24739. attr.$observe(htmlAttrName, function wrappedObserver(val) {
  24740. if (val !== oldVal) {
  24741. oldVal = val;
  24742. changeFn(val);
  24743. }
  24744. });
  24745. }
  24746. function minChange(val) {
  24747. minVal = parseNumberAttrVal(val);
  24748. // ignore changes before model is initialized
  24749. if (isNumberNaN(ctrl.$modelValue)) {
  24750. return;
  24751. }
  24752. if (supportsRange) {
  24753. var elVal = element.val();
  24754. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  24755. if (minVal > elVal) {
  24756. elVal = minVal;
  24757. element.val(elVal);
  24758. }
  24759. ctrl.$setViewValue(elVal);
  24760. } else {
  24761. // TODO(matsko): implement validateLater to reduce number of validations
  24762. ctrl.$validate();
  24763. }
  24764. }
  24765. function maxChange(val) {
  24766. maxVal = parseNumberAttrVal(val);
  24767. // ignore changes before model is initialized
  24768. if (isNumberNaN(ctrl.$modelValue)) {
  24769. return;
  24770. }
  24771. if (supportsRange) {
  24772. var elVal = element.val();
  24773. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  24774. if (maxVal < elVal) {
  24775. element.val(maxVal);
  24776. // IE11 and Chrome don't set the value to the minVal when max < min
  24777. elVal = maxVal < minVal ? minVal : maxVal;
  24778. }
  24779. ctrl.$setViewValue(elVal);
  24780. } else {
  24781. // TODO(matsko): implement validateLater to reduce number of validations
  24782. ctrl.$validate();
  24783. }
  24784. }
  24785. function stepChange(val) {
  24786. stepVal = parseNumberAttrVal(val);
  24787. // ignore changes before model is initialized
  24788. if (isNumberNaN(ctrl.$modelValue)) {
  24789. return;
  24790. }
  24791. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  24792. if (!supportsRange) {
  24793. // TODO(matsko): implement validateLater to reduce number of validations
  24794. ctrl.$validate();
  24795. } else if (ctrl.$viewValue !== element.val()) {
  24796. ctrl.$setViewValue(element.val());
  24797. }
  24798. }
  24799. }
  24800. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24801. // Note: no badInputChecker here by purpose as `url` is only a validation
  24802. // in browsers, i.e. we can always read out input.value even if it is not valid!
  24803. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24804. stringBasedInputType(ctrl);
  24805. ctrl.$validators.url = function(modelValue, viewValue) {
  24806. var value = modelValue || viewValue;
  24807. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  24808. };
  24809. }
  24810. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24811. // Note: no badInputChecker here by purpose as `url` is only a validation
  24812. // in browsers, i.e. we can always read out input.value even if it is not valid!
  24813. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24814. stringBasedInputType(ctrl);
  24815. ctrl.$validators.email = function(modelValue, viewValue) {
  24816. var value = modelValue || viewValue;
  24817. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  24818. };
  24819. }
  24820. function radioInputType(scope, element, attr, ctrl) {
  24821. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  24822. // make the name unique, if not defined
  24823. if (isUndefined(attr.name)) {
  24824. element.attr('name', nextUid());
  24825. }
  24826. var listener = function(ev) {
  24827. var value;
  24828. if (element[0].checked) {
  24829. value = attr.value;
  24830. if (doTrim) {
  24831. value = trim(value);
  24832. }
  24833. ctrl.$setViewValue(value, ev && ev.type);
  24834. }
  24835. };
  24836. element.on('change', listener);
  24837. ctrl.$render = function() {
  24838. var value = attr.value;
  24839. if (doTrim) {
  24840. value = trim(value);
  24841. }
  24842. element[0].checked = (value === ctrl.$viewValue);
  24843. };
  24844. attr.$observe('value', ctrl.$render);
  24845. }
  24846. function parseConstantExpr($parse, context, name, expression, fallback) {
  24847. var parseFn;
  24848. if (isDefined(expression)) {
  24849. parseFn = $parse(expression);
  24850. if (!parseFn.constant) {
  24851. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  24852. '`{1}`.', name, expression);
  24853. }
  24854. return parseFn(context);
  24855. }
  24856. return fallback;
  24857. }
  24858. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  24859. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  24860. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  24861. var listener = function(ev) {
  24862. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  24863. };
  24864. element.on('change', listener);
  24865. ctrl.$render = function() {
  24866. element[0].checked = ctrl.$viewValue;
  24867. };
  24868. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  24869. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  24870. // it to a boolean.
  24871. ctrl.$isEmpty = function(value) {
  24872. return value === false;
  24873. };
  24874. ctrl.$formatters.push(function(value) {
  24875. return equals(value, trueValue);
  24876. });
  24877. ctrl.$parsers.push(function(value) {
  24878. return value ? trueValue : falseValue;
  24879. });
  24880. }
  24881. /**
  24882. * @ngdoc directive
  24883. * @name textarea
  24884. * @restrict E
  24885. *
  24886. * @description
  24887. * HTML textarea element control with AngularJS data-binding. The data-binding and validation
  24888. * properties of this element are exactly the same as those of the
  24889. * {@link ng.directive:input input element}.
  24890. *
  24891. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24892. * @param {string=} name Property name of the form under which the control is published.
  24893. * @param {string=} required Sets `required` validation error key if the value is not entered.
  24894. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  24895. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  24896. * `required` when you want to data-bind to the `required` attribute.
  24897. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  24898. * minlength.
  24899. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  24900. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  24901. * length.
  24902. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  24903. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  24904. * If the expression evaluates to a RegExp object, then this is used directly.
  24905. * If the expression evaluates to a string, then it will be converted to a RegExp
  24906. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  24907. * `new RegExp('^abc$')`.<br />
  24908. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  24909. * start at the index of the last search's match, thus not taking the whole input value into
  24910. * account.
  24911. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24912. * interaction with the input element.
  24913. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  24914. *
  24915. * @knownIssue
  24916. *
  24917. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  24918. * insert the placeholder value as the textarea's content. If the placeholder value contains
  24919. * interpolation (`{{ ... }}`), an error will be logged in the console when AngularJS tries to update
  24920. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  24921. * textarea, but can be undesirable.
  24922. *
  24923. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  24924. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  24925. * find more details on `ngAttr` in the
  24926. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  24927. * Developer Guide.
  24928. */
  24929. /**
  24930. * @ngdoc directive
  24931. * @name input
  24932. * @restrict E
  24933. *
  24934. * @description
  24935. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  24936. * input state control, and validation.
  24937. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  24938. *
  24939. * <div class="alert alert-warning">
  24940. * **Note:** Not every feature offered is available for all input types.
  24941. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  24942. * </div>
  24943. *
  24944. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24945. * @param {string=} name Property name of the form under which the control is published.
  24946. * @param {string=} required Sets `required` validation error key if the value is not entered.
  24947. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  24948. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  24949. * minlength.
  24950. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  24951. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  24952. * length.
  24953. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  24954. * value does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  24955. * If the expression evaluates to a RegExp object, then this is used directly.
  24956. * If the expression evaluates to a string, then it will be converted to a RegExp
  24957. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  24958. * `new RegExp('^abc$')`.<br />
  24959. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  24960. * start at the index of the last search's match, thus not taking the whole input value into
  24961. * account.
  24962. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24963. * interaction with the input element.
  24964. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  24965. * This parameter is ignored for input[type=password] controls, which will never trim the
  24966. * input.
  24967. *
  24968. * @example
  24969. <example name="input-directive" module="inputExample">
  24970. <file name="index.html">
  24971. <script>
  24972. angular.module('inputExample', [])
  24973. .controller('ExampleController', ['$scope', function($scope) {
  24974. $scope.user = {name: 'guest', last: 'visitor'};
  24975. }]);
  24976. </script>
  24977. <div ng-controller="ExampleController">
  24978. <form name="myForm">
  24979. <label>
  24980. User name:
  24981. <input type="text" name="userName" ng-model="user.name" required>
  24982. </label>
  24983. <div role="alert">
  24984. <span class="error" ng-show="myForm.userName.$error.required">
  24985. Required!</span>
  24986. </div>
  24987. <label>
  24988. Last name:
  24989. <input type="text" name="lastName" ng-model="user.last"
  24990. ng-minlength="3" ng-maxlength="10">
  24991. </label>
  24992. <div role="alert">
  24993. <span class="error" ng-show="myForm.lastName.$error.minlength">
  24994. Too short!</span>
  24995. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  24996. Too long!</span>
  24997. </div>
  24998. </form>
  24999. <hr>
  25000. <tt>user = {{user}}</tt><br/>
  25001. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  25002. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  25003. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  25004. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  25005. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25006. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25007. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  25008. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  25009. </div>
  25010. </file>
  25011. <file name="protractor.js" type="protractor">
  25012. var user = element(by.exactBinding('user'));
  25013. var userNameValid = element(by.binding('myForm.userName.$valid'));
  25014. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  25015. var lastNameError = element(by.binding('myForm.lastName.$error'));
  25016. var formValid = element(by.binding('myForm.$valid'));
  25017. var userNameInput = element(by.model('user.name'));
  25018. var userLastInput = element(by.model('user.last'));
  25019. it('should initialize to model', function() {
  25020. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  25021. expect(userNameValid.getText()).toContain('true');
  25022. expect(formValid.getText()).toContain('true');
  25023. });
  25024. it('should be invalid if empty when required', function() {
  25025. userNameInput.clear();
  25026. userNameInput.sendKeys('');
  25027. expect(user.getText()).toContain('{"last":"visitor"}');
  25028. expect(userNameValid.getText()).toContain('false');
  25029. expect(formValid.getText()).toContain('false');
  25030. });
  25031. it('should be valid if empty when min length is set', function() {
  25032. userLastInput.clear();
  25033. userLastInput.sendKeys('');
  25034. expect(user.getText()).toContain('{"name":"guest","last":""}');
  25035. expect(lastNameValid.getText()).toContain('true');
  25036. expect(formValid.getText()).toContain('true');
  25037. });
  25038. it('should be invalid if less than required min length', function() {
  25039. userLastInput.clear();
  25040. userLastInput.sendKeys('xx');
  25041. expect(user.getText()).toContain('{"name":"guest"}');
  25042. expect(lastNameValid.getText()).toContain('false');
  25043. expect(lastNameError.getText()).toContain('minlength');
  25044. expect(formValid.getText()).toContain('false');
  25045. });
  25046. it('should be invalid if longer than max length', function() {
  25047. userLastInput.clear();
  25048. userLastInput.sendKeys('some ridiculously long name');
  25049. expect(user.getText()).toContain('{"name":"guest"}');
  25050. expect(lastNameValid.getText()).toContain('false');
  25051. expect(lastNameError.getText()).toContain('maxlength');
  25052. expect(formValid.getText()).toContain('false');
  25053. });
  25054. </file>
  25055. </example>
  25056. */
  25057. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  25058. function($browser, $sniffer, $filter, $parse) {
  25059. return {
  25060. restrict: 'E',
  25061. require: ['?ngModel'],
  25062. link: {
  25063. pre: function(scope, element, attr, ctrls) {
  25064. if (ctrls[0]) {
  25065. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  25066. $browser, $filter, $parse);
  25067. }
  25068. }
  25069. }
  25070. };
  25071. }];
  25072. var hiddenInputBrowserCacheDirective = function() {
  25073. var valueProperty = {
  25074. configurable: true,
  25075. enumerable: false,
  25076. get: function() {
  25077. return this.getAttribute('value') || '';
  25078. },
  25079. set: function(val) {
  25080. this.setAttribute('value', val);
  25081. }
  25082. };
  25083. return {
  25084. restrict: 'E',
  25085. priority: 200,
  25086. compile: function(_, attr) {
  25087. if (lowercase(attr.type) !== 'hidden') {
  25088. return;
  25089. }
  25090. return {
  25091. pre: function(scope, element, attr, ctrls) {
  25092. var node = element[0];
  25093. // Support: Edge
  25094. // Moving the DOM around prevents autofillling
  25095. if (node.parentNode) {
  25096. node.parentNode.insertBefore(node, node.nextSibling);
  25097. }
  25098. // Support: FF, IE
  25099. // Avoiding direct assignment to .value prevents autofillling
  25100. if (Object.defineProperty) {
  25101. Object.defineProperty(node, 'value', valueProperty);
  25102. }
  25103. }
  25104. };
  25105. }
  25106. };
  25107. };
  25108. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  25109. /**
  25110. * @ngdoc directive
  25111. * @name ngValue
  25112. * @restrict A
  25113. * @priority 100
  25114. *
  25115. * @description
  25116. * Binds the given expression to the value of the element.
  25117. *
  25118. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  25119. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  25120. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  25121. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  25122. *
  25123. * It can also be used to achieve one-way binding of a given expression to an input element
  25124. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  25125. *
  25126. * @element ANY
  25127. * @param {string=} ngValue AngularJS expression, whose value will be bound to the `value` attribute
  25128. * and `value` property of the element.
  25129. *
  25130. * @example
  25131. <example name="ngValue-directive" module="valueExample">
  25132. <file name="index.html">
  25133. <script>
  25134. angular.module('valueExample', [])
  25135. .controller('ExampleController', ['$scope', function($scope) {
  25136. $scope.names = ['pizza', 'unicorns', 'robots'];
  25137. $scope.my = { favorite: 'unicorns' };
  25138. }]);
  25139. </script>
  25140. <form ng-controller="ExampleController">
  25141. <h2>Which is your favorite?</h2>
  25142. <label ng-repeat="name in names" for="{{name}}">
  25143. {{name}}
  25144. <input type="radio"
  25145. ng-model="my.favorite"
  25146. ng-value="name"
  25147. id="{{name}}"
  25148. name="favorite">
  25149. </label>
  25150. <div>You chose {{my.favorite}}</div>
  25151. </form>
  25152. </file>
  25153. <file name="protractor.js" type="protractor">
  25154. var favorite = element(by.binding('my.favorite'));
  25155. it('should initialize to model', function() {
  25156. expect(favorite.getText()).toContain('unicorns');
  25157. });
  25158. it('should bind the values to the inputs', function() {
  25159. element.all(by.model('my.favorite')).get(0).click();
  25160. expect(favorite.getText()).toContain('pizza');
  25161. });
  25162. </file>
  25163. </example>
  25164. */
  25165. var ngValueDirective = function() {
  25166. /**
  25167. * inputs use the value attribute as their default value if the value property is not set.
  25168. * Once the value property has been set (by adding input), it will not react to changes to
  25169. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  25170. * makes it possible to use ngValue as a sort of one-way bind.
  25171. */
  25172. function updateElementValue(element, attr, value) {
  25173. // Support: IE9 only
  25174. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  25175. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  25176. element.prop('value', propValue);
  25177. attr.$set('value', value);
  25178. }
  25179. return {
  25180. restrict: 'A',
  25181. priority: 100,
  25182. compile: function(tpl, tplAttr) {
  25183. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  25184. return function ngValueConstantLink(scope, elm, attr) {
  25185. var value = scope.$eval(attr.ngValue);
  25186. updateElementValue(elm, attr, value);
  25187. };
  25188. } else {
  25189. return function ngValueLink(scope, elm, attr) {
  25190. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  25191. updateElementValue(elm, attr, value);
  25192. });
  25193. };
  25194. }
  25195. }
  25196. };
  25197. };
  25198. /**
  25199. * @ngdoc directive
  25200. * @name ngBind
  25201. * @restrict AC
  25202. *
  25203. * @description
  25204. * The `ngBind` attribute tells AngularJS to replace the text content of the specified HTML element
  25205. * with the value of a given expression, and to update the text content when the value of that
  25206. * expression changes.
  25207. *
  25208. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  25209. * `{{ expression }}` which is similar but less verbose.
  25210. *
  25211. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  25212. * displayed by the browser in its raw state before AngularJS compiles it. Since `ngBind` is an
  25213. * element attribute, it makes the bindings invisible to the user while the page is loading.
  25214. *
  25215. * An alternative solution to this problem would be using the
  25216. * {@link ng.directive:ngCloak ngCloak} directive.
  25217. *
  25218. *
  25219. * @element ANY
  25220. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  25221. *
  25222. * @example
  25223. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  25224. <example module="bindExample" name="ng-bind">
  25225. <file name="index.html">
  25226. <script>
  25227. angular.module('bindExample', [])
  25228. .controller('ExampleController', ['$scope', function($scope) {
  25229. $scope.name = 'Whirled';
  25230. }]);
  25231. </script>
  25232. <div ng-controller="ExampleController">
  25233. <label>Enter name: <input type="text" ng-model="name"></label><br>
  25234. Hello <span ng-bind="name"></span>!
  25235. </div>
  25236. </file>
  25237. <file name="protractor.js" type="protractor">
  25238. it('should check ng-bind', function() {
  25239. var nameInput = element(by.model('name'));
  25240. expect(element(by.binding('name')).getText()).toBe('Whirled');
  25241. nameInput.clear();
  25242. nameInput.sendKeys('world');
  25243. expect(element(by.binding('name')).getText()).toBe('world');
  25244. });
  25245. </file>
  25246. </example>
  25247. */
  25248. var ngBindDirective = ['$compile', function($compile) {
  25249. return {
  25250. restrict: 'AC',
  25251. compile: function ngBindCompile(templateElement) {
  25252. $compile.$$addBindingClass(templateElement);
  25253. return function ngBindLink(scope, element, attr) {
  25254. $compile.$$addBindingInfo(element, attr.ngBind);
  25255. element = element[0];
  25256. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  25257. element.textContent = stringify(value);
  25258. });
  25259. };
  25260. }
  25261. };
  25262. }];
  25263. /**
  25264. * @ngdoc directive
  25265. * @name ngBindTemplate
  25266. *
  25267. * @description
  25268. * The `ngBindTemplate` directive specifies that the element
  25269. * text content should be replaced with the interpolation of the template
  25270. * in the `ngBindTemplate` attribute.
  25271. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  25272. * expressions. This directive is needed since some HTML elements
  25273. * (such as TITLE and OPTION) cannot contain SPAN elements.
  25274. *
  25275. * @element ANY
  25276. * @param {string} ngBindTemplate template of form
  25277. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  25278. *
  25279. * @example
  25280. * Try it here: enter text in text box and watch the greeting change.
  25281. <example module="bindExample" name="ng-bind-template">
  25282. <file name="index.html">
  25283. <script>
  25284. angular.module('bindExample', [])
  25285. .controller('ExampleController', ['$scope', function($scope) {
  25286. $scope.salutation = 'Hello';
  25287. $scope.name = 'World';
  25288. }]);
  25289. </script>
  25290. <div ng-controller="ExampleController">
  25291. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  25292. <label>Name: <input type="text" ng-model="name"></label><br>
  25293. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  25294. </div>
  25295. </file>
  25296. <file name="protractor.js" type="protractor">
  25297. it('should check ng-bind', function() {
  25298. var salutationElem = element(by.binding('salutation'));
  25299. var salutationInput = element(by.model('salutation'));
  25300. var nameInput = element(by.model('name'));
  25301. expect(salutationElem.getText()).toBe('Hello World!');
  25302. salutationInput.clear();
  25303. salutationInput.sendKeys('Greetings');
  25304. nameInput.clear();
  25305. nameInput.sendKeys('user');
  25306. expect(salutationElem.getText()).toBe('Greetings user!');
  25307. });
  25308. </file>
  25309. </example>
  25310. */
  25311. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  25312. return {
  25313. compile: function ngBindTemplateCompile(templateElement) {
  25314. $compile.$$addBindingClass(templateElement);
  25315. return function ngBindTemplateLink(scope, element, attr) {
  25316. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  25317. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  25318. element = element[0];
  25319. attr.$observe('ngBindTemplate', function(value) {
  25320. element.textContent = isUndefined(value) ? '' : value;
  25321. });
  25322. };
  25323. }
  25324. };
  25325. }];
  25326. /**
  25327. * @ngdoc directive
  25328. * @name ngBindHtml
  25329. *
  25330. * @description
  25331. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  25332. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  25333. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  25334. * ngSanitize} in your module's dependencies (not in core AngularJS). In order to use {@link ngSanitize}
  25335. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  25336. *
  25337. * You may also bypass sanitization for values you know are safe. To do so, bind to
  25338. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  25339. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  25340. *
  25341. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  25342. * will have an exception (instead of an exploit.)
  25343. *
  25344. * @element ANY
  25345. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  25346. *
  25347. * @example
  25348. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  25349. <file name="index.html">
  25350. <div ng-controller="ExampleController">
  25351. <p ng-bind-html="myHTML"></p>
  25352. </div>
  25353. </file>
  25354. <file name="script.js">
  25355. angular.module('bindHtmlExample', ['ngSanitize'])
  25356. .controller('ExampleController', ['$scope', function($scope) {
  25357. $scope.myHTML =
  25358. 'I am an <code>HTML</code>string with ' +
  25359. '<a href="#">links!</a> and other <em>stuff</em>';
  25360. }]);
  25361. </file>
  25362. <file name="protractor.js" type="protractor">
  25363. it('should check ng-bind-html', function() {
  25364. expect(element(by.binding('myHTML')).getText()).toBe(
  25365. 'I am an HTMLstring with links! and other stuff');
  25366. });
  25367. </file>
  25368. </example>
  25369. */
  25370. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  25371. return {
  25372. restrict: 'A',
  25373. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  25374. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  25375. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  25376. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  25377. return $sce.valueOf(val);
  25378. });
  25379. $compile.$$addBindingClass(tElement);
  25380. return function ngBindHtmlLink(scope, element, attr) {
  25381. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  25382. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  25383. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  25384. var value = ngBindHtmlGetter(scope);
  25385. element.html($sce.getTrustedHtml(value) || '');
  25386. });
  25387. };
  25388. }
  25389. };
  25390. }];
  25391. /**
  25392. * @ngdoc directive
  25393. * @name ngChange
  25394. * @restrict A
  25395. *
  25396. * @description
  25397. * Evaluate the given expression when the user changes the input.
  25398. * The expression is evaluated immediately, unlike the JavaScript onchange event
  25399. * which only triggers at the end of a change (usually, when the user leaves the
  25400. * form element or presses the return key).
  25401. *
  25402. * The `ngChange` expression is only evaluated when a change in the input value causes
  25403. * a new value to be committed to the model.
  25404. *
  25405. * It will not be evaluated:
  25406. * * if the value returned from the `$parsers` transformation pipeline has not changed
  25407. * * if the input has continued to be invalid since the model will stay `null`
  25408. * * if the model is changed programmatically and not by a change to the input value
  25409. *
  25410. *
  25411. * Note, this directive requires `ngModel` to be present.
  25412. *
  25413. * @element ANY
  25414. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  25415. * in input value.
  25416. *
  25417. * @example
  25418. * <example name="ngChange-directive" module="changeExample">
  25419. * <file name="index.html">
  25420. * <script>
  25421. * angular.module('changeExample', [])
  25422. * .controller('ExampleController', ['$scope', function($scope) {
  25423. * $scope.counter = 0;
  25424. * $scope.change = function() {
  25425. * $scope.counter++;
  25426. * };
  25427. * }]);
  25428. * </script>
  25429. * <div ng-controller="ExampleController">
  25430. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  25431. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  25432. * <label for="ng-change-example2">Confirmed</label><br />
  25433. * <tt>debug = {{confirmed}}</tt><br/>
  25434. * <tt>counter = {{counter}}</tt><br/>
  25435. * </div>
  25436. * </file>
  25437. * <file name="protractor.js" type="protractor">
  25438. * var counter = element(by.binding('counter'));
  25439. * var debug = element(by.binding('confirmed'));
  25440. *
  25441. * it('should evaluate the expression if changing from view', function() {
  25442. * expect(counter.getText()).toContain('0');
  25443. *
  25444. * element(by.id('ng-change-example1')).click();
  25445. *
  25446. * expect(counter.getText()).toContain('1');
  25447. * expect(debug.getText()).toContain('true');
  25448. * });
  25449. *
  25450. * it('should not evaluate the expression if changing from model', function() {
  25451. * element(by.id('ng-change-example2')).click();
  25452. * expect(counter.getText()).toContain('0');
  25453. * expect(debug.getText()).toContain('true');
  25454. * });
  25455. * </file>
  25456. * </example>
  25457. */
  25458. var ngChangeDirective = valueFn({
  25459. restrict: 'A',
  25460. require: 'ngModel',
  25461. link: function(scope, element, attr, ctrl) {
  25462. ctrl.$viewChangeListeners.push(function() {
  25463. scope.$eval(attr.ngChange);
  25464. });
  25465. }
  25466. });
  25467. /* exported
  25468. ngClassDirective,
  25469. ngClassEvenDirective,
  25470. ngClassOddDirective
  25471. */
  25472. function classDirective(name, selector) {
  25473. name = 'ngClass' + name;
  25474. var indexWatchExpression;
  25475. return ['$parse', function($parse) {
  25476. return {
  25477. restrict: 'AC',
  25478. link: function(scope, element, attr) {
  25479. var classCounts = element.data('$classCounts');
  25480. var oldModulo = true;
  25481. var oldClassString;
  25482. if (!classCounts) {
  25483. // Use createMap() to prevent class assumptions involving property
  25484. // names in Object.prototype
  25485. classCounts = createMap();
  25486. element.data('$classCounts', classCounts);
  25487. }
  25488. if (name !== 'ngClass') {
  25489. if (!indexWatchExpression) {
  25490. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  25491. // eslint-disable-next-line no-bitwise
  25492. return $index & 1;
  25493. });
  25494. }
  25495. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  25496. }
  25497. scope.$watch($parse(attr[name], toClassString), ngClassWatchAction);
  25498. function addClasses(classString) {
  25499. classString = digestClassCounts(split(classString), 1);
  25500. attr.$addClass(classString);
  25501. }
  25502. function removeClasses(classString) {
  25503. classString = digestClassCounts(split(classString), -1);
  25504. attr.$removeClass(classString);
  25505. }
  25506. function updateClasses(oldClassString, newClassString) {
  25507. var oldClassArray = split(oldClassString);
  25508. var newClassArray = split(newClassString);
  25509. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  25510. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  25511. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  25512. var toAddString = digestClassCounts(toAddArray, 1);
  25513. attr.$addClass(toAddString);
  25514. attr.$removeClass(toRemoveString);
  25515. }
  25516. function digestClassCounts(classArray, count) {
  25517. var classesToUpdate = [];
  25518. forEach(classArray, function(className) {
  25519. if (count > 0 || classCounts[className]) {
  25520. classCounts[className] = (classCounts[className] || 0) + count;
  25521. if (classCounts[className] === +(count > 0)) {
  25522. classesToUpdate.push(className);
  25523. }
  25524. }
  25525. });
  25526. return classesToUpdate.join(' ');
  25527. }
  25528. function ngClassIndexWatchAction(newModulo) {
  25529. // This watch-action should run before the `ngClassWatchAction()`, thus it
  25530. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  25531. // `ngClassWatchAction()` will update the classes.
  25532. if (newModulo === selector) {
  25533. addClasses(oldClassString);
  25534. } else {
  25535. removeClasses(oldClassString);
  25536. }
  25537. oldModulo = newModulo;
  25538. }
  25539. function ngClassWatchAction(newClassString) {
  25540. if (oldModulo === selector) {
  25541. updateClasses(oldClassString, newClassString);
  25542. }
  25543. oldClassString = newClassString;
  25544. }
  25545. }
  25546. };
  25547. }];
  25548. // Helpers
  25549. function arrayDifference(tokens1, tokens2) {
  25550. if (!tokens1 || !tokens1.length) return [];
  25551. if (!tokens2 || !tokens2.length) return tokens1;
  25552. var values = [];
  25553. outer:
  25554. for (var i = 0; i < tokens1.length; i++) {
  25555. var token = tokens1[i];
  25556. for (var j = 0; j < tokens2.length; j++) {
  25557. if (token === tokens2[j]) continue outer;
  25558. }
  25559. values.push(token);
  25560. }
  25561. return values;
  25562. }
  25563. function split(classString) {
  25564. return classString && classString.split(' ');
  25565. }
  25566. function toClassString(classValue) {
  25567. if (!classValue) return classValue;
  25568. var classString = classValue;
  25569. if (isArray(classValue)) {
  25570. classString = classValue.map(toClassString).join(' ');
  25571. } else if (isObject(classValue)) {
  25572. classString = Object.keys(classValue).
  25573. filter(function(key) { return classValue[key]; }).
  25574. join(' ');
  25575. } else if (!isString(classValue)) {
  25576. classString = classValue + '';
  25577. }
  25578. return classString;
  25579. }
  25580. }
  25581. /**
  25582. * @ngdoc directive
  25583. * @name ngClass
  25584. * @restrict AC
  25585. * @element ANY
  25586. *
  25587. * @description
  25588. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  25589. * an expression that represents all classes to be added.
  25590. *
  25591. * The directive operates in three different ways, depending on which of three types the expression
  25592. * evaluates to:
  25593. *
  25594. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  25595. * names.
  25596. *
  25597. * 2. If the expression evaluates to an object, then for each key-value pair of the
  25598. * object with a truthy value the corresponding key is used as a class name.
  25599. *
  25600. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  25601. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  25602. * to give you more control over what CSS classes appear. See the code below for an example of this.
  25603. *
  25604. *
  25605. * The directive won't add duplicate classes if a particular class was already set.
  25606. *
  25607. * When the expression changes, the previously added classes are removed and only then are the
  25608. * new classes added.
  25609. *
  25610. * @knownIssue
  25611. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  25612. * attribute, when using the `ngClass` directive on the same element.
  25613. * See {@link guide/interpolation#known-issues here} for more info.
  25614. *
  25615. * @animations
  25616. * | Animation | Occurs |
  25617. * |----------------------------------|-------------------------------------|
  25618. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25619. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25620. * | {@link ng.$animate#setClass setClass} | just before classes are added and classes are removed from the element at the same time |
  25621. *
  25622. * ### ngClass and pre-existing CSS3 Transitions/Animations
  25623. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  25624. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  25625. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  25626. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  25627. {@link $animate#removeClass $animate.removeClass}.
  25628. *
  25629. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  25630. * of the evaluation can be a string representing space delimited class
  25631. * names, an array, or a map of class names to boolean values. In the case of a map, the
  25632. * names of the properties whose values are truthy will be added as css classes to the
  25633. * element.
  25634. *
  25635. * @example
  25636. * ### Basic
  25637. <example name="ng-class">
  25638. <file name="index.html">
  25639. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  25640. <label>
  25641. <input type="checkbox" ng-model="deleted">
  25642. deleted (apply "strike" class)
  25643. </label><br>
  25644. <label>
  25645. <input type="checkbox" ng-model="important">
  25646. important (apply "bold" class)
  25647. </label><br>
  25648. <label>
  25649. <input type="checkbox" ng-model="error">
  25650. error (apply "has-error" class)
  25651. </label>
  25652. <hr>
  25653. <p ng-class="style">Using String Syntax</p>
  25654. <input type="text" ng-model="style"
  25655. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  25656. <hr>
  25657. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  25658. <input ng-model="style1"
  25659. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  25660. <input ng-model="style2"
  25661. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  25662. <input ng-model="style3"
  25663. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  25664. <hr>
  25665. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  25666. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  25667. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  25668. </file>
  25669. <file name="style.css">
  25670. .strike {
  25671. text-decoration: line-through;
  25672. }
  25673. .bold {
  25674. font-weight: bold;
  25675. }
  25676. .red {
  25677. color: red;
  25678. }
  25679. .has-error {
  25680. color: red;
  25681. background-color: yellow;
  25682. }
  25683. .orange {
  25684. color: orange;
  25685. }
  25686. </file>
  25687. <file name="protractor.js" type="protractor">
  25688. var ps = element.all(by.css('p'));
  25689. it('should let you toggle the class', function() {
  25690. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  25691. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  25692. element(by.model('important')).click();
  25693. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  25694. element(by.model('error')).click();
  25695. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  25696. });
  25697. it('should let you toggle string example', function() {
  25698. expect(ps.get(1).getAttribute('class')).toBe('');
  25699. element(by.model('style')).clear();
  25700. element(by.model('style')).sendKeys('red');
  25701. expect(ps.get(1).getAttribute('class')).toBe('red');
  25702. });
  25703. it('array example should have 3 classes', function() {
  25704. expect(ps.get(2).getAttribute('class')).toBe('');
  25705. element(by.model('style1')).sendKeys('bold');
  25706. element(by.model('style2')).sendKeys('strike');
  25707. element(by.model('style3')).sendKeys('red');
  25708. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  25709. });
  25710. it('array with map example should have 2 classes', function() {
  25711. expect(ps.last().getAttribute('class')).toBe('');
  25712. element(by.model('style4')).sendKeys('bold');
  25713. element(by.model('warning')).click();
  25714. expect(ps.last().getAttribute('class')).toBe('bold orange');
  25715. });
  25716. </file>
  25717. </example>
  25718. @example
  25719. ### Animations
  25720. The example below demonstrates how to perform animations using ngClass.
  25721. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  25722. <file name="index.html">
  25723. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  25724. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  25725. <br>
  25726. <span class="base-class" ng-class="myVar">Sample Text</span>
  25727. </file>
  25728. <file name="style.css">
  25729. .base-class {
  25730. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25731. }
  25732. .base-class.my-class {
  25733. color: red;
  25734. font-size:3em;
  25735. }
  25736. </file>
  25737. <file name="protractor.js" type="protractor">
  25738. it('should check ng-class', function() {
  25739. expect(element(by.css('.base-class')).getAttribute('class')).not.
  25740. toMatch(/my-class/);
  25741. element(by.id('setbtn')).click();
  25742. expect(element(by.css('.base-class')).getAttribute('class')).
  25743. toMatch(/my-class/);
  25744. element(by.id('clearbtn')).click();
  25745. expect(element(by.css('.base-class')).getAttribute('class')).not.
  25746. toMatch(/my-class/);
  25747. });
  25748. </file>
  25749. </example>
  25750. */
  25751. var ngClassDirective = classDirective('', true);
  25752. /**
  25753. * @ngdoc directive
  25754. * @name ngClassOdd
  25755. * @restrict AC
  25756. *
  25757. * @description
  25758. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  25759. * {@link ng.directive:ngClass ngClass}, except they work in
  25760. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  25761. *
  25762. * This directive can be applied only within the scope of an
  25763. * {@link ng.directive:ngRepeat ngRepeat}.
  25764. *
  25765. * @animations
  25766. * | Animation | Occurs |
  25767. * |----------------------------------|-------------------------------------|
  25768. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25769. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25770. *
  25771. * @element ANY
  25772. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  25773. * of the evaluation can be a string representing space delimited class names or an array.
  25774. *
  25775. * @example
  25776. <example name="ng-class-odd">
  25777. <file name="index.html">
  25778. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  25779. <li ng-repeat="name in names">
  25780. <span ng-class-odd="'odd'" ng-class-even="'even'">
  25781. {{name}}
  25782. </span>
  25783. </li>
  25784. </ol>
  25785. </file>
  25786. <file name="style.css">
  25787. .odd {
  25788. color: red;
  25789. }
  25790. .even {
  25791. color: blue;
  25792. }
  25793. </file>
  25794. <file name="protractor.js" type="protractor">
  25795. it('should check ng-class-odd and ng-class-even', function() {
  25796. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  25797. toMatch(/odd/);
  25798. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  25799. toMatch(/even/);
  25800. });
  25801. </file>
  25802. </example>
  25803. *
  25804. * <hr />
  25805. * @example
  25806. * An example on how to implement animations using `ngClassOdd`:
  25807. *
  25808. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-odd-animate">
  25809. <file name="index.html">
  25810. <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']">
  25811. <button ng-click="items.unshift('Item ' + items.length)">Add item</button>
  25812. <hr />
  25813. <table>
  25814. <tr ng-repeat="item in items" ng-class-odd="'odd'">
  25815. <td>{{ item }}</td>
  25816. </tr>
  25817. </table>
  25818. </div>
  25819. </file>
  25820. <file name="style.css">
  25821. .odd {
  25822. background: rgba(255, 255, 0, 0.25);
  25823. }
  25824. .odd-add, .odd-remove {
  25825. transition: 1.5s;
  25826. }
  25827. </file>
  25828. <file name="protractor.js" type="protractor">
  25829. it('should add new entries to the beginning of the list', function() {
  25830. var button = element(by.buttonText('Add item'));
  25831. var rows = element.all(by.repeater('item in items'));
  25832. expect(rows.count()).toBe(4);
  25833. expect(rows.get(0).getText()).toBe('Item 3');
  25834. expect(rows.get(1).getText()).toBe('Item 2');
  25835. button.click();
  25836. expect(rows.count()).toBe(5);
  25837. expect(rows.get(0).getText()).toBe('Item 4');
  25838. expect(rows.get(1).getText()).toBe('Item 3');
  25839. });
  25840. it('should add odd class to odd entries', function() {
  25841. var button = element(by.buttonText('Add item'));
  25842. var rows = element.all(by.repeater('item in items'));
  25843. expect(rows.get(0).getAttribute('class')).toMatch(/odd/);
  25844. expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/);
  25845. button.click();
  25846. expect(rows.get(0).getAttribute('class')).toMatch(/odd/);
  25847. expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/);
  25848. });
  25849. </file>
  25850. </example>
  25851. */
  25852. var ngClassOddDirective = classDirective('Odd', 0);
  25853. /**
  25854. * @ngdoc directive
  25855. * @name ngClassEven
  25856. * @restrict AC
  25857. *
  25858. * @description
  25859. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  25860. * {@link ng.directive:ngClass ngClass}, except they work in
  25861. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  25862. *
  25863. * This directive can be applied only within the scope of an
  25864. * {@link ng.directive:ngRepeat ngRepeat}.
  25865. *
  25866. * @animations
  25867. * | Animation | Occurs |
  25868. * |----------------------------------|-------------------------------------|
  25869. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25870. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25871. *
  25872. * @element ANY
  25873. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  25874. * result of the evaluation can be a string representing space delimited class names or an array.
  25875. *
  25876. * @example
  25877. <example name="ng-class-even">
  25878. <file name="index.html">
  25879. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  25880. <li ng-repeat="name in names">
  25881. <span ng-class-odd="'odd'" ng-class-even="'even'">
  25882. {{name}} &nbsp; &nbsp; &nbsp;
  25883. </span>
  25884. </li>
  25885. </ol>
  25886. </file>
  25887. <file name="style.css">
  25888. .odd {
  25889. color: red;
  25890. }
  25891. .even {
  25892. color: blue;
  25893. }
  25894. </file>
  25895. <file name="protractor.js" type="protractor">
  25896. it('should check ng-class-odd and ng-class-even', function() {
  25897. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  25898. toMatch(/odd/);
  25899. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  25900. toMatch(/even/);
  25901. });
  25902. </file>
  25903. </example>
  25904. *
  25905. * <hr />
  25906. * @example
  25907. * An example on how to implement animations using `ngClassEven`:
  25908. *
  25909. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-even-animate">
  25910. <file name="index.html">
  25911. <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']">
  25912. <button ng-click="items.unshift('Item ' + items.length)">Add item</button>
  25913. <hr />
  25914. <table>
  25915. <tr ng-repeat="item in items" ng-class-even="'even'">
  25916. <td>{{ item }}</td>
  25917. </tr>
  25918. </table>
  25919. </div>
  25920. </file>
  25921. <file name="style.css">
  25922. .even {
  25923. background: rgba(255, 255, 0, 0.25);
  25924. }
  25925. .even-add, .even-remove {
  25926. transition: 1.5s;
  25927. }
  25928. </file>
  25929. <file name="protractor.js" type="protractor">
  25930. it('should add new entries to the beginning of the list', function() {
  25931. var button = element(by.buttonText('Add item'));
  25932. var rows = element.all(by.repeater('item in items'));
  25933. expect(rows.count()).toBe(4);
  25934. expect(rows.get(0).getText()).toBe('Item 3');
  25935. expect(rows.get(1).getText()).toBe('Item 2');
  25936. button.click();
  25937. expect(rows.count()).toBe(5);
  25938. expect(rows.get(0).getText()).toBe('Item 4');
  25939. expect(rows.get(1).getText()).toBe('Item 3');
  25940. });
  25941. it('should add even class to even entries', function() {
  25942. var button = element(by.buttonText('Add item'));
  25943. var rows = element.all(by.repeater('item in items'));
  25944. expect(rows.get(0).getAttribute('class')).not.toMatch(/even/);
  25945. expect(rows.get(1).getAttribute('class')).toMatch(/even/);
  25946. button.click();
  25947. expect(rows.get(0).getAttribute('class')).not.toMatch(/even/);
  25948. expect(rows.get(1).getAttribute('class')).toMatch(/even/);
  25949. });
  25950. </file>
  25951. </example>
  25952. */
  25953. var ngClassEvenDirective = classDirective('Even', 1);
  25954. /**
  25955. * @ngdoc directive
  25956. * @name ngCloak
  25957. * @restrict AC
  25958. *
  25959. * @description
  25960. * The `ngCloak` directive is used to prevent the AngularJS html template from being briefly
  25961. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  25962. * directive to avoid the undesirable flicker effect caused by the html template display.
  25963. *
  25964. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  25965. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  25966. * of the browser view.
  25967. *
  25968. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  25969. * `angular.min.js`.
  25970. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25971. *
  25972. * ```css
  25973. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  25974. * display: none !important;
  25975. * }
  25976. * ```
  25977. *
  25978. * When this css rule is loaded by the browser, all html elements (including their children) that
  25979. * are tagged with the `ngCloak` directive are hidden. When AngularJS encounters this directive
  25980. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  25981. * the compiled element visible.
  25982. *
  25983. * For the best result, the `angular.js` script must be loaded in the head section of the html
  25984. * document; alternatively, the css rule above must be included in the external stylesheet of the
  25985. * application.
  25986. *
  25987. * @element ANY
  25988. *
  25989. * @example
  25990. <example name="ng-cloak">
  25991. <file name="index.html">
  25992. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  25993. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  25994. </file>
  25995. <file name="protractor.js" type="protractor">
  25996. it('should remove the template directive and css class', function() {
  25997. expect($('#template1').getAttribute('ng-cloak')).
  25998. toBeNull();
  25999. expect($('#template2').getAttribute('ng-cloak')).
  26000. toBeNull();
  26001. });
  26002. </file>
  26003. </example>
  26004. *
  26005. */
  26006. var ngCloakDirective = ngDirective({
  26007. compile: function(element, attr) {
  26008. attr.$set('ngCloak', undefined);
  26009. element.removeClass('ng-cloak');
  26010. }
  26011. });
  26012. /**
  26013. * @ngdoc directive
  26014. * @name ngController
  26015. *
  26016. * @description
  26017. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  26018. * supports the principles behind the Model-View-Controller design pattern.
  26019. *
  26020. * MVC components in angular:
  26021. *
  26022. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  26023. * are accessed through bindings.
  26024. * * View — The template (HTML with data bindings) that is rendered into the View.
  26025. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  26026. * logic behind the application to decorate the scope with functions and values
  26027. *
  26028. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  26029. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  26030. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  26031. * and executed twice.
  26032. *
  26033. * @element ANY
  26034. * @scope
  26035. * @priority 500
  26036. * @param {expression} ngController Name of a constructor function registered with the current
  26037. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  26038. * that on the current scope evaluates to a constructor function.
  26039. *
  26040. * The controller instance can be published into a scope property by specifying
  26041. * `ng-controller="as propertyName"`.
  26042. *
  26043. * @example
  26044. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  26045. * greeting are methods declared on the controller (see source tab). These methods can
  26046. * easily be called from the AngularJS markup. Any changes to the data are automatically reflected
  26047. * in the View without the need for a manual update.
  26048. *
  26049. * Two different declaration styles are included below:
  26050. *
  26051. * * one binds methods and properties directly onto the controller using `this`:
  26052. * `ng-controller="SettingsController1 as settings"`
  26053. * * one injects `$scope` into the controller:
  26054. * `ng-controller="SettingsController2"`
  26055. *
  26056. * The second option is more common in the AngularJS community, and is generally used in boilerplates
  26057. * and in this guide. However, there are advantages to binding properties directly to the controller
  26058. * and avoiding scope.
  26059. *
  26060. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  26061. * multiple controllers apply to an element.
  26062. * * If you are writing your controllers as classes you have easier access to the properties and
  26063. * methods, which will appear on the scope, from inside the controller code.
  26064. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  26065. * inheritance masking primitives.
  26066. *
  26067. * This example demonstrates the `controller as` syntax.
  26068. *
  26069. * <example name="ngControllerAs" module="controllerAsExample">
  26070. * <file name="index.html">
  26071. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  26072. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  26073. * <button ng-click="settings.greet()">greet</button><br/>
  26074. * Contact:
  26075. * <ul>
  26076. * <li ng-repeat="contact in settings.contacts">
  26077. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  26078. * <option>phone</option>
  26079. * <option>email</option>
  26080. * </select>
  26081. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  26082. * <button ng-click="settings.clearContact(contact)">clear</button>
  26083. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  26084. * </li>
  26085. * <li><button ng-click="settings.addContact()">add</button></li>
  26086. * </ul>
  26087. * </div>
  26088. * </file>
  26089. * <file name="app.js">
  26090. * angular.module('controllerAsExample', [])
  26091. * .controller('SettingsController1', SettingsController1);
  26092. *
  26093. * function SettingsController1() {
  26094. * this.name = 'John Smith';
  26095. * this.contacts = [
  26096. * {type: 'phone', value: '408 555 1212'},
  26097. * {type: 'email', value: 'john.smith@example.org'}
  26098. * ];
  26099. * }
  26100. *
  26101. * SettingsController1.prototype.greet = function() {
  26102. * alert(this.name);
  26103. * };
  26104. *
  26105. * SettingsController1.prototype.addContact = function() {
  26106. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  26107. * };
  26108. *
  26109. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  26110. * var index = this.contacts.indexOf(contactToRemove);
  26111. * this.contacts.splice(index, 1);
  26112. * };
  26113. *
  26114. * SettingsController1.prototype.clearContact = function(contact) {
  26115. * contact.type = 'phone';
  26116. * contact.value = '';
  26117. * };
  26118. * </file>
  26119. * <file name="protractor.js" type="protractor">
  26120. * it('should check controller as', function() {
  26121. * var container = element(by.id('ctrl-as-exmpl'));
  26122. * expect(container.element(by.model('settings.name'))
  26123. * .getAttribute('value')).toBe('John Smith');
  26124. *
  26125. * var firstRepeat =
  26126. * container.element(by.repeater('contact in settings.contacts').row(0));
  26127. * var secondRepeat =
  26128. * container.element(by.repeater('contact in settings.contacts').row(1));
  26129. *
  26130. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  26131. * .toBe('408 555 1212');
  26132. *
  26133. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  26134. * .toBe('john.smith@example.org');
  26135. *
  26136. * firstRepeat.element(by.buttonText('clear')).click();
  26137. *
  26138. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  26139. * .toBe('');
  26140. *
  26141. * container.element(by.buttonText('add')).click();
  26142. *
  26143. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  26144. * .element(by.model('contact.value'))
  26145. * .getAttribute('value'))
  26146. * .toBe('yourname@example.org');
  26147. * });
  26148. * </file>
  26149. * </example>
  26150. *
  26151. * This example demonstrates the "attach to `$scope`" style of controller.
  26152. *
  26153. * <example name="ngController" module="controllerExample">
  26154. * <file name="index.html">
  26155. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  26156. * <label>Name: <input type="text" ng-model="name"/></label>
  26157. * <button ng-click="greet()">greet</button><br/>
  26158. * Contact:
  26159. * <ul>
  26160. * <li ng-repeat="contact in contacts">
  26161. * <select ng-model="contact.type" id="select_{{$index}}">
  26162. * <option>phone</option>
  26163. * <option>email</option>
  26164. * </select>
  26165. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  26166. * <button ng-click="clearContact(contact)">clear</button>
  26167. * <button ng-click="removeContact(contact)">X</button>
  26168. * </li>
  26169. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  26170. * </ul>
  26171. * </div>
  26172. * </file>
  26173. * <file name="app.js">
  26174. * angular.module('controllerExample', [])
  26175. * .controller('SettingsController2', ['$scope', SettingsController2]);
  26176. *
  26177. * function SettingsController2($scope) {
  26178. * $scope.name = 'John Smith';
  26179. * $scope.contacts = [
  26180. * {type:'phone', value:'408 555 1212'},
  26181. * {type:'email', value:'john.smith@example.org'}
  26182. * ];
  26183. *
  26184. * $scope.greet = function() {
  26185. * alert($scope.name);
  26186. * };
  26187. *
  26188. * $scope.addContact = function() {
  26189. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  26190. * };
  26191. *
  26192. * $scope.removeContact = function(contactToRemove) {
  26193. * var index = $scope.contacts.indexOf(contactToRemove);
  26194. * $scope.contacts.splice(index, 1);
  26195. * };
  26196. *
  26197. * $scope.clearContact = function(contact) {
  26198. * contact.type = 'phone';
  26199. * contact.value = '';
  26200. * };
  26201. * }
  26202. * </file>
  26203. * <file name="protractor.js" type="protractor">
  26204. * it('should check controller', function() {
  26205. * var container = element(by.id('ctrl-exmpl'));
  26206. *
  26207. * expect(container.element(by.model('name'))
  26208. * .getAttribute('value')).toBe('John Smith');
  26209. *
  26210. * var firstRepeat =
  26211. * container.element(by.repeater('contact in contacts').row(0));
  26212. * var secondRepeat =
  26213. * container.element(by.repeater('contact in contacts').row(1));
  26214. *
  26215. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  26216. * .toBe('408 555 1212');
  26217. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  26218. * .toBe('john.smith@example.org');
  26219. *
  26220. * firstRepeat.element(by.buttonText('clear')).click();
  26221. *
  26222. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  26223. * .toBe('');
  26224. *
  26225. * container.element(by.buttonText('add')).click();
  26226. *
  26227. * expect(container.element(by.repeater('contact in contacts').row(2))
  26228. * .element(by.model('contact.value'))
  26229. * .getAttribute('value'))
  26230. * .toBe('yourname@example.org');
  26231. * });
  26232. * </file>
  26233. *</example>
  26234. */
  26235. var ngControllerDirective = [function() {
  26236. return {
  26237. restrict: 'A',
  26238. scope: true,
  26239. controller: '@',
  26240. priority: 500
  26241. };
  26242. }];
  26243. /**
  26244. * @ngdoc directive
  26245. * @name ngCsp
  26246. *
  26247. * @restrict A
  26248. * @element ANY
  26249. * @description
  26250. *
  26251. * AngularJS has some features that can conflict with certain restrictions that are applied when using
  26252. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  26253. *
  26254. * If you intend to implement CSP with these rules then you must tell AngularJS not to use these
  26255. * features.
  26256. *
  26257. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  26258. *
  26259. *
  26260. * The following default rules in CSP affect AngularJS:
  26261. *
  26262. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  26263. * code from strings is forbidden. AngularJS makes use of this in the {@link $parse} service to
  26264. * provide a 30% increase in the speed of evaluating AngularJS expressions. (This CSP rule can be
  26265. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  26266. * weaken the protections offered by CSP.)
  26267. *
  26268. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  26269. * This prevents apps from injecting custom styles directly into the document. AngularJS makes use of
  26270. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  26271. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  26272. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  26273. * it is generally not recommended as it would weaken the protections offered by CSP.)
  26274. *
  26275. * If you do not provide `ngCsp` then AngularJS tries to autodetect if CSP is blocking dynamic code
  26276. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  26277. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  26278. * CSP error to be logged in the console:
  26279. *
  26280. * ```
  26281. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  26282. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  26283. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  26284. * ```
  26285. *
  26286. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  26287. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  26288. * the `angular.js` file.
  26289. *
  26290. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  26291. *
  26292. * You can specify which of the CSP related AngularJS features should be deactivated by providing
  26293. * a value for the `ng-csp` attribute. The options are as follows:
  26294. *
  26295. * * no-inline-style: this stops AngularJS from injecting CSS styles into the DOM
  26296. *
  26297. * * no-unsafe-eval: this stops AngularJS from optimizing $parse with unsafe eval of strings
  26298. *
  26299. * You can use these values in the following combinations:
  26300. *
  26301. *
  26302. * * No declaration means that AngularJS will assume that you can do inline styles, but it will do
  26303. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  26304. * versions of AngularJS.
  26305. *
  26306. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell AngularJS to deactivate both inline
  26307. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  26308. * versions of AngularJS.
  26309. *
  26310. * * Specifying only `no-unsafe-eval` tells AngularJS that we must not use eval, but that we can
  26311. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  26312. *
  26313. * * Specifying only `no-inline-style` tells AngularJS that we must not inject styles, but that we can
  26314. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  26315. *
  26316. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells AngularJS that we must not inject
  26317. * styles nor use eval, which is the same as an empty: ng-csp.
  26318. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  26319. *
  26320. * @example
  26321. *
  26322. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  26323. ```html
  26324. <!doctype html>
  26325. <html ng-app ng-csp>
  26326. ...
  26327. ...
  26328. </html>
  26329. ```
  26330. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  26331. <example name="example.csp" module="cspExample" ng-csp="true">
  26332. <file name="index.html">
  26333. <div ng-controller="MainController as ctrl">
  26334. <div>
  26335. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  26336. <span id="counter">
  26337. {{ctrl.counter}}
  26338. </span>
  26339. </div>
  26340. <div>
  26341. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  26342. <span id="evilError">
  26343. {{ctrl.evilError}}
  26344. </span>
  26345. </div>
  26346. </div>
  26347. </file>
  26348. <file name="script.js">
  26349. angular.module('cspExample', [])
  26350. .controller('MainController', function MainController() {
  26351. this.counter = 0;
  26352. this.inc = function() {
  26353. this.counter++;
  26354. };
  26355. this.evil = function() {
  26356. try {
  26357. eval('1+2'); // eslint-disable-line no-eval
  26358. } catch (e) {
  26359. this.evilError = e.message;
  26360. }
  26361. };
  26362. });
  26363. </file>
  26364. <file name="protractor.js" type="protractor">
  26365. var util, webdriver;
  26366. var incBtn = element(by.id('inc'));
  26367. var counter = element(by.id('counter'));
  26368. var evilBtn = element(by.id('evil'));
  26369. var evilError = element(by.id('evilError'));
  26370. function getAndClearSevereErrors() {
  26371. return browser.manage().logs().get('browser').then(function(browserLog) {
  26372. return browserLog.filter(function(logEntry) {
  26373. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  26374. });
  26375. });
  26376. }
  26377. function clearErrors() {
  26378. getAndClearSevereErrors();
  26379. }
  26380. function expectNoErrors() {
  26381. getAndClearSevereErrors().then(function(filteredLog) {
  26382. expect(filteredLog.length).toEqual(0);
  26383. if (filteredLog.length) {
  26384. console.log('browser console errors: ' + util.inspect(filteredLog));
  26385. }
  26386. });
  26387. }
  26388. function expectError(regex) {
  26389. getAndClearSevereErrors().then(function(filteredLog) {
  26390. var found = false;
  26391. filteredLog.forEach(function(log) {
  26392. if (log.message.match(regex)) {
  26393. found = true;
  26394. }
  26395. });
  26396. if (!found) {
  26397. throw new Error('expected an error that matches ' + regex);
  26398. }
  26399. });
  26400. }
  26401. beforeEach(function() {
  26402. util = require('util');
  26403. webdriver = require('selenium-webdriver');
  26404. });
  26405. // For now, we only test on Chrome,
  26406. // as Safari does not load the page with Protractor's injected scripts,
  26407. // and Firefox webdriver always disables content security policy (#6358)
  26408. if (browser.params.browser !== 'chrome') {
  26409. return;
  26410. }
  26411. it('should not report errors when the page is loaded', function() {
  26412. // clear errors so we are not dependent on previous tests
  26413. clearErrors();
  26414. // Need to reload the page as the page is already loaded when
  26415. // we come here
  26416. browser.driver.getCurrentUrl().then(function(url) {
  26417. browser.get(url);
  26418. });
  26419. expectNoErrors();
  26420. });
  26421. it('should evaluate expressions', function() {
  26422. expect(counter.getText()).toEqual('0');
  26423. incBtn.click();
  26424. expect(counter.getText()).toEqual('1');
  26425. expectNoErrors();
  26426. });
  26427. it('should throw and report an error when using "eval"', function() {
  26428. evilBtn.click();
  26429. expect(evilError.getText()).toMatch(/Content Security Policy/);
  26430. expectError(/Content Security Policy/);
  26431. });
  26432. </file>
  26433. </example>
  26434. */
  26435. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  26436. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  26437. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  26438. /**
  26439. * @ngdoc directive
  26440. * @name ngClick
  26441. * @restrict A
  26442. * @element ANY
  26443. * @priority 0
  26444. *
  26445. * @description
  26446. * The ngClick directive allows you to specify custom behavior when
  26447. * an element is clicked.
  26448. *
  26449. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  26450. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  26451. *
  26452. * @example
  26453. <example name="ng-click">
  26454. <file name="index.html">
  26455. <button ng-click="count = count + 1" ng-init="count=0">
  26456. Increment
  26457. </button>
  26458. <span>
  26459. count: {{count}}
  26460. </span>
  26461. </file>
  26462. <file name="protractor.js" type="protractor">
  26463. it('should check ng-click', function() {
  26464. expect(element(by.binding('count')).getText()).toMatch('0');
  26465. element(by.css('button')).click();
  26466. expect(element(by.binding('count')).getText()).toMatch('1');
  26467. });
  26468. </file>
  26469. </example>
  26470. */
  26471. /*
  26472. * A collection of directives that allows creation of custom event handlers that are defined as
  26473. * AngularJS expressions and are compiled and executed within the current scope.
  26474. */
  26475. var ngEventDirectives = {};
  26476. // For events that might fire synchronously during DOM manipulation
  26477. // we need to execute their event handlers asynchronously using $evalAsync,
  26478. // so that they are not executed in an inconsistent state.
  26479. var forceAsyncEvents = {
  26480. 'blur': true,
  26481. 'focus': true
  26482. };
  26483. forEach(
  26484. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  26485. function(eventName) {
  26486. var directiveName = directiveNormalize('ng-' + eventName);
  26487. ngEventDirectives[directiveName] = ['$parse', '$rootScope', '$exceptionHandler', function($parse, $rootScope, $exceptionHandler) {
  26488. return createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsyncEvents[eventName]);
  26489. }];
  26490. }
  26491. );
  26492. function createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsync) {
  26493. return {
  26494. restrict: 'A',
  26495. compile: function($element, attr) {
  26496. // NOTE:
  26497. // We expose the powerful `$event` object on the scope that provides access to the Window,
  26498. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  26499. // sandbox was never meant to be a security feature anyway).
  26500. var fn = $parse(attr[directiveName]);
  26501. return function ngEventHandler(scope, element) {
  26502. element.on(eventName, function(event) {
  26503. var callback = function() {
  26504. fn(scope, {$event: event});
  26505. };
  26506. if (!$rootScope.$$phase) {
  26507. scope.$apply(callback);
  26508. } else if (forceAsync) {
  26509. scope.$evalAsync(callback);
  26510. } else {
  26511. try {
  26512. callback();
  26513. } catch (error) {
  26514. $exceptionHandler(error);
  26515. }
  26516. }
  26517. });
  26518. };
  26519. }
  26520. };
  26521. }
  26522. /**
  26523. * @ngdoc directive
  26524. * @name ngDblclick
  26525. * @restrict A
  26526. * @element ANY
  26527. * @priority 0
  26528. *
  26529. * @description
  26530. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  26531. *
  26532. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  26533. * a dblclick. (The Event object is available as `$event`)
  26534. *
  26535. * @example
  26536. <example name="ng-dblclick">
  26537. <file name="index.html">
  26538. <button ng-dblclick="count = count + 1" ng-init="count=0">
  26539. Increment (on double click)
  26540. </button>
  26541. count: {{count}}
  26542. </file>
  26543. </example>
  26544. */
  26545. /**
  26546. * @ngdoc directive
  26547. * @name ngMousedown
  26548. * @restrict A
  26549. * @element ANY
  26550. * @priority 0
  26551. *
  26552. * @description
  26553. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  26554. *
  26555. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  26556. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  26557. *
  26558. * @example
  26559. <example name="ng-mousedown">
  26560. <file name="index.html">
  26561. <button ng-mousedown="count = count + 1" ng-init="count=0">
  26562. Increment (on mouse down)
  26563. </button>
  26564. count: {{count}}
  26565. </file>
  26566. </example>
  26567. */
  26568. /**
  26569. * @ngdoc directive
  26570. * @name ngMouseup
  26571. * @restrict A
  26572. * @element ANY
  26573. * @priority 0
  26574. *
  26575. * @description
  26576. * Specify custom behavior on mouseup event.
  26577. *
  26578. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  26579. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  26580. *
  26581. * @example
  26582. <example name="ng-mouseup">
  26583. <file name="index.html">
  26584. <button ng-mouseup="count = count + 1" ng-init="count=0">
  26585. Increment (on mouse up)
  26586. </button>
  26587. count: {{count}}
  26588. </file>
  26589. </example>
  26590. */
  26591. /**
  26592. * @ngdoc directive
  26593. * @name ngMouseover
  26594. * @restrict A
  26595. * @element ANY
  26596. * @priority 0
  26597. *
  26598. * @description
  26599. * Specify custom behavior on mouseover event.
  26600. *
  26601. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  26602. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  26603. *
  26604. * @example
  26605. <example name="ng-mouseover">
  26606. <file name="index.html">
  26607. <button ng-mouseover="count = count + 1" ng-init="count=0">
  26608. Increment (when mouse is over)
  26609. </button>
  26610. count: {{count}}
  26611. </file>
  26612. </example>
  26613. */
  26614. /**
  26615. * @ngdoc directive
  26616. * @name ngMouseenter
  26617. * @restrict A
  26618. * @element ANY
  26619. * @priority 0
  26620. *
  26621. * @description
  26622. * Specify custom behavior on mouseenter event.
  26623. *
  26624. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  26625. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  26626. *
  26627. * @example
  26628. <example name="ng-mouseenter">
  26629. <file name="index.html">
  26630. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  26631. Increment (when mouse enters)
  26632. </button>
  26633. count: {{count}}
  26634. </file>
  26635. </example>
  26636. */
  26637. /**
  26638. * @ngdoc directive
  26639. * @name ngMouseleave
  26640. * @restrict A
  26641. * @element ANY
  26642. * @priority 0
  26643. *
  26644. * @description
  26645. * Specify custom behavior on mouseleave event.
  26646. *
  26647. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  26648. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  26649. *
  26650. * @example
  26651. <example name="ng-mouseleave">
  26652. <file name="index.html">
  26653. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  26654. Increment (when mouse leaves)
  26655. </button>
  26656. count: {{count}}
  26657. </file>
  26658. </example>
  26659. */
  26660. /**
  26661. * @ngdoc directive
  26662. * @name ngMousemove
  26663. * @restrict A
  26664. * @element ANY
  26665. * @priority 0
  26666. *
  26667. * @description
  26668. * Specify custom behavior on mousemove event.
  26669. *
  26670. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  26671. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  26672. *
  26673. * @example
  26674. <example name="ng-mousemove">
  26675. <file name="index.html">
  26676. <button ng-mousemove="count = count + 1" ng-init="count=0">
  26677. Increment (when mouse moves)
  26678. </button>
  26679. count: {{count}}
  26680. </file>
  26681. </example>
  26682. */
  26683. /**
  26684. * @ngdoc directive
  26685. * @name ngKeydown
  26686. * @restrict A
  26687. * @element ANY
  26688. * @priority 0
  26689. *
  26690. * @description
  26691. * Specify custom behavior on keydown event.
  26692. *
  26693. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  26694. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  26695. *
  26696. * @example
  26697. <example name="ng-keydown">
  26698. <file name="index.html">
  26699. <input ng-keydown="count = count + 1" ng-init="count=0">
  26700. key down count: {{count}}
  26701. </file>
  26702. </example>
  26703. */
  26704. /**
  26705. * @ngdoc directive
  26706. * @name ngKeyup
  26707. * @restrict A
  26708. * @element ANY
  26709. * @priority 0
  26710. *
  26711. * @description
  26712. * Specify custom behavior on keyup event.
  26713. *
  26714. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  26715. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  26716. *
  26717. * @example
  26718. <example name="ng-keyup">
  26719. <file name="index.html">
  26720. <p>Typing in the input box below updates the key count</p>
  26721. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  26722. <p>Typing in the input box below updates the keycode</p>
  26723. <input ng-keyup="event=$event">
  26724. <p>event keyCode: {{ event.keyCode }}</p>
  26725. <p>event altKey: {{ event.altKey }}</p>
  26726. </file>
  26727. </example>
  26728. */
  26729. /**
  26730. * @ngdoc directive
  26731. * @name ngKeypress
  26732. * @restrict A
  26733. * @element ANY
  26734. *
  26735. * @description
  26736. * Specify custom behavior on keypress event.
  26737. *
  26738. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  26739. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  26740. * and can be interrogated for keyCode, altKey, etc.)
  26741. *
  26742. * @example
  26743. <example name="ng-keypress">
  26744. <file name="index.html">
  26745. <input ng-keypress="count = count + 1" ng-init="count=0">
  26746. key press count: {{count}}
  26747. </file>
  26748. </example>
  26749. */
  26750. /**
  26751. * @ngdoc directive
  26752. * @name ngSubmit
  26753. * @restrict A
  26754. * @element form
  26755. * @priority 0
  26756. *
  26757. * @description
  26758. * Enables binding AngularJS expressions to onsubmit events.
  26759. *
  26760. * Additionally it prevents the default action (which for form means sending the request to the
  26761. * server and reloading the current page), but only if the form does not contain `action`,
  26762. * `data-action`, or `x-action` attributes.
  26763. *
  26764. * <div class="alert alert-warning">
  26765. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  26766. * `ngSubmit` handlers together. See the
  26767. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  26768. * for a detailed discussion of when `ngSubmit` may be triggered.
  26769. * </div>
  26770. *
  26771. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  26772. * ({@link guide/expression#-event- Event object is available as `$event`})
  26773. *
  26774. * @example
  26775. <example module="submitExample" name="ng-submit">
  26776. <file name="index.html">
  26777. <script>
  26778. angular.module('submitExample', [])
  26779. .controller('ExampleController', ['$scope', function($scope) {
  26780. $scope.list = [];
  26781. $scope.text = 'hello';
  26782. $scope.submit = function() {
  26783. if ($scope.text) {
  26784. $scope.list.push(this.text);
  26785. $scope.text = '';
  26786. }
  26787. };
  26788. }]);
  26789. </script>
  26790. <form ng-submit="submit()" ng-controller="ExampleController">
  26791. Enter text and hit enter:
  26792. <input type="text" ng-model="text" name="text" />
  26793. <input type="submit" id="submit" value="Submit" />
  26794. <pre>list={{list}}</pre>
  26795. </form>
  26796. </file>
  26797. <file name="protractor.js" type="protractor">
  26798. it('should check ng-submit', function() {
  26799. expect(element(by.binding('list')).getText()).toBe('list=[]');
  26800. element(by.css('#submit')).click();
  26801. expect(element(by.binding('list')).getText()).toContain('hello');
  26802. expect(element(by.model('text')).getAttribute('value')).toBe('');
  26803. });
  26804. it('should ignore empty strings', function() {
  26805. expect(element(by.binding('list')).getText()).toBe('list=[]');
  26806. element(by.css('#submit')).click();
  26807. element(by.css('#submit')).click();
  26808. expect(element(by.binding('list')).getText()).toContain('hello');
  26809. });
  26810. </file>
  26811. </example>
  26812. */
  26813. /**
  26814. * @ngdoc directive
  26815. * @name ngFocus
  26816. * @restrict A
  26817. * @element window, input, select, textarea, a
  26818. * @priority 0
  26819. *
  26820. * @description
  26821. * Specify custom behavior on focus event.
  26822. *
  26823. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  26824. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  26825. * during an `$apply` to ensure a consistent state.
  26826. *
  26827. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  26828. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  26829. *
  26830. * @example
  26831. * See {@link ng.directive:ngClick ngClick}
  26832. */
  26833. /**
  26834. * @ngdoc directive
  26835. * @name ngBlur
  26836. * @restrict A
  26837. * @element window, input, select, textarea, a
  26838. * @priority 0
  26839. *
  26840. * @description
  26841. * Specify custom behavior on blur event.
  26842. *
  26843. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  26844. * an element has lost focus.
  26845. *
  26846. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  26847. * (e.g. removing a focussed input),
  26848. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  26849. * during an `$apply` to ensure a consistent state.
  26850. *
  26851. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  26852. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  26853. *
  26854. * @example
  26855. * See {@link ng.directive:ngClick ngClick}
  26856. */
  26857. /**
  26858. * @ngdoc directive
  26859. * @name ngCopy
  26860. * @restrict A
  26861. * @element window, input, select, textarea, a
  26862. * @priority 0
  26863. *
  26864. * @description
  26865. * Specify custom behavior on copy event.
  26866. *
  26867. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  26868. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  26869. *
  26870. * @example
  26871. <example name="ng-copy">
  26872. <file name="index.html">
  26873. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  26874. copied: {{copied}}
  26875. </file>
  26876. </example>
  26877. */
  26878. /**
  26879. * @ngdoc directive
  26880. * @name ngCut
  26881. * @restrict A
  26882. * @element window, input, select, textarea, a
  26883. * @priority 0
  26884. *
  26885. * @description
  26886. * Specify custom behavior on cut event.
  26887. *
  26888. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  26889. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  26890. *
  26891. * @example
  26892. <example name="ng-cut">
  26893. <file name="index.html">
  26894. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  26895. cut: {{cut}}
  26896. </file>
  26897. </example>
  26898. */
  26899. /**
  26900. * @ngdoc directive
  26901. * @name ngPaste
  26902. * @restrict A
  26903. * @element window, input, select, textarea, a
  26904. * @priority 0
  26905. *
  26906. * @description
  26907. * Specify custom behavior on paste event.
  26908. *
  26909. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  26910. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  26911. *
  26912. * @example
  26913. <example name="ng-paste">
  26914. <file name="index.html">
  26915. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  26916. pasted: {{paste}}
  26917. </file>
  26918. </example>
  26919. */
  26920. /**
  26921. * @ngdoc directive
  26922. * @name ngIf
  26923. * @restrict A
  26924. * @multiElement
  26925. *
  26926. * @description
  26927. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  26928. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  26929. * value then the element is removed from the DOM, otherwise a clone of the
  26930. * element is reinserted into the DOM.
  26931. *
  26932. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  26933. * element in the DOM rather than changing its visibility via the `display` css property. A common
  26934. * case when this difference is significant is when using css selectors that rely on an element's
  26935. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  26936. *
  26937. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  26938. * is created when the element is restored. The scope created within `ngIf` inherits from
  26939. * its parent scope using
  26940. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  26941. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  26942. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  26943. * variable within the child scope will override (hide) the value in the parent scope.
  26944. *
  26945. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  26946. * is if an element's class attribute is directly modified after it's compiled, using something like
  26947. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  26948. * the added class will be lost because the original compiled state is used to regenerate the element.
  26949. *
  26950. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  26951. * and `leave` effects.
  26952. *
  26953. * @animations
  26954. * | Animation | Occurs |
  26955. * |----------------------------------|-------------------------------------|
  26956. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  26957. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  26958. *
  26959. * @element ANY
  26960. * @scope
  26961. * @priority 600
  26962. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  26963. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  26964. * element is added to the DOM tree.
  26965. *
  26966. * @example
  26967. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  26968. <file name="index.html">
  26969. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  26970. Show when checked:
  26971. <span ng-if="checked" class="animate-if">
  26972. This is removed when the checkbox is unchecked.
  26973. </span>
  26974. </file>
  26975. <file name="animations.css">
  26976. .animate-if {
  26977. background:white;
  26978. border:1px solid black;
  26979. padding:10px;
  26980. }
  26981. .animate-if.ng-enter, .animate-if.ng-leave {
  26982. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26983. }
  26984. .animate-if.ng-enter,
  26985. .animate-if.ng-leave.ng-leave-active {
  26986. opacity:0;
  26987. }
  26988. .animate-if.ng-leave,
  26989. .animate-if.ng-enter.ng-enter-active {
  26990. opacity:1;
  26991. }
  26992. </file>
  26993. </example>
  26994. */
  26995. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  26996. return {
  26997. multiElement: true,
  26998. transclude: 'element',
  26999. priority: 600,
  27000. terminal: true,
  27001. restrict: 'A',
  27002. $$tlb: true,
  27003. link: function($scope, $element, $attr, ctrl, $transclude) {
  27004. var block, childScope, previousElements;
  27005. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  27006. if (value) {
  27007. if (!childScope) {
  27008. $transclude(function(clone, newScope) {
  27009. childScope = newScope;
  27010. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  27011. // Note: We only need the first/last node of the cloned nodes.
  27012. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  27013. // by a directive with templateUrl when its template arrives.
  27014. block = {
  27015. clone: clone
  27016. };
  27017. $animate.enter(clone, $element.parent(), $element);
  27018. });
  27019. }
  27020. } else {
  27021. if (previousElements) {
  27022. previousElements.remove();
  27023. previousElements = null;
  27024. }
  27025. if (childScope) {
  27026. childScope.$destroy();
  27027. childScope = null;
  27028. }
  27029. if (block) {
  27030. previousElements = getBlockNodes(block.clone);
  27031. $animate.leave(previousElements).done(function(response) {
  27032. if (response !== false) previousElements = null;
  27033. });
  27034. block = null;
  27035. }
  27036. }
  27037. });
  27038. }
  27039. };
  27040. }];
  27041. /**
  27042. * @ngdoc directive
  27043. * @name ngInclude
  27044. * @restrict ECA
  27045. * @scope
  27046. * @priority -400
  27047. *
  27048. * @description
  27049. * Fetches, compiles and includes an external HTML fragment.
  27050. *
  27051. * By default, the template URL is restricted to the same domain and protocol as the
  27052. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  27053. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  27054. * you may either add them to your {@link ng.$sceDelegateProvider#trustedResourceUrlList trusted
  27055. * resource URL list} or {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to
  27056. * AngularJS's {@link ng.$sce Strict Contextual Escaping}.
  27057. *
  27058. * In addition, the browser's
  27059. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  27060. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  27061. * policy may further restrict whether the template is successfully loaded.
  27062. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  27063. * access on some browsers.
  27064. *
  27065. * @animations
  27066. * | Animation | Occurs |
  27067. * |----------------------------------|-------------------------------------|
  27068. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  27069. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  27070. *
  27071. * The enter and leave animation occur concurrently.
  27072. *
  27073. * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant,
  27074. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  27075. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  27076. * <div class="alert alert-warning">
  27077. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  27078. * a function with the name on the window element, which will usually throw a
  27079. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  27080. * different form that {@link guide/directive#normalization matches} `onload`.
  27081. * </div>
  27082. *
  27083. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  27084. * $anchorScroll} to scroll the viewport after the content is loaded.
  27085. *
  27086. * - If the attribute is not set, disable scrolling.
  27087. * - If the attribute is set without value, enable scrolling.
  27088. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  27089. *
  27090. * @example
  27091. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  27092. <file name="index.html">
  27093. <div ng-controller="ExampleController">
  27094. <select ng-model="template" ng-options="t.name for t in templates">
  27095. <option value="">(blank)</option>
  27096. </select>
  27097. url of the template: <code>{{template.url}}</code>
  27098. <hr/>
  27099. <div class="slide-animate-container">
  27100. <div class="slide-animate" ng-include="template.url"></div>
  27101. </div>
  27102. </div>
  27103. </file>
  27104. <file name="script.js">
  27105. angular.module('includeExample', ['ngAnimate'])
  27106. .controller('ExampleController', ['$scope', function($scope) {
  27107. $scope.templates =
  27108. [{ name: 'template1.html', url: 'template1.html'},
  27109. { name: 'template2.html', url: 'template2.html'}];
  27110. $scope.template = $scope.templates[0];
  27111. }]);
  27112. </file>
  27113. <file name="template1.html">
  27114. Content of template1.html
  27115. </file>
  27116. <file name="template2.html">
  27117. Content of template2.html
  27118. </file>
  27119. <file name="animations.css">
  27120. .slide-animate-container {
  27121. position:relative;
  27122. background:white;
  27123. border:1px solid black;
  27124. height:40px;
  27125. overflow:hidden;
  27126. }
  27127. .slide-animate {
  27128. padding:10px;
  27129. }
  27130. .slide-animate.ng-enter, .slide-animate.ng-leave {
  27131. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  27132. position:absolute;
  27133. top:0;
  27134. left:0;
  27135. right:0;
  27136. bottom:0;
  27137. display:block;
  27138. padding:10px;
  27139. }
  27140. .slide-animate.ng-enter {
  27141. top:-50px;
  27142. }
  27143. .slide-animate.ng-enter.ng-enter-active {
  27144. top:0;
  27145. }
  27146. .slide-animate.ng-leave {
  27147. top:0;
  27148. }
  27149. .slide-animate.ng-leave.ng-leave-active {
  27150. top:50px;
  27151. }
  27152. </file>
  27153. <file name="protractor.js" type="protractor">
  27154. var templateSelect = element(by.model('template'));
  27155. var includeElem = element(by.css('[ng-include]'));
  27156. it('should load template1.html', function() {
  27157. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  27158. });
  27159. it('should load template2.html', function() {
  27160. if (browser.params.browser === 'firefox') {
  27161. // Firefox can't handle using selects
  27162. // See https://github.com/angular/protractor/issues/480
  27163. return;
  27164. }
  27165. templateSelect.click();
  27166. templateSelect.all(by.css('option')).get(2).click();
  27167. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  27168. });
  27169. it('should change to blank', function() {
  27170. if (browser.params.browser === 'firefox') {
  27171. // Firefox can't handle using selects
  27172. return;
  27173. }
  27174. templateSelect.click();
  27175. templateSelect.all(by.css('option')).get(0).click();
  27176. expect(includeElem.isPresent()).toBe(false);
  27177. });
  27178. </file>
  27179. </example>
  27180. */
  27181. /**
  27182. * @ngdoc event
  27183. * @name ngInclude#$includeContentRequested
  27184. * @eventType emit on the scope ngInclude was declared in
  27185. * @description
  27186. * Emitted every time the ngInclude content is requested.
  27187. *
  27188. * @param {Object} angularEvent Synthetic event object.
  27189. * @param {String} src URL of content to load.
  27190. */
  27191. /**
  27192. * @ngdoc event
  27193. * @name ngInclude#$includeContentLoaded
  27194. * @eventType emit on the current ngInclude scope
  27195. * @description
  27196. * Emitted every time the ngInclude content is reloaded.
  27197. *
  27198. * @param {Object} angularEvent Synthetic event object.
  27199. * @param {String} src URL of content to load.
  27200. */
  27201. /**
  27202. * @ngdoc event
  27203. * @name ngInclude#$includeContentError
  27204. * @eventType emit on the scope ngInclude was declared in
  27205. * @description
  27206. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  27207. *
  27208. * @param {Object} angularEvent Synthetic event object.
  27209. * @param {String} src URL of content to load.
  27210. */
  27211. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  27212. function($templateRequest, $anchorScroll, $animate) {
  27213. return {
  27214. restrict: 'ECA',
  27215. priority: 400,
  27216. terminal: true,
  27217. transclude: 'element',
  27218. controller: angular.noop,
  27219. compile: function(element, attr) {
  27220. var srcExp = attr.ngInclude || attr.src,
  27221. onloadExp = attr.onload || '',
  27222. autoScrollExp = attr.autoscroll;
  27223. return function(scope, $element, $attr, ctrl, $transclude) {
  27224. var changeCounter = 0,
  27225. currentScope,
  27226. previousElement,
  27227. currentElement;
  27228. var cleanupLastIncludeContent = function() {
  27229. if (previousElement) {
  27230. previousElement.remove();
  27231. previousElement = null;
  27232. }
  27233. if (currentScope) {
  27234. currentScope.$destroy();
  27235. currentScope = null;
  27236. }
  27237. if (currentElement) {
  27238. $animate.leave(currentElement).done(function(response) {
  27239. if (response !== false) previousElement = null;
  27240. });
  27241. previousElement = currentElement;
  27242. currentElement = null;
  27243. }
  27244. };
  27245. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  27246. var afterAnimation = function(response) {
  27247. if (response !== false && isDefined(autoScrollExp) &&
  27248. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  27249. $anchorScroll();
  27250. }
  27251. };
  27252. var thisChangeId = ++changeCounter;
  27253. if (src) {
  27254. //set the 2nd param to true to ignore the template request error so that the inner
  27255. //contents and scope can be cleaned up.
  27256. $templateRequest(src, true).then(function(response) {
  27257. if (scope.$$destroyed) return;
  27258. if (thisChangeId !== changeCounter) return;
  27259. var newScope = scope.$new();
  27260. ctrl.template = response;
  27261. // Note: This will also link all children of ng-include that were contained in the original
  27262. // html. If that content contains controllers, ... they could pollute/change the scope.
  27263. // However, using ng-include on an element with additional content does not make sense...
  27264. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  27265. // function is called before linking the content, which would apply child
  27266. // directives to non existing elements.
  27267. var clone = $transclude(newScope, function(clone) {
  27268. cleanupLastIncludeContent();
  27269. $animate.enter(clone, null, $element).done(afterAnimation);
  27270. });
  27271. currentScope = newScope;
  27272. currentElement = clone;
  27273. currentScope.$emit('$includeContentLoaded', src);
  27274. scope.$eval(onloadExp);
  27275. }, function() {
  27276. if (scope.$$destroyed) return;
  27277. if (thisChangeId === changeCounter) {
  27278. cleanupLastIncludeContent();
  27279. scope.$emit('$includeContentError', src);
  27280. }
  27281. });
  27282. scope.$emit('$includeContentRequested', src);
  27283. } else {
  27284. cleanupLastIncludeContent();
  27285. ctrl.template = null;
  27286. }
  27287. });
  27288. };
  27289. }
  27290. };
  27291. }];
  27292. // This directive is called during the $transclude call of the first `ngInclude` directive.
  27293. // It will replace and compile the content of the element with the loaded template.
  27294. // We need this directive so that the element content is already filled when
  27295. // the link function of another directive on the same element as ngInclude
  27296. // is called.
  27297. var ngIncludeFillContentDirective = ['$compile',
  27298. function($compile) {
  27299. return {
  27300. restrict: 'ECA',
  27301. priority: -400,
  27302. require: 'ngInclude',
  27303. link: function(scope, $element, $attr, ctrl) {
  27304. if (toString.call($element[0]).match(/SVG/)) {
  27305. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  27306. // support innerHTML, so detect this here and try to generate the contents
  27307. // specially.
  27308. $element.empty();
  27309. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  27310. function namespaceAdaptedClone(clone) {
  27311. $element.append(clone);
  27312. }, {futureParentElement: $element});
  27313. return;
  27314. }
  27315. $element.html(ctrl.template);
  27316. $compile($element.contents())(scope);
  27317. }
  27318. };
  27319. }];
  27320. /**
  27321. * @ngdoc directive
  27322. * @name ngInit
  27323. * @restrict AC
  27324. * @priority 450
  27325. * @element ANY
  27326. *
  27327. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  27328. *
  27329. * @description
  27330. * The `ngInit` directive allows you to evaluate an expression in the
  27331. * current scope.
  27332. *
  27333. * <div class="alert alert-danger">
  27334. * This directive can be abused to add unnecessary amounts of logic into your templates.
  27335. * There are only a few appropriate uses of `ngInit`:
  27336. * <ul>
  27337. * <li>aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`},
  27338. * as seen in the demo below.</li>
  27339. * <li>initializing data during development, or for examples, as seen throughout these docs.</li>
  27340. * <li>injecting data via server side scripting.</li>
  27341. * </ul>
  27342. *
  27343. * Besides these few cases, you should use {@link guide/component Components} or
  27344. * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope.
  27345. * </div>
  27346. *
  27347. * <div class="alert alert-warning">
  27348. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  27349. * sure you have parentheses to ensure correct operator precedence:
  27350. * <pre class="prettyprint">
  27351. * `<div ng-init="test1 = ($index | toString)"></div>`
  27352. * </pre>
  27353. * </div>
  27354. *
  27355. * @example
  27356. <example module="initExample" name="ng-init">
  27357. <file name="index.html">
  27358. <script>
  27359. angular.module('initExample', [])
  27360. .controller('ExampleController', ['$scope', function($scope) {
  27361. $scope.list = [['a', 'b'], ['c', 'd']];
  27362. }]);
  27363. </script>
  27364. <div ng-controller="ExampleController">
  27365. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  27366. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  27367. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  27368. </div>
  27369. </div>
  27370. </div>
  27371. </file>
  27372. <file name="protractor.js" type="protractor">
  27373. it('should alias index positions', function() {
  27374. var elements = element.all(by.css('.example-init'));
  27375. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  27376. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  27377. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  27378. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  27379. });
  27380. </file>
  27381. </example>
  27382. */
  27383. var ngInitDirective = ngDirective({
  27384. priority: 450,
  27385. compile: function() {
  27386. return {
  27387. pre: function(scope, element, attrs) {
  27388. scope.$eval(attrs.ngInit);
  27389. }
  27390. };
  27391. }
  27392. });
  27393. /**
  27394. * @ngdoc directive
  27395. * @name ngList
  27396. * @restrict A
  27397. * @priority 100
  27398. *
  27399. * @param {string=} ngList optional delimiter that should be used to split the value.
  27400. *
  27401. * @description
  27402. * Text input that converts between a delimited string and an array of strings. The default
  27403. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  27404. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  27405. *
  27406. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  27407. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  27408. * list item is respected. This implies that the user of the directive is responsible for
  27409. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  27410. * tab or newline character.
  27411. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  27412. * when joining the list items back together) and whitespace around each list item is stripped
  27413. * before it is added to the model.
  27414. *
  27415. * @example
  27416. * ### Validation
  27417. *
  27418. * <example name="ngList-directive" module="listExample">
  27419. * <file name="app.js">
  27420. * angular.module('listExample', [])
  27421. * .controller('ExampleController', ['$scope', function($scope) {
  27422. * $scope.names = ['morpheus', 'neo', 'trinity'];
  27423. * }]);
  27424. * </file>
  27425. * <file name="index.html">
  27426. * <form name="myForm" ng-controller="ExampleController">
  27427. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  27428. * <span role="alert">
  27429. * <span class="error" ng-show="myForm.namesInput.$error.required">
  27430. * Required!</span>
  27431. * </span>
  27432. * <br>
  27433. * <tt>names = {{names}}</tt><br/>
  27434. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  27435. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  27436. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  27437. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  27438. * </form>
  27439. * </file>
  27440. * <file name="protractor.js" type="protractor">
  27441. * var listInput = element(by.model('names'));
  27442. * var names = element(by.exactBinding('names'));
  27443. * var valid = element(by.binding('myForm.namesInput.$valid'));
  27444. * var error = element(by.css('span.error'));
  27445. *
  27446. * it('should initialize to model', function() {
  27447. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  27448. * expect(valid.getText()).toContain('true');
  27449. * expect(error.getCssValue('display')).toBe('none');
  27450. * });
  27451. *
  27452. * it('should be invalid if empty', function() {
  27453. * listInput.clear();
  27454. * listInput.sendKeys('');
  27455. *
  27456. * expect(names.getText()).toContain('');
  27457. * expect(valid.getText()).toContain('false');
  27458. * expect(error.getCssValue('display')).not.toBe('none');
  27459. * });
  27460. * </file>
  27461. * </example>
  27462. *
  27463. * @example
  27464. * ### Splitting on newline
  27465. *
  27466. * <example name="ngList-directive-newlines">
  27467. * <file name="index.html">
  27468. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  27469. * <pre>{{ list | json }}</pre>
  27470. * </file>
  27471. * <file name="protractor.js" type="protractor">
  27472. * it("should split the text by newlines", function() {
  27473. * var listInput = element(by.model('list'));
  27474. * var output = element(by.binding('list | json'));
  27475. * listInput.sendKeys('abc\ndef\nghi');
  27476. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  27477. * });
  27478. * </file>
  27479. * </example>
  27480. *
  27481. */
  27482. var ngListDirective = function() {
  27483. return {
  27484. restrict: 'A',
  27485. priority: 100,
  27486. require: 'ngModel',
  27487. link: function(scope, element, attr, ctrl) {
  27488. var ngList = attr.ngList || ', ';
  27489. var trimValues = attr.ngTrim !== 'false';
  27490. var separator = trimValues ? trim(ngList) : ngList;
  27491. var parse = function(viewValue) {
  27492. // If the viewValue is invalid (say required but empty) it will be `undefined`
  27493. if (isUndefined(viewValue)) return;
  27494. var list = [];
  27495. if (viewValue) {
  27496. forEach(viewValue.split(separator), function(value) {
  27497. if (value) list.push(trimValues ? trim(value) : value);
  27498. });
  27499. }
  27500. return list;
  27501. };
  27502. ctrl.$parsers.push(parse);
  27503. ctrl.$formatters.push(function(value) {
  27504. if (isArray(value)) {
  27505. return value.join(ngList);
  27506. }
  27507. return undefined;
  27508. });
  27509. // Override the standard $isEmpty because an empty array means the input is empty.
  27510. ctrl.$isEmpty = function(value) {
  27511. return !value || !value.length;
  27512. };
  27513. }
  27514. };
  27515. };
  27516. /* global VALID_CLASS: true,
  27517. INVALID_CLASS: true,
  27518. PRISTINE_CLASS: true,
  27519. DIRTY_CLASS: true,
  27520. UNTOUCHED_CLASS: true,
  27521. TOUCHED_CLASS: true,
  27522. PENDING_CLASS: true,
  27523. addSetValidityMethod: true,
  27524. setupValidity: true,
  27525. defaultModelOptions: false
  27526. */
  27527. var VALID_CLASS = 'ng-valid',
  27528. INVALID_CLASS = 'ng-invalid',
  27529. PRISTINE_CLASS = 'ng-pristine',
  27530. DIRTY_CLASS = 'ng-dirty',
  27531. UNTOUCHED_CLASS = 'ng-untouched',
  27532. TOUCHED_CLASS = 'ng-touched',
  27533. EMPTY_CLASS = 'ng-empty',
  27534. NOT_EMPTY_CLASS = 'ng-not-empty';
  27535. var ngModelMinErr = minErr('ngModel');
  27536. /**
  27537. * @ngdoc type
  27538. * @name ngModel.NgModelController
  27539. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  27540. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  27541. * is set.
  27542. *
  27543. * @property {*} $modelValue The value in the model that the control is bound to.
  27544. *
  27545. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  27546. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  27547. `$viewValue`} from the DOM, usually via user input.
  27548. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  27549. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  27550. The functions are called in array order, each passing
  27551. its return value through to the next. The last return value is forwarded to the
  27552. {@link ngModel.NgModelController#$validators `$validators`} collection.
  27553. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  27554. `$viewValue`}.
  27555. Returning `undefined` from a parser means a parse error occurred. In that case,
  27556. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  27557. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  27558. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  27559. This simple example shows a parser that would convert text input value to lowercase:
  27560. * ```js
  27561. * function parse(value) {
  27562. * if (value) {
  27563. * return value.toLowerCase();
  27564. * }
  27565. * }
  27566. * ngModelController.$parsers.push(parse);
  27567. * ```
  27568. *
  27569. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  27570. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  27571. value of the control is changed by user interaction.
  27572. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  27573. `$modelValue`} for display in the control.
  27574. The functions are called in reverse array order, each passing the value through to the
  27575. next. The last return value is used as the actual DOM value.
  27576. This simple example shows a formatter that would convert the model value to uppercase:
  27577. * ```js
  27578. * function format(value) {
  27579. * if (value) {
  27580. * return value.toUpperCase();
  27581. * }
  27582. * }
  27583. * ngModel.$formatters.push(format);
  27584. * ```
  27585. *
  27586. * @property {Object.<string, function>} $validators A collection of validators that are applied
  27587. * whenever the model value changes. The key value within the object refers to the name of the
  27588. * validator while the function refers to the validation operation. The validation operation is
  27589. * provided with the model value as an argument and must return a true or false value depending
  27590. * on the response of that validation.
  27591. *
  27592. * ```js
  27593. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  27594. * var value = modelValue || viewValue;
  27595. * return /[0-9]+/.test(value) &&
  27596. * /[a-z]+/.test(value) &&
  27597. * /[A-Z]+/.test(value) &&
  27598. * /\W+/.test(value);
  27599. * };
  27600. * ```
  27601. *
  27602. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  27603. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  27604. * is expected to return a promise when it is run during the model validation process. Once the promise
  27605. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  27606. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  27607. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  27608. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  27609. * will only run once all synchronous validators have passed.
  27610. *
  27611. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  27612. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  27613. *
  27614. * ```js
  27615. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  27616. * var value = modelValue || viewValue;
  27617. *
  27618. * // Lookup user by username
  27619. * return $http.get('/api/users/' + value).
  27620. * then(function resolved() {
  27621. * //username exists, this means validation fails
  27622. * return $q.reject('exists');
  27623. * }, function rejected() {
  27624. * //username does not exist, therefore this validation passes
  27625. * return true;
  27626. * });
  27627. * };
  27628. * ```
  27629. *
  27630. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever
  27631. * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change
  27632. * to {@link ngModel.NgModelController#$modelValue `$modelValue`}.
  27633. * It is called with no arguments, and its return value is ignored.
  27634. * This can be used in place of additional $watches against the model value.
  27635. *
  27636. * @property {Object} $error An object hash with all failing validator ids as keys.
  27637. * @property {Object} $pending An object hash with all pending validator ids as keys.
  27638. *
  27639. * @property {boolean} $untouched True if control has not lost focus yet.
  27640. * @property {boolean} $touched True if control has lost focus.
  27641. * @property {boolean} $pristine True if user has not interacted with the control yet.
  27642. * @property {boolean} $dirty True if user has already interacted with the control.
  27643. * @property {boolean} $valid True if there is no error.
  27644. * @property {boolean} $invalid True if at least one error on the control.
  27645. * @property {string} $name The name attribute of the control.
  27646. *
  27647. * @description
  27648. *
  27649. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  27650. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  27651. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  27652. * listening to DOM events.
  27653. * Such DOM related logic should be provided by other directives which make use of
  27654. * `NgModelController` for data-binding to control elements.
  27655. * AngularJS provides this DOM logic for most {@link input `input`} elements.
  27656. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  27657. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  27658. *
  27659. * @example
  27660. * ### Custom Control Example
  27661. * This example shows how to use `NgModelController` with a custom control to achieve
  27662. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  27663. * collaborate together to achieve the desired result.
  27664. *
  27665. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  27666. * contents be edited in place by the user.
  27667. *
  27668. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  27669. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  27670. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  27671. * that content using the `$sce` service.
  27672. *
  27673. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  27674. <file name="style.css">
  27675. [contenteditable] {
  27676. border: 1px solid black;
  27677. background-color: white;
  27678. min-height: 20px;
  27679. }
  27680. .ng-invalid {
  27681. border: 1px solid red;
  27682. }
  27683. </file>
  27684. <file name="script.js">
  27685. angular.module('customControl', ['ngSanitize']).
  27686. directive('contenteditable', ['$sce', function($sce) {
  27687. return {
  27688. restrict: 'A', // only activate on element attribute
  27689. require: '?ngModel', // get a hold of NgModelController
  27690. link: function(scope, element, attrs, ngModel) {
  27691. if (!ngModel) return; // do nothing if no ng-model
  27692. // Specify how UI should be updated
  27693. ngModel.$render = function() {
  27694. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  27695. };
  27696. // Listen for change events to enable binding
  27697. element.on('blur keyup change', function() {
  27698. scope.$evalAsync(read);
  27699. });
  27700. read(); // initialize
  27701. // Write data to the model
  27702. function read() {
  27703. var html = element.html();
  27704. // When we clear the content editable the browser leaves a <br> behind
  27705. // If strip-br attribute is provided then we strip this out
  27706. if (attrs.stripBr && html === '<br>') {
  27707. html = '';
  27708. }
  27709. ngModel.$setViewValue(html);
  27710. }
  27711. }
  27712. };
  27713. }]);
  27714. </file>
  27715. <file name="index.html">
  27716. <form name="myForm">
  27717. <div contenteditable
  27718. name="myWidget" ng-model="userContent"
  27719. strip-br="true"
  27720. required>Change me!</div>
  27721. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  27722. <hr>
  27723. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  27724. </form>
  27725. </file>
  27726. <file name="protractor.js" type="protractor">
  27727. it('should data-bind and become invalid', function() {
  27728. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  27729. // SafariDriver can't handle contenteditable
  27730. // and Firefox driver can't clear contenteditables very well
  27731. return;
  27732. }
  27733. var contentEditable = element(by.css('[contenteditable]'));
  27734. var content = 'Change me!';
  27735. expect(contentEditable.getText()).toEqual(content);
  27736. contentEditable.clear();
  27737. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  27738. expect(contentEditable.getText()).toEqual('');
  27739. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  27740. });
  27741. </file>
  27742. * </example>
  27743. *
  27744. *
  27745. */
  27746. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  27747. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  27748. this.$viewValue = Number.NaN;
  27749. this.$modelValue = Number.NaN;
  27750. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  27751. this.$validators = {};
  27752. this.$asyncValidators = {};
  27753. this.$parsers = [];
  27754. this.$formatters = [];
  27755. this.$viewChangeListeners = [];
  27756. this.$untouched = true;
  27757. this.$touched = false;
  27758. this.$pristine = true;
  27759. this.$dirty = false;
  27760. this.$valid = true;
  27761. this.$invalid = false;
  27762. this.$error = {}; // keep invalid keys here
  27763. this.$$success = {}; // keep valid keys here
  27764. this.$pending = undefined; // keep pending keys here
  27765. this.$name = $interpolate($attr.name || '', false)($scope);
  27766. this.$$parentForm = nullFormCtrl;
  27767. this.$options = defaultModelOptions;
  27768. this.$$updateEvents = '';
  27769. // Attach the correct context to the event handler function for updateOn
  27770. this.$$updateEventHandler = this.$$updateEventHandler.bind(this);
  27771. this.$$parsedNgModel = $parse($attr.ngModel);
  27772. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  27773. this.$$ngModelGet = this.$$parsedNgModel;
  27774. this.$$ngModelSet = this.$$parsedNgModelAssign;
  27775. this.$$pendingDebounce = null;
  27776. this.$$parserValid = undefined;
  27777. this.$$parserName = 'parse';
  27778. this.$$currentValidationRunId = 0;
  27779. this.$$scope = $scope;
  27780. this.$$rootScope = $scope.$root;
  27781. this.$$attr = $attr;
  27782. this.$$element = $element;
  27783. this.$$animate = $animate;
  27784. this.$$timeout = $timeout;
  27785. this.$$parse = $parse;
  27786. this.$$q = $q;
  27787. this.$$exceptionHandler = $exceptionHandler;
  27788. setupValidity(this);
  27789. setupModelWatcher(this);
  27790. }
  27791. NgModelController.prototype = {
  27792. $$initGetterSetters: function() {
  27793. if (this.$options.getOption('getterSetter')) {
  27794. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  27795. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  27796. this.$$ngModelGet = function($scope) {
  27797. var modelValue = this.$$parsedNgModel($scope);
  27798. if (isFunction(modelValue)) {
  27799. modelValue = invokeModelGetter($scope);
  27800. }
  27801. return modelValue;
  27802. };
  27803. this.$$ngModelSet = function($scope, newValue) {
  27804. if (isFunction(this.$$parsedNgModel($scope))) {
  27805. invokeModelSetter($scope, {$$$p: newValue});
  27806. } else {
  27807. this.$$parsedNgModelAssign($scope, newValue);
  27808. }
  27809. };
  27810. } else if (!this.$$parsedNgModel.assign) {
  27811. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  27812. this.$$attr.ngModel, startingTag(this.$$element));
  27813. }
  27814. },
  27815. /**
  27816. * @ngdoc method
  27817. * @name ngModel.NgModelController#$render
  27818. *
  27819. * @description
  27820. * Called when the view needs to be updated. It is expected that the user of the ng-model
  27821. * directive will implement this method.
  27822. *
  27823. * The `$render()` method is invoked in the following situations:
  27824. *
  27825. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  27826. * committed value then `$render()` is called to update the input control.
  27827. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  27828. * the `$viewValue` are different from last time.
  27829. *
  27830. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  27831. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  27832. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  27833. * invoked if you only change a property on the objects.
  27834. */
  27835. $render: noop,
  27836. /**
  27837. * @ngdoc method
  27838. * @name ngModel.NgModelController#$isEmpty
  27839. *
  27840. * @description
  27841. * This is called when we need to determine if the value of an input is empty.
  27842. *
  27843. * For instance, the required directive does this to work out if the input has data or not.
  27844. *
  27845. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  27846. *
  27847. * You can override this for input directives whose concept of being empty is different from the
  27848. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  27849. * implies empty.
  27850. *
  27851. * @param {*} value The value of the input to check for emptiness.
  27852. * @returns {boolean} True if `value` is "empty".
  27853. */
  27854. $isEmpty: function(value) {
  27855. // eslint-disable-next-line no-self-compare
  27856. return isUndefined(value) || value === '' || value === null || value !== value;
  27857. },
  27858. $$updateEmptyClasses: function(value) {
  27859. if (this.$isEmpty(value)) {
  27860. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  27861. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  27862. } else {
  27863. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  27864. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  27865. }
  27866. },
  27867. /**
  27868. * @ngdoc method
  27869. * @name ngModel.NgModelController#$setPristine
  27870. *
  27871. * @description
  27872. * Sets the control to its pristine state.
  27873. *
  27874. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  27875. * state (`ng-pristine` class). A model is considered to be pristine when the control
  27876. * has not been changed from when first compiled.
  27877. */
  27878. $setPristine: function() {
  27879. this.$dirty = false;
  27880. this.$pristine = true;
  27881. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  27882. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  27883. },
  27884. /**
  27885. * @ngdoc method
  27886. * @name ngModel.NgModelController#$setDirty
  27887. *
  27888. * @description
  27889. * Sets the control to its dirty state.
  27890. *
  27891. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  27892. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  27893. * from when first compiled.
  27894. */
  27895. $setDirty: function() {
  27896. this.$dirty = true;
  27897. this.$pristine = false;
  27898. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  27899. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  27900. this.$$parentForm.$setDirty();
  27901. },
  27902. /**
  27903. * @ngdoc method
  27904. * @name ngModel.NgModelController#$setUntouched
  27905. *
  27906. * @description
  27907. * Sets the control to its untouched state.
  27908. *
  27909. * This method can be called to remove the `ng-touched` class and set the control to its
  27910. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  27911. * by default, however this function can be used to restore that state if the model has
  27912. * already been touched by the user.
  27913. */
  27914. $setUntouched: function() {
  27915. this.$touched = false;
  27916. this.$untouched = true;
  27917. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  27918. },
  27919. /**
  27920. * @ngdoc method
  27921. * @name ngModel.NgModelController#$setTouched
  27922. *
  27923. * @description
  27924. * Sets the control to its touched state.
  27925. *
  27926. * This method can be called to remove the `ng-untouched` class and set the control to its
  27927. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  27928. * first focused the control element and then shifted focus away from the control (blur event).
  27929. */
  27930. $setTouched: function() {
  27931. this.$touched = true;
  27932. this.$untouched = false;
  27933. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  27934. },
  27935. /**
  27936. * @ngdoc method
  27937. * @name ngModel.NgModelController#$rollbackViewValue
  27938. *
  27939. * @description
  27940. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  27941. * which may be caused by a pending debounced event or because the input is waiting for some
  27942. * future event.
  27943. *
  27944. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  27945. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  27946. * sync with the ngModel's `$modelValue`.
  27947. *
  27948. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  27949. * and reset the input to the last committed view value.
  27950. *
  27951. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  27952. * programmatically before these debounced/future events have resolved/occurred, because AngularJS's
  27953. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  27954. *
  27955. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  27956. * input which may have such events pending. This is important in order to make sure that the
  27957. * input field will be updated with the new model value and any pending operations are cancelled.
  27958. *
  27959. * @example
  27960. * <example name="ng-model-cancel-update" module="cancel-update-example">
  27961. * <file name="app.js">
  27962. * angular.module('cancel-update-example', [])
  27963. *
  27964. * .controller('CancelUpdateController', ['$scope', function($scope) {
  27965. * $scope.model = {value1: '', value2: ''};
  27966. *
  27967. * $scope.setEmpty = function(e, value, rollback) {
  27968. * if (e.keyCode === 27) {
  27969. * e.preventDefault();
  27970. * if (rollback) {
  27971. * $scope.myForm[value].$rollbackViewValue();
  27972. * }
  27973. * $scope.model[value] = '';
  27974. * }
  27975. * };
  27976. * }]);
  27977. * </file>
  27978. * <file name="index.html">
  27979. * <div ng-controller="CancelUpdateController">
  27980. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  27981. * empty them. Follow these steps and observe the difference:</p>
  27982. * <ol>
  27983. * <li>Type something in the input. You will see that the model is not yet updated</li>
  27984. * <li>Press the Escape key.
  27985. * <ol>
  27986. * <li> In the first example, nothing happens, because the model is already '', and no
  27987. * update is detected. If you blur the input, the model will be set to the current view.
  27988. * </li>
  27989. * <li> In the second example, the pending update is cancelled, and the input is set back
  27990. * to the last committed view value (''). Blurring the input does nothing.
  27991. * </li>
  27992. * </ol>
  27993. * </li>
  27994. * </ol>
  27995. *
  27996. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  27997. * <div>
  27998. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  27999. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  28000. * ng-keydown="setEmpty($event, 'value1')">
  28001. * value1: "{{ model.value1 }}"
  28002. * </div>
  28003. *
  28004. * <div>
  28005. * <p id="inputDescription2">With $rollbackViewValue():</p>
  28006. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  28007. * ng-keydown="setEmpty($event, 'value2', true)">
  28008. * value2: "{{ model.value2 }}"
  28009. * </div>
  28010. * </form>
  28011. * </div>
  28012. * </file>
  28013. <file name="style.css">
  28014. div {
  28015. display: table-cell;
  28016. }
  28017. div:nth-child(1) {
  28018. padding-right: 30px;
  28019. }
  28020. </file>
  28021. * </example>
  28022. */
  28023. $rollbackViewValue: function() {
  28024. this.$$timeout.cancel(this.$$pendingDebounce);
  28025. this.$viewValue = this.$$lastCommittedViewValue;
  28026. this.$render();
  28027. },
  28028. /**
  28029. * @ngdoc method
  28030. * @name ngModel.NgModelController#$validate
  28031. *
  28032. * @description
  28033. * Runs each of the registered validators (first synchronous validators and then
  28034. * asynchronous validators).
  28035. * If the validity changes to invalid, the model will be set to `undefined`,
  28036. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  28037. * If the validity changes to valid, it will set the model to the last available valid
  28038. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  28039. */
  28040. $validate: function() {
  28041. // ignore $validate before model is initialized
  28042. if (isNumberNaN(this.$modelValue)) {
  28043. return;
  28044. }
  28045. var viewValue = this.$$lastCommittedViewValue;
  28046. // Note: we use the $$rawModelValue as $modelValue might have been
  28047. // set to undefined during a view -> model update that found validation
  28048. // errors. We can't parse the view here, since that could change
  28049. // the model although neither viewValue nor the model on the scope changed
  28050. var modelValue = this.$$rawModelValue;
  28051. var prevValid = this.$valid;
  28052. var prevModelValue = this.$modelValue;
  28053. var allowInvalid = this.$options.getOption('allowInvalid');
  28054. var that = this;
  28055. this.$$runValidators(modelValue, viewValue, function(allValid) {
  28056. // If there was no change in validity, don't update the model
  28057. // This prevents changing an invalid modelValue to undefined
  28058. if (!allowInvalid && prevValid !== allValid) {
  28059. // Note: Don't check this.$valid here, as we could have
  28060. // external validators (e.g. calculated on the server),
  28061. // that just call $setValidity and need the model value
  28062. // to calculate their validity.
  28063. that.$modelValue = allValid ? modelValue : undefined;
  28064. if (that.$modelValue !== prevModelValue) {
  28065. that.$$writeModelToScope();
  28066. }
  28067. }
  28068. });
  28069. },
  28070. $$runValidators: function(modelValue, viewValue, doneCallback) {
  28071. this.$$currentValidationRunId++;
  28072. var localValidationRunId = this.$$currentValidationRunId;
  28073. var that = this;
  28074. // check parser error
  28075. if (!processParseErrors()) {
  28076. validationDone(false);
  28077. return;
  28078. }
  28079. if (!processSyncValidators()) {
  28080. validationDone(false);
  28081. return;
  28082. }
  28083. processAsyncValidators();
  28084. function processParseErrors() {
  28085. var errorKey = that.$$parserName;
  28086. if (isUndefined(that.$$parserValid)) {
  28087. setValidity(errorKey, null);
  28088. } else {
  28089. if (!that.$$parserValid) {
  28090. forEach(that.$validators, function(v, name) {
  28091. setValidity(name, null);
  28092. });
  28093. forEach(that.$asyncValidators, function(v, name) {
  28094. setValidity(name, null);
  28095. });
  28096. }
  28097. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  28098. setValidity(errorKey, that.$$parserValid);
  28099. return that.$$parserValid;
  28100. }
  28101. return true;
  28102. }
  28103. function processSyncValidators() {
  28104. var syncValidatorsValid = true;
  28105. forEach(that.$validators, function(validator, name) {
  28106. var result = Boolean(validator(modelValue, viewValue));
  28107. syncValidatorsValid = syncValidatorsValid && result;
  28108. setValidity(name, result);
  28109. });
  28110. if (!syncValidatorsValid) {
  28111. forEach(that.$asyncValidators, function(v, name) {
  28112. setValidity(name, null);
  28113. });
  28114. return false;
  28115. }
  28116. return true;
  28117. }
  28118. function processAsyncValidators() {
  28119. var validatorPromises = [];
  28120. var allValid = true;
  28121. forEach(that.$asyncValidators, function(validator, name) {
  28122. var promise = validator(modelValue, viewValue);
  28123. if (!isPromiseLike(promise)) {
  28124. throw ngModelMinErr('nopromise',
  28125. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  28126. }
  28127. setValidity(name, undefined);
  28128. validatorPromises.push(promise.then(function() {
  28129. setValidity(name, true);
  28130. }, function() {
  28131. allValid = false;
  28132. setValidity(name, false);
  28133. }));
  28134. });
  28135. if (!validatorPromises.length) {
  28136. validationDone(true);
  28137. } else {
  28138. that.$$q.all(validatorPromises).then(function() {
  28139. validationDone(allValid);
  28140. }, noop);
  28141. }
  28142. }
  28143. function setValidity(name, isValid) {
  28144. if (localValidationRunId === that.$$currentValidationRunId) {
  28145. that.$setValidity(name, isValid);
  28146. }
  28147. }
  28148. function validationDone(allValid) {
  28149. if (localValidationRunId === that.$$currentValidationRunId) {
  28150. doneCallback(allValid);
  28151. }
  28152. }
  28153. },
  28154. /**
  28155. * @ngdoc method
  28156. * @name ngModel.NgModelController#$commitViewValue
  28157. *
  28158. * @description
  28159. * Commit a pending update to the `$modelValue`.
  28160. *
  28161. * Updates may be pending by a debounced event or because the input is waiting for a some future
  28162. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  28163. * usually handles calling this in response to input events.
  28164. */
  28165. $commitViewValue: function() {
  28166. var viewValue = this.$viewValue;
  28167. this.$$timeout.cancel(this.$$pendingDebounce);
  28168. // If the view value has not changed then we should just exit, except in the case where there is
  28169. // a native validator on the element. In this case the validation state may have changed even though
  28170. // the viewValue has stayed empty.
  28171. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  28172. return;
  28173. }
  28174. this.$$updateEmptyClasses(viewValue);
  28175. this.$$lastCommittedViewValue = viewValue;
  28176. // change to dirty
  28177. if (this.$pristine) {
  28178. this.$setDirty();
  28179. }
  28180. this.$$parseAndValidate();
  28181. },
  28182. $$parseAndValidate: function() {
  28183. var viewValue = this.$$lastCommittedViewValue;
  28184. var modelValue = viewValue;
  28185. var that = this;
  28186. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  28187. // Reset any previous parse error
  28188. this.$setValidity(this.$$parserName, null);
  28189. this.$$parserName = 'parse';
  28190. if (this.$$parserValid) {
  28191. for (var i = 0; i < this.$parsers.length; i++) {
  28192. modelValue = this.$parsers[i](modelValue);
  28193. if (isUndefined(modelValue)) {
  28194. this.$$parserValid = false;
  28195. break;
  28196. }
  28197. }
  28198. }
  28199. if (isNumberNaN(this.$modelValue)) {
  28200. // this.$modelValue has not been touched yet...
  28201. this.$modelValue = this.$$ngModelGet(this.$$scope);
  28202. }
  28203. var prevModelValue = this.$modelValue;
  28204. var allowInvalid = this.$options.getOption('allowInvalid');
  28205. this.$$rawModelValue = modelValue;
  28206. if (allowInvalid) {
  28207. this.$modelValue = modelValue;
  28208. writeToModelIfNeeded();
  28209. }
  28210. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  28211. // This can happen if e.g. $setViewValue is called from inside a parser
  28212. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  28213. if (!allowInvalid) {
  28214. // Note: Don't check this.$valid here, as we could have
  28215. // external validators (e.g. calculated on the server),
  28216. // that just call $setValidity and need the model value
  28217. // to calculate their validity.
  28218. that.$modelValue = allValid ? modelValue : undefined;
  28219. writeToModelIfNeeded();
  28220. }
  28221. });
  28222. function writeToModelIfNeeded() {
  28223. if (that.$modelValue !== prevModelValue) {
  28224. that.$$writeModelToScope();
  28225. }
  28226. }
  28227. },
  28228. $$writeModelToScope: function() {
  28229. this.$$ngModelSet(this.$$scope, this.$modelValue);
  28230. forEach(this.$viewChangeListeners, function(listener) {
  28231. try {
  28232. listener();
  28233. } catch (e) {
  28234. // eslint-disable-next-line no-invalid-this
  28235. this.$$exceptionHandler(e);
  28236. }
  28237. }, this);
  28238. },
  28239. /**
  28240. * @ngdoc method
  28241. * @name ngModel.NgModelController#$setViewValue
  28242. *
  28243. * @description
  28244. * Update the view value.
  28245. *
  28246. * This method should be called when a control wants to change the view value; typically,
  28247. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  28248. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  28249. * calls it when an option is selected.
  28250. *
  28251. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  28252. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  28253. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  28254. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  28255. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  28256. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  28257. *
  28258. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  28259. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  28260. * `updateOn` events is triggered on the DOM element.
  28261. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  28262. * directive is used with a custom debounce for this particular event.
  28263. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  28264. * is specified, once the timer runs out.
  28265. *
  28266. * When used with standard inputs, the view value will always be a string (which is in some cases
  28267. * parsed into another type, such as a `Date` object for `input[date]`.)
  28268. * However, custom controls might also pass objects to this method. In this case, we should make
  28269. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  28270. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  28271. * the property of the object then ngModel will not realize that the object has changed and
  28272. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  28273. * not change properties of the copy once it has been passed to `$setViewValue`.
  28274. * Otherwise you may cause the model value on the scope to change incorrectly.
  28275. *
  28276. * <div class="alert alert-info">
  28277. * In any case, the value passed to the method should always reflect the current value
  28278. * of the control. For example, if you are calling `$setViewValue` for an input element,
  28279. * you should pass the input DOM value. Otherwise, the control and the scope model become
  28280. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  28281. * the control's DOM value in any way. If we want to change the control's DOM value
  28282. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  28283. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  28284. * to update the DOM, and finally call `$validate` on it.
  28285. * </div>
  28286. *
  28287. * @param {*} value value from the view.
  28288. * @param {string} trigger Event that triggered the update.
  28289. */
  28290. $setViewValue: function(value, trigger) {
  28291. this.$viewValue = value;
  28292. if (this.$options.getOption('updateOnDefault')) {
  28293. this.$$debounceViewValueCommit(trigger);
  28294. }
  28295. },
  28296. $$debounceViewValueCommit: function(trigger) {
  28297. var debounceDelay = this.$options.getOption('debounce');
  28298. if (isNumber(debounceDelay[trigger])) {
  28299. debounceDelay = debounceDelay[trigger];
  28300. } else if (isNumber(debounceDelay['default']) &&
  28301. this.$options.getOption('updateOn').indexOf(trigger) === -1
  28302. ) {
  28303. debounceDelay = debounceDelay['default'];
  28304. } else if (isNumber(debounceDelay['*'])) {
  28305. debounceDelay = debounceDelay['*'];
  28306. }
  28307. this.$$timeout.cancel(this.$$pendingDebounce);
  28308. var that = this;
  28309. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  28310. this.$$pendingDebounce = this.$$timeout(function() {
  28311. that.$commitViewValue();
  28312. }, debounceDelay);
  28313. } else if (this.$$rootScope.$$phase) {
  28314. this.$commitViewValue();
  28315. } else {
  28316. this.$$scope.$apply(function() {
  28317. that.$commitViewValue();
  28318. });
  28319. }
  28320. },
  28321. /**
  28322. * @ngdoc method
  28323. *
  28324. * @name ngModel.NgModelController#$overrideModelOptions
  28325. *
  28326. * @description
  28327. *
  28328. * Override the current model options settings programmatically.
  28329. *
  28330. * The previous `ModelOptions` value will not be modified. Instead, a
  28331. * new `ModelOptions` object will inherit from the previous one overriding
  28332. * or inheriting settings that are defined in the given parameter.
  28333. *
  28334. * See {@link ngModelOptions} for information about what options can be specified
  28335. * and how model option inheritance works.
  28336. *
  28337. * <div class="alert alert-warning">
  28338. * **Note:** this function only affects the options set on the `ngModelController`,
  28339. * and not the options on the {@link ngModelOptions} directive from which they might have been
  28340. * obtained initially.
  28341. * </div>
  28342. *
  28343. * <div class="alert alert-danger">
  28344. * **Note:** it is not possible to override the `getterSetter` option.
  28345. * </div>
  28346. *
  28347. * @param {Object} options a hash of settings to override the previous options
  28348. *
  28349. */
  28350. $overrideModelOptions: function(options) {
  28351. this.$options = this.$options.createChild(options);
  28352. this.$$setUpdateOnEvents();
  28353. },
  28354. /**
  28355. * @ngdoc method
  28356. *
  28357. * @name ngModel.NgModelController#$processModelValue
  28358. * @description
  28359. *
  28360. * Runs the model -> view pipeline on the current
  28361. * {@link ngModel.NgModelController#$modelValue $modelValue}.
  28362. *
  28363. * The following actions are performed by this method:
  28364. *
  28365. * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters}
  28366. * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue}
  28367. * - the `ng-empty` or `ng-not-empty` class is set on the element
  28368. * - if the `$viewValue` has changed:
  28369. * - {@link ngModel.NgModelController#$render $render} is called on the control
  28370. * - the {@link ngModel.NgModelController#$validators $validators} are run and
  28371. * the validation status is set.
  28372. *
  28373. * This method is called by ngModel internally when the bound scope value changes.
  28374. * Application developers usually do not have to call this function themselves.
  28375. *
  28376. * This function can be used when the `$viewValue` or the rendered DOM value are not correctly
  28377. * formatted and the `$modelValue` must be run through the `$formatters` again.
  28378. *
  28379. * @example
  28380. * Consider a text input with an autocomplete list (for fruit), where the items are
  28381. * objects with a name and an id.
  28382. * A user enters `ap` and then selects `Apricot` from the list.
  28383. * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`,
  28384. * but the rendered value will still be `ap`.
  28385. * The widget can then call `ctrl.$processModelValue()` to run the model -> view
  28386. * pipeline again, which formats the object to the string `Apricot`,
  28387. * then updates the `$viewValue`, and finally renders it in the DOM.
  28388. *
  28389. * <example module="inputExample" name="ng-model-process">
  28390. <file name="index.html">
  28391. <div ng-controller="inputController" style="display: flex;">
  28392. <div style="margin-right: 30px;">
  28393. Search Fruit:
  28394. <basic-autocomplete items="items" on-select="selectedFruit = item"></basic-autocomplete>
  28395. </div>
  28396. <div>
  28397. Model:<br>
  28398. <pre>{{selectedFruit | json}}</pre>
  28399. </div>
  28400. </div>
  28401. </file>
  28402. <file name="app.js">
  28403. angular.module('inputExample', [])
  28404. .controller('inputController', function($scope) {
  28405. $scope.items = [
  28406. {name: 'Apricot', id: 443},
  28407. {name: 'Clementine', id: 972},
  28408. {name: 'Durian', id: 169},
  28409. {name: 'Jackfruit', id: 982},
  28410. {name: 'Strawberry', id: 863}
  28411. ];
  28412. })
  28413. .component('basicAutocomplete', {
  28414. bindings: {
  28415. items: '<',
  28416. onSelect: '&'
  28417. },
  28418. templateUrl: 'autocomplete.html',
  28419. controller: function($element, $scope) {
  28420. var that = this;
  28421. var ngModel;
  28422. that.$postLink = function() {
  28423. ngModel = $element.find('input').controller('ngModel');
  28424. ngModel.$formatters.push(function(value) {
  28425. return (value && value.name) || value;
  28426. });
  28427. ngModel.$parsers.push(function(value) {
  28428. var match = value;
  28429. for (var i = 0; i < that.items.length; i++) {
  28430. if (that.items[i].name === value) {
  28431. match = that.items[i];
  28432. break;
  28433. }
  28434. }
  28435. return match;
  28436. });
  28437. };
  28438. that.selectItem = function(item) {
  28439. ngModel.$setViewValue(item);
  28440. ngModel.$processModelValue();
  28441. that.onSelect({item: item});
  28442. };
  28443. }
  28444. });
  28445. </file>
  28446. <file name="autocomplete.html">
  28447. <div>
  28448. <input type="search" ng-model="$ctrl.searchTerm" />
  28449. <ul>
  28450. <li ng-repeat="item in $ctrl.items | filter:$ctrl.searchTerm">
  28451. <button ng-click="$ctrl.selectItem(item)">{{ item.name }}</button>
  28452. </li>
  28453. </ul>
  28454. </div>
  28455. </file>
  28456. * </example>
  28457. *
  28458. */
  28459. $processModelValue: function() {
  28460. var viewValue = this.$$format();
  28461. if (this.$viewValue !== viewValue) {
  28462. this.$$updateEmptyClasses(viewValue);
  28463. this.$viewValue = this.$$lastCommittedViewValue = viewValue;
  28464. this.$render();
  28465. // It is possible that model and view value have been updated during render
  28466. this.$$runValidators(this.$modelValue, this.$viewValue, noop);
  28467. }
  28468. },
  28469. /**
  28470. * This method is called internally to run the $formatters on the $modelValue
  28471. */
  28472. $$format: function() {
  28473. var formatters = this.$formatters,
  28474. idx = formatters.length;
  28475. var viewValue = this.$modelValue;
  28476. while (idx--) {
  28477. viewValue = formatters[idx](viewValue);
  28478. }
  28479. return viewValue;
  28480. },
  28481. /**
  28482. * This method is called internally when the bound scope value changes.
  28483. */
  28484. $$setModelValue: function(modelValue) {
  28485. this.$modelValue = this.$$rawModelValue = modelValue;
  28486. this.$$parserValid = undefined;
  28487. this.$processModelValue();
  28488. },
  28489. $$setUpdateOnEvents: function() {
  28490. if (this.$$updateEvents) {
  28491. this.$$element.off(this.$$updateEvents, this.$$updateEventHandler);
  28492. }
  28493. this.$$updateEvents = this.$options.getOption('updateOn');
  28494. if (this.$$updateEvents) {
  28495. this.$$element.on(this.$$updateEvents, this.$$updateEventHandler);
  28496. }
  28497. },
  28498. $$updateEventHandler: function(ev) {
  28499. this.$$debounceViewValueCommit(ev && ev.type);
  28500. }
  28501. };
  28502. function setupModelWatcher(ctrl) {
  28503. // model -> value
  28504. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  28505. // 1. scope value is 'a'
  28506. // 2. user enters 'b'
  28507. // 3. ng-change kicks in and reverts scope value to 'a'
  28508. // -> scope value did not change since the last digest as
  28509. // ng-change executes in apply phase
  28510. // 4. view should be changed back to 'a'
  28511. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  28512. var modelValue = ctrl.$$ngModelGet(scope);
  28513. // if scope model value and ngModel value are out of sync
  28514. // This cannot be moved to the action function, because it would not catch the
  28515. // case where the model is changed in the ngChange function or the model setter
  28516. if (modelValue !== ctrl.$modelValue &&
  28517. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  28518. // eslint-disable-next-line no-self-compare
  28519. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  28520. ) {
  28521. ctrl.$$setModelValue(modelValue);
  28522. }
  28523. return modelValue;
  28524. });
  28525. }
  28526. /**
  28527. * @ngdoc method
  28528. * @name ngModel.NgModelController#$setValidity
  28529. *
  28530. * @description
  28531. * Change the validity state, and notify the form.
  28532. *
  28533. * This method can be called within $parsers/$formatters or a custom validation implementation.
  28534. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  28535. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  28536. *
  28537. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  28538. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  28539. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  28540. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  28541. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  28542. * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.
  28543. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  28544. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  28545. * Skipped is used by AngularJS when validators do not run because of parse errors and
  28546. * when `$asyncValidators` do not run because any of the `$validators` failed.
  28547. */
  28548. addSetValidityMethod({
  28549. clazz: NgModelController,
  28550. set: function(object, property) {
  28551. object[property] = true;
  28552. },
  28553. unset: function(object, property) {
  28554. delete object[property];
  28555. }
  28556. });
  28557. /**
  28558. * @ngdoc directive
  28559. * @name ngModel
  28560. * @restrict A
  28561. * @priority 1
  28562. * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to.
  28563. *
  28564. * @description
  28565. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  28566. * property on the scope using {@link ngModel.NgModelController NgModelController},
  28567. * which is created and exposed by this directive.
  28568. *
  28569. * `ngModel` is responsible for:
  28570. *
  28571. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  28572. * require.
  28573. * - Providing validation behavior (i.e. required, number, email, url).
  28574. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  28575. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  28576. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  28577. * - Registering the control with its parent {@link ng.directive:form form}.
  28578. *
  28579. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  28580. * current scope. If the property doesn't already exist on this scope, it will be created
  28581. * implicitly and added to the scope.
  28582. *
  28583. * For best practices on using `ngModel`, see:
  28584. *
  28585. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  28586. *
  28587. * For basic examples, how to use `ngModel`, see:
  28588. *
  28589. * - {@link ng.directive:input input}
  28590. * - {@link input[text] text}
  28591. * - {@link input[checkbox] checkbox}
  28592. * - {@link input[radio] radio}
  28593. * - {@link input[number] number}
  28594. * - {@link input[email] email}
  28595. * - {@link input[url] url}
  28596. * - {@link input[date] date}
  28597. * - {@link input[datetime-local] datetime-local}
  28598. * - {@link input[time] time}
  28599. * - {@link input[month] month}
  28600. * - {@link input[week] week}
  28601. * - {@link ng.directive:select select}
  28602. * - {@link ng.directive:textarea textarea}
  28603. *
  28604. * ## Complex Models (objects or collections)
  28605. *
  28606. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  28607. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  28608. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  28609. *
  28610. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  28611. *
  28612. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  28613. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  28614. * if the select is given the `multiple` attribute.
  28615. *
  28616. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  28617. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  28618. * not trigger a re-rendering of the model.
  28619. *
  28620. * ## CSS classes
  28621. * The following CSS classes are added and removed on the associated input/select/textarea element
  28622. * depending on the validity of the model.
  28623. *
  28624. * - `ng-valid`: the model is valid
  28625. * - `ng-invalid`: the model is invalid
  28626. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  28627. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  28628. * - `ng-pristine`: the control hasn't been interacted with yet
  28629. * - `ng-dirty`: the control has been interacted with
  28630. * - `ng-touched`: the control has been blurred
  28631. * - `ng-untouched`: the control hasn't been blurred
  28632. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  28633. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  28634. * by the {@link ngModel.NgModelController#$isEmpty} method
  28635. * - `ng-not-empty`: the view contains a non-empty value
  28636. *
  28637. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  28638. *
  28639. * @animations
  28640. * Animations within models are triggered when any of the associated CSS classes are added and removed
  28641. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  28642. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  28643. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  28644. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  28645. *
  28646. * The following example shows a simple way to utilize CSS transitions to style an input element
  28647. * that has been rendered as invalid after it has been validated:
  28648. *
  28649. * <pre>
  28650. * //be sure to include ngAnimate as a module to hook into more
  28651. * //advanced animations
  28652. * .my-input {
  28653. * transition:0.5s linear all;
  28654. * background: white;
  28655. * }
  28656. * .my-input.ng-invalid {
  28657. * background: red;
  28658. * color:white;
  28659. * }
  28660. * </pre>
  28661. *
  28662. * @example
  28663. * ### Basic Usage
  28664. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  28665. <file name="index.html">
  28666. <script>
  28667. angular.module('inputExample', [])
  28668. .controller('ExampleController', ['$scope', function($scope) {
  28669. $scope.val = '1';
  28670. }]);
  28671. </script>
  28672. <style>
  28673. .my-input {
  28674. transition:all linear 0.5s;
  28675. background: transparent;
  28676. }
  28677. .my-input.ng-invalid {
  28678. color:white;
  28679. background: red;
  28680. }
  28681. </style>
  28682. <p id="inputDescription">
  28683. Update input to see transitions when valid/invalid.
  28684. Integer is a valid value.
  28685. </p>
  28686. <form name="testForm" ng-controller="ExampleController">
  28687. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  28688. aria-describedby="inputDescription" />
  28689. </form>
  28690. </file>
  28691. * </example>
  28692. *
  28693. * @example
  28694. * ### Binding to a getter/setter
  28695. *
  28696. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  28697. * function that returns a representation of the model when called with zero arguments, and sets
  28698. * the internal state of a model when called with an argument. It's sometimes useful to use this
  28699. * for models that have an internal representation that's different from what the model exposes
  28700. * to the view.
  28701. *
  28702. * <div class="alert alert-success">
  28703. * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more
  28704. * frequently than other parts of your code.
  28705. * </div>
  28706. *
  28707. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  28708. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  28709. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  28710. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  28711. *
  28712. * The following example shows how to use `ngModel` with a getter/setter:
  28713. *
  28714. * @example
  28715. * <example name="ngModel-getter-setter" module="getterSetterExample">
  28716. <file name="index.html">
  28717. <div ng-controller="ExampleController">
  28718. <form name="userForm">
  28719. <label>Name:
  28720. <input type="text" name="userName"
  28721. ng-model="user.name"
  28722. ng-model-options="{ getterSetter: true }" />
  28723. </label>
  28724. </form>
  28725. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  28726. </div>
  28727. </file>
  28728. <file name="app.js">
  28729. angular.module('getterSetterExample', [])
  28730. .controller('ExampleController', ['$scope', function($scope) {
  28731. var _name = 'Brian';
  28732. $scope.user = {
  28733. name: function(newName) {
  28734. // Note that newName can be undefined for two reasons:
  28735. // 1. Because it is called as a getter and thus called with no arguments
  28736. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  28737. // input is invalid
  28738. return arguments.length ? (_name = newName) : _name;
  28739. }
  28740. };
  28741. }]);
  28742. </file>
  28743. * </example>
  28744. */
  28745. var ngModelDirective = ['$rootScope', function($rootScope) {
  28746. return {
  28747. restrict: 'A',
  28748. require: ['ngModel', '^?form', '^?ngModelOptions'],
  28749. controller: NgModelController,
  28750. // Prelink needs to run before any input directive
  28751. // so that we can set the NgModelOptions in NgModelController
  28752. // before anyone else uses it.
  28753. priority: 1,
  28754. compile: function ngModelCompile(element) {
  28755. // Setup initial state of the control
  28756. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  28757. return {
  28758. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  28759. var modelCtrl = ctrls[0],
  28760. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  28761. optionsCtrl = ctrls[2];
  28762. if (optionsCtrl) {
  28763. modelCtrl.$options = optionsCtrl.$options;
  28764. }
  28765. modelCtrl.$$initGetterSetters();
  28766. // notify others, especially parent forms
  28767. formCtrl.$addControl(modelCtrl);
  28768. attr.$observe('name', function(newValue) {
  28769. if (modelCtrl.$name !== newValue) {
  28770. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  28771. }
  28772. });
  28773. scope.$on('$destroy', function() {
  28774. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  28775. });
  28776. },
  28777. post: function ngModelPostLink(scope, element, attr, ctrls) {
  28778. var modelCtrl = ctrls[0];
  28779. modelCtrl.$$setUpdateOnEvents();
  28780. function setTouched() {
  28781. modelCtrl.$setTouched();
  28782. }
  28783. element.on('blur', function() {
  28784. if (modelCtrl.$touched) return;
  28785. if ($rootScope.$$phase) {
  28786. scope.$evalAsync(setTouched);
  28787. } else {
  28788. scope.$apply(setTouched);
  28789. }
  28790. });
  28791. }
  28792. };
  28793. }
  28794. };
  28795. }];
  28796. /* exported defaultModelOptions */
  28797. var defaultModelOptions;
  28798. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  28799. /**
  28800. * @ngdoc type
  28801. * @name ModelOptions
  28802. * @description
  28803. * A container for the options set by the {@link ngModelOptions} directive
  28804. */
  28805. function ModelOptions(options) {
  28806. this.$$options = options;
  28807. }
  28808. ModelOptions.prototype = {
  28809. /**
  28810. * @ngdoc method
  28811. * @name ModelOptions#getOption
  28812. * @param {string} name the name of the option to retrieve
  28813. * @returns {*} the value of the option
  28814. * @description
  28815. * Returns the value of the given option
  28816. */
  28817. getOption: function(name) {
  28818. return this.$$options[name];
  28819. },
  28820. /**
  28821. * @ngdoc method
  28822. * @name ModelOptions#createChild
  28823. * @param {Object} options a hash of options for the new child that will override the parent's options
  28824. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  28825. */
  28826. createChild: function(options) {
  28827. var inheritAll = false;
  28828. // make a shallow copy
  28829. options = extend({}, options);
  28830. // Inherit options from the parent if specified by the value `"$inherit"`
  28831. forEach(options, /** @this */ function(option, key) {
  28832. if (option === '$inherit') {
  28833. if (key === '*') {
  28834. inheritAll = true;
  28835. } else {
  28836. options[key] = this.$$options[key];
  28837. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  28838. if (key === 'updateOn') {
  28839. options.updateOnDefault = this.$$options.updateOnDefault;
  28840. }
  28841. }
  28842. } else {
  28843. if (key === 'updateOn') {
  28844. // If the `updateOn` property contains the `default` event then we have to remove
  28845. // it from the event list and set the `updateOnDefault` flag.
  28846. options.updateOnDefault = false;
  28847. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  28848. options.updateOnDefault = true;
  28849. return ' ';
  28850. }));
  28851. }
  28852. }
  28853. }, this);
  28854. if (inheritAll) {
  28855. // We have a property of the form: `"*": "$inherit"`
  28856. delete options['*'];
  28857. defaults(options, this.$$options);
  28858. }
  28859. // Finally add in any missing defaults
  28860. defaults(options, defaultModelOptions.$$options);
  28861. return new ModelOptions(options);
  28862. }
  28863. };
  28864. defaultModelOptions = new ModelOptions({
  28865. updateOn: '',
  28866. updateOnDefault: true,
  28867. debounce: 0,
  28868. getterSetter: false,
  28869. allowInvalid: false,
  28870. timezone: null
  28871. });
  28872. /**
  28873. * @ngdoc directive
  28874. * @name ngModelOptions
  28875. * @restrict A
  28876. * @priority 10
  28877. *
  28878. * @description
  28879. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  28880. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  28881. * directives will use the options of their nearest `ngModelOptions` ancestor.
  28882. *
  28883. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  28884. * an AngularJS expression. This expression should evaluate to an object, whose properties contain
  28885. * the settings. For example: `<div ng-model-options="{ debounce: 100 }"`.
  28886. *
  28887. * ## Inheriting Options
  28888. *
  28889. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  28890. * directive by giving it the value of `"$inherit"`.
  28891. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  28892. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  28893. * will be used.
  28894. *
  28895. * For example given the following fragment of HTML
  28896. *
  28897. *
  28898. * ```html
  28899. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  28900. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  28901. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  28902. * </form>
  28903. * </div>
  28904. * ```
  28905. *
  28906. * the `input` element will have the following settings
  28907. *
  28908. * ```js
  28909. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  28910. * ```
  28911. *
  28912. * Notice that the `debounce` setting was not inherited and used the default value instead.
  28913. *
  28914. * You can specify that all undefined settings are automatically inherited from an ancestor by
  28915. * including a property with key of `"*"` and value of `"$inherit"`.
  28916. *
  28917. * For example given the following fragment of HTML
  28918. *
  28919. *
  28920. * ```html
  28921. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  28922. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  28923. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  28924. * </form>
  28925. * </div>
  28926. * ```
  28927. *
  28928. * the `input` element will have the following settings
  28929. *
  28930. * ```js
  28931. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  28932. * ```
  28933. *
  28934. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  28935. *
  28936. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  28937. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  28938. *
  28939. *
  28940. * ## Triggering and debouncing model updates
  28941. *
  28942. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  28943. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  28944. * a timer expires; this timer will be reset after another change takes place.
  28945. *
  28946. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  28947. * be different from the value in the actual model. This means that if you update the model you
  28948. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  28949. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  28950. *
  28951. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  28952. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  28953. * important because `form` controllers are published to the related scope under the name in their
  28954. * `name` attribute.
  28955. *
  28956. * Any pending changes will take place immediately when an enclosing form is submitted via the
  28957. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  28958. * to have access to the updated model.
  28959. *
  28960. * ### Overriding immediate updates
  28961. *
  28962. * The following example shows how to override immediate updates. Changes on the inputs within the
  28963. * form will update the model only when the control loses focus (blur event). If `escape` key is
  28964. * pressed while the input field is focused, the value is reset to the value in the current model.
  28965. *
  28966. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  28967. * <file name="index.html">
  28968. * <div ng-controller="ExampleController">
  28969. * <form name="userForm">
  28970. * <label>
  28971. * Name:
  28972. * <input type="text" name="userName"
  28973. * ng-model="user.name"
  28974. * ng-model-options="{ updateOn: 'blur' }"
  28975. * ng-keyup="cancel($event)" />
  28976. * </label><br />
  28977. * <label>
  28978. * Other data:
  28979. * <input type="text" ng-model="user.data" />
  28980. * </label><br />
  28981. * </form>
  28982. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  28983. * </div>
  28984. * </file>
  28985. * <file name="app.js">
  28986. * angular.module('optionsExample', [])
  28987. * .controller('ExampleController', ['$scope', function($scope) {
  28988. * $scope.user = { name: 'say', data: '' };
  28989. *
  28990. * $scope.cancel = function(e) {
  28991. * if (e.keyCode === 27) {
  28992. * $scope.userForm.userName.$rollbackViewValue();
  28993. * }
  28994. * };
  28995. * }]);
  28996. * </file>
  28997. * <file name="protractor.js" type="protractor">
  28998. * var model = element(by.binding('user.name'));
  28999. * var input = element(by.model('user.name'));
  29000. * var other = element(by.model('user.data'));
  29001. *
  29002. * it('should allow custom events', function() {
  29003. * input.sendKeys(' hello');
  29004. * input.click();
  29005. * expect(model.getText()).toEqual('say');
  29006. * other.click();
  29007. * expect(model.getText()).toEqual('say hello');
  29008. * });
  29009. *
  29010. * it('should $rollbackViewValue when model changes', function() {
  29011. * input.sendKeys(' hello');
  29012. * expect(input.getAttribute('value')).toEqual('say hello');
  29013. * input.sendKeys(protractor.Key.ESCAPE);
  29014. * expect(input.getAttribute('value')).toEqual('say');
  29015. * other.click();
  29016. * expect(model.getText()).toEqual('say');
  29017. * });
  29018. * </file>
  29019. * </example>
  29020. *
  29021. * ### Debouncing updates
  29022. *
  29023. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  29024. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  29025. *
  29026. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  29027. * <file name="index.html">
  29028. * <div ng-controller="ExampleController">
  29029. * <form name="userForm">
  29030. * Name:
  29031. * <input type="text" name="userName"
  29032. * ng-model="user.name"
  29033. * ng-model-options="{ debounce: 1000 }" />
  29034. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  29035. * </form>
  29036. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  29037. * </div>
  29038. * </file>
  29039. * <file name="app.js">
  29040. * angular.module('optionsExample', [])
  29041. * .controller('ExampleController', ['$scope', function($scope) {
  29042. * $scope.user = { name: 'say' };
  29043. * }]);
  29044. * </file>
  29045. * </example>
  29046. *
  29047. * ### Default events, extra triggers, and catch-all debounce values
  29048. *
  29049. * This example shows the relationship between "default" update events and
  29050. * additional `updateOn` triggers.
  29051. *
  29052. * `default` events are those that are bound to the control, and when fired, update the `$viewValue`
  29053. * via {@link ngModel.NgModelController#$setViewValue $setViewValue}. Every event that is not listed
  29054. * in `updateOn` is considered a "default" event, since different control types have different
  29055. * default events.
  29056. *
  29057. * The control in this example updates by "default", "click", and "blur", with different `debounce`
  29058. * values. You can see that "click" doesn't have an individual `debounce` value -
  29059. * therefore it uses the `*` debounce value.
  29060. *
  29061. * There is also a button that calls {@link ngModel.NgModelController#$setViewValue $setViewValue}
  29062. * directly with a "custom" event. Since "custom" is not defined in the `updateOn` list,
  29063. * it is considered a "default" event and will update the
  29064. * control if "default" is defined in `updateOn`, and will receive the "default" debounce value.
  29065. * Note that this is just to illustrate how custom controls would possibly call `$setViewValue`.
  29066. *
  29067. * You can change the `updateOn` and `debounce` configuration to test different scenarios. This
  29068. * is done with {@link ngModel.NgModelController#$overrideModelOptions $overrideModelOptions}.
  29069. *
  29070. <example name="ngModelOptions-advanced" module="optionsExample">
  29071. <file name="index.html">
  29072. <model-update-demo></model-update-demo>
  29073. </file>
  29074. <file name="app.js">
  29075. angular.module('optionsExample', [])
  29076. .component('modelUpdateDemo', {
  29077. templateUrl: 'template.html',
  29078. controller: function() {
  29079. this.name = 'Chinua';
  29080. this.options = {
  29081. updateOn: 'default blur click',
  29082. debounce: {
  29083. default: 2000,
  29084. blur: 0,
  29085. '*': 1000
  29086. }
  29087. };
  29088. this.updateEvents = function() {
  29089. var eventList = this.options.updateOn.split(' ');
  29090. eventList.push('*');
  29091. var events = {};
  29092. for (var i = 0; i < eventList.length; i++) {
  29093. events[eventList[i]] = this.options.debounce[eventList[i]];
  29094. }
  29095. this.events = events;
  29096. };
  29097. this.updateOptions = function() {
  29098. var options = angular.extend(this.options, {
  29099. updateOn: Object.keys(this.events).join(' ').replace('*', ''),
  29100. debounce: this.events
  29101. });
  29102. this.form.input.$overrideModelOptions(options);
  29103. };
  29104. // Initialize the event form
  29105. this.updateEvents();
  29106. }
  29107. });
  29108. </file>
  29109. <file name="template.html">
  29110. <form name="$ctrl.form">
  29111. Input: <input type="text" name="input" ng-model="$ctrl.name" ng-model-options="$ctrl.options" />
  29112. </form>
  29113. Model: <tt>{{$ctrl.name}}</tt>
  29114. <hr>
  29115. <button ng-click="$ctrl.form.input.$setViewValue('some value', 'custom')">Trigger setViewValue with 'some value' and 'custom' event</button>
  29116. <hr>
  29117. <form ng-submit="$ctrl.updateOptions()">
  29118. <b>updateOn</b><br>
  29119. <input type="text" ng-model="$ctrl.options.updateOn" ng-change="$ctrl.updateEvents()" ng-model-options="{debounce: 500}">
  29120. <table>
  29121. <tr>
  29122. <th>Option</th>
  29123. <th>Debounce value</th>
  29124. </tr>
  29125. <tr ng-repeat="(key, value) in $ctrl.events">
  29126. <td>{{key}}</td>
  29127. <td><input type="number" ng-model="$ctrl.events[key]" /></td>
  29128. </tr>
  29129. </table>
  29130. <br>
  29131. <input type="submit" value="Update options">
  29132. </form>
  29133. </file>
  29134. </example>
  29135. *
  29136. *
  29137. * ## Model updates and validation
  29138. *
  29139. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  29140. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  29141. * the model will still be updated even if the value is invalid.
  29142. *
  29143. *
  29144. * ## Connecting to the scope
  29145. *
  29146. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  29147. * on the scope refers to a "getter/setter" function rather than the value itself.
  29148. *
  29149. * The following example shows how to bind to getter/setters:
  29150. *
  29151. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  29152. * <file name="index.html">
  29153. * <div ng-controller="ExampleController">
  29154. * <form name="userForm">
  29155. * <label>
  29156. * Name:
  29157. * <input type="text" name="userName"
  29158. * ng-model="user.name"
  29159. * ng-model-options="{ getterSetter: true }" />
  29160. * </label>
  29161. * </form>
  29162. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  29163. * </div>
  29164. * </file>
  29165. * <file name="app.js">
  29166. * angular.module('getterSetterExample', [])
  29167. * .controller('ExampleController', ['$scope', function($scope) {
  29168. * var _name = 'Brian';
  29169. * $scope.user = {
  29170. * name: function(newName) {
  29171. * return angular.isDefined(newName) ? (_name = newName) : _name;
  29172. * }
  29173. * };
  29174. * }]);
  29175. * </file>
  29176. * </example>
  29177. *
  29178. *
  29179. * ## Programmatically changing options
  29180. *
  29181. * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not
  29182. * watched for changes. However, it is possible to override the options on a single
  29183. * {@link ngModel.NgModelController} instance with
  29184. * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}.
  29185. * See also the example for
  29186. * {@link ngModelOptions#default-events-extra-triggers-and-catch-all-debounce-values
  29187. * Default events, extra triggers, and catch-all debounce values}.
  29188. *
  29189. *
  29190. * ## Specifying timezones
  29191. *
  29192. * You can specify the timezone that date/time input directives expect by providing its name in the
  29193. * `timezone` property.
  29194. *
  29195. *
  29196. * ## Formatting the value of `time` and `datetime-local`
  29197. *
  29198. * With the options `timeSecondsFormat` and `timeStripZeroSeconds` it is possible to adjust the value
  29199. * that is displayed in the control. Note that browsers may apply their own formatting
  29200. * in the user interface.
  29201. *
  29202. <example name="ngModelOptions-time-format" module="timeExample">
  29203. <file name="index.html">
  29204. <time-example></time-example>
  29205. </file>
  29206. <file name="script.js">
  29207. angular.module('timeExample', [])
  29208. .component('timeExample', {
  29209. templateUrl: 'timeExample.html',
  29210. controller: function() {
  29211. this.time = new Date(1970, 0, 1, 14, 57, 0);
  29212. this.options = {
  29213. timeSecondsFormat: 'ss',
  29214. timeStripZeroSeconds: true
  29215. };
  29216. this.optionChange = function() {
  29217. this.timeForm.timeFormatted.$overrideModelOptions(this.options);
  29218. this.time = new Date(this.time);
  29219. };
  29220. }
  29221. });
  29222. </file>
  29223. <file name="timeExample.html">
  29224. <form name="$ctrl.timeForm">
  29225. <strong>Default</strong>:
  29226. <input type="time" ng-model="$ctrl.time" step="any" /><br>
  29227. <strong>With options</strong>:
  29228. <input type="time" name="timeFormatted" ng-model="$ctrl.time" step="any" ng-model-options="$ctrl.options" />
  29229. <br>
  29230. Options:<br>
  29231. <code>timeSecondsFormat</code>:
  29232. <input
  29233. type="text"
  29234. ng-model="$ctrl.options.timeSecondsFormat"
  29235. ng-change="$ctrl.optionChange()">
  29236. <br>
  29237. <code>timeStripZeroSeconds</code>:
  29238. <input
  29239. type="checkbox"
  29240. ng-model="$ctrl.options.timeStripZeroSeconds"
  29241. ng-change="$ctrl.optionChange()">
  29242. </form>
  29243. </file>
  29244. * </example>
  29245. *
  29246. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  29247. * and its descendents.
  29248. *
  29249. * **General options**:
  29250. *
  29251. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  29252. * events using an space delimited list. There is a special event called `default` that
  29253. * matches the default events belonging to the control. These are the events that are bound to
  29254. * the control, and when fired, update the `$viewValue` via `$setViewValue`.
  29255. *
  29256. * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event,
  29257. * since different control types use different default events.
  29258. *
  29259. * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates
  29260. * Triggering and debouncing model updates}.
  29261. *
  29262. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  29263. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  29264. * custom value for each event. For example:
  29265. * ```
  29266. * ng-model-options="{
  29267. * updateOn: 'default blur',
  29268. * debounce: { 'default': 500, 'blur': 0 }
  29269. * }"
  29270. * ```
  29271. * You can use the `*` key to specify a debounce value that applies to all events that are not
  29272. * specifically listed. In the following example, `mouseup` would have a debounce delay of 1000:
  29273. * ```
  29274. * ng-model-options="{
  29275. * updateOn: 'default blur mouseup',
  29276. * debounce: { 'default': 500, 'blur': 0, '*': 1000 }
  29277. * }"
  29278. * ```
  29279. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  29280. * not validate correctly instead of the default behavior of setting the model to undefined.
  29281. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  29282. * `ngModel` as getters/setters.
  29283. *
  29284. *
  29285. * **Input-type specific options**:
  29286. *
  29287. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  29288. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  29289. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  29290. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  29291. * If not specified, the timezone of the browser will be used.
  29292. * Note that changing the timezone will have no effect on the current date, and is only applied after
  29293. * the next input / model change.
  29294. *
  29295. * - `timeSecondsFormat`: Defines if the `time` and `datetime-local` types should show seconds and
  29296. * milliseconds. The option follows the format string of {@link date date filter}.
  29297. * By default, the options is `undefined` which is equal to `'ss.sss'` (seconds and milliseconds).
  29298. * The other options are `'ss'` (strips milliseconds), and `''` (empty string), which strips both
  29299. * seconds and milliseconds.
  29300. * Note that browsers that support `time` and `datetime-local` require the hour and minutes
  29301. * part of the time string, and may show the value differently in the user interface.
  29302. * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.
  29303. *
  29304. * - `timeStripZeroSeconds`: Defines if the `time` and `datetime-local` types should strip the
  29305. * seconds and milliseconds from the formatted value if they are zero. This option is applied
  29306. * after `timeSecondsFormat`.
  29307. * This option can be used to make the formatting consistent over different browsers, as some
  29308. * browsers with support for `time` will natively hide the milliseconds and
  29309. * seconds if they are zero, but others won't, and browsers that don't implement these input
  29310. * types will always show the full string.
  29311. * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.
  29312. *
  29313. */
  29314. var ngModelOptionsDirective = function() {
  29315. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  29316. function NgModelOptionsController($attrs, $scope) {
  29317. this.$$attrs = $attrs;
  29318. this.$$scope = $scope;
  29319. }
  29320. NgModelOptionsController.prototype = {
  29321. $onInit: function() {
  29322. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  29323. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  29324. this.$options = parentOptions.createChild(modelOptionsDefinition);
  29325. }
  29326. };
  29327. return {
  29328. restrict: 'A',
  29329. // ngModelOptions needs to run before ngModel and input directives
  29330. priority: 10,
  29331. require: {parentCtrl: '?^^ngModelOptions'},
  29332. bindToController: true,
  29333. controller: NgModelOptionsController
  29334. };
  29335. };
  29336. // shallow copy over values from `src` that are not already specified on `dst`
  29337. function defaults(dst, src) {
  29338. forEach(src, function(value, key) {
  29339. if (!isDefined(dst[key])) {
  29340. dst[key] = value;
  29341. }
  29342. });
  29343. }
  29344. /**
  29345. * @ngdoc directive
  29346. * @name ngNonBindable
  29347. * @restrict AC
  29348. * @priority 1000
  29349. * @element ANY
  29350. *
  29351. * @description
  29352. * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current
  29353. * DOM element, including directives on the element itself that have a lower priority than
  29354. * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives
  29355. * and bindings but which should be ignored by AngularJS. This could be the case if you have a site
  29356. * that displays snippets of code, for instance.
  29357. *
  29358. * @example
  29359. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  29360. * but the one wrapped in `ngNonBindable` is left alone.
  29361. *
  29362. <example name="ng-non-bindable">
  29363. <file name="index.html">
  29364. <div>Normal: {{1 + 2}}</div>
  29365. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  29366. </file>
  29367. <file name="protractor.js" type="protractor">
  29368. it('should check ng-non-bindable', function() {
  29369. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  29370. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  29371. });
  29372. </file>
  29373. </example>
  29374. */
  29375. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  29376. /* exported ngOptionsDirective */
  29377. /* global jqLiteRemove */
  29378. var ngOptionsMinErr = minErr('ngOptions');
  29379. /**
  29380. * @ngdoc directive
  29381. * @name ngOptions
  29382. * @restrict A
  29383. *
  29384. * @description
  29385. *
  29386. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  29387. * elements for the `<select>` element using the array or object obtained by evaluating the
  29388. * `ngOptions` comprehension expression.
  29389. *
  29390. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  29391. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  29392. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29393. * comprehension expression
  29394. * - reduced memory consumption by not creating a new scope for each repeated instance
  29395. * - increased render speed by creating the options in a documentFragment instead of individually
  29396. *
  29397. * When an item in the `<select>` menu is selected, the array element or object property
  29398. * represented by the selected option will be bound to the model identified by the `ngModel`
  29399. * directive.
  29400. *
  29401. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29402. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29403. * option. See example below for demonstration.
  29404. *
  29405. * ## Complex Models (objects or collections)
  29406. *
  29407. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  29408. * binding the select to a model that is an object or a collection.
  29409. *
  29410. * One issue occurs if you want to preselect an option. For example, if you set
  29411. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  29412. * because the objects are not identical. So by default, you should always reference the item in your collection
  29413. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  29414. *
  29415. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  29416. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  29417. * collection items have an id property, you would `track by item.id`.
  29418. *
  29419. * A different issue with objects or collections is that ngModel won't detect if an object property or
  29420. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  29421. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  29422. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  29423. * has not changed identity, but only a property on the object or an item in the collection changes.
  29424. *
  29425. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  29426. * if the model is an array). This means that changing a property deeper than the first level inside the
  29427. * object/collection will not trigger a re-rendering.
  29428. *
  29429. * ## `select` **`as`**
  29430. *
  29431. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  29432. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  29433. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  29434. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  29435. *
  29436. *
  29437. * ### `select` **`as`** and **`track by`**
  29438. *
  29439. * <div class="alert alert-warning">
  29440. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  29441. * </div>
  29442. *
  29443. * Given this array of items on the $scope:
  29444. *
  29445. * ```js
  29446. * $scope.items = [{
  29447. * id: 1,
  29448. * label: 'aLabel',
  29449. * subItem: { name: 'aSubItem' }
  29450. * }, {
  29451. * id: 2,
  29452. * label: 'bLabel',
  29453. * subItem: { name: 'bSubItem' }
  29454. * }];
  29455. * ```
  29456. *
  29457. * This will work:
  29458. *
  29459. * ```html
  29460. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  29461. * ```
  29462. * ```js
  29463. * $scope.selected = $scope.items[0];
  29464. * ```
  29465. *
  29466. * but this will not work:
  29467. *
  29468. * ```html
  29469. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  29470. * ```
  29471. * ```js
  29472. * $scope.selected = $scope.items[0].subItem;
  29473. * ```
  29474. *
  29475. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  29476. * `items` array. Because the selected option has been set programmatically in the controller, the
  29477. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  29478. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  29479. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  29480. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  29481. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  29482. *
  29483. *
  29484. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  29485. * @param {comprehension_expression} ngOptions in one of the following forms:
  29486. *
  29487. * * for array data sources:
  29488. * * `label` **`for`** `value` **`in`** `array`
  29489. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  29490. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  29491. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  29492. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  29493. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  29494. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  29495. * (for including a filter with `track by`)
  29496. * * for object data sources:
  29497. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  29498. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  29499. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  29500. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  29501. * * `select` **`as`** `label` **`group by`** `group`
  29502. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  29503. * * `select` **`as`** `label` **`disable when`** `disable`
  29504. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  29505. *
  29506. * Where:
  29507. *
  29508. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  29509. * * `value`: local variable which will refer to each item in the `array` or each property value
  29510. * of `object` during iteration.
  29511. * * `key`: local variable which will refer to a property name in `object` during iteration.
  29512. * * `label`: The result of this expression will be the label for `<option>` element. The
  29513. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  29514. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  29515. * element. If not specified, `select` expression will default to `value`.
  29516. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  29517. * DOM element.
  29518. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  29519. * element. Return `true` to disable.
  29520. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  29521. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  29522. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  29523. * even when the options are recreated (e.g. reloaded from the server).
  29524. * @param {string=} name Property name of the form under which the control is published.
  29525. * @param {string=} required The control is considered valid only if value is entered.
  29526. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  29527. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  29528. * `required` when you want to data-bind to the `required` attribute.
  29529. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  29530. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  29531. *
  29532. * @example
  29533. <example module="selectExample" name="select">
  29534. <file name="index.html">
  29535. <script>
  29536. angular.module('selectExample', [])
  29537. .controller('ExampleController', ['$scope', function($scope) {
  29538. $scope.colors = [
  29539. {name:'black', shade:'dark'},
  29540. {name:'white', shade:'light', notAnOption: true},
  29541. {name:'red', shade:'dark'},
  29542. {name:'blue', shade:'dark', notAnOption: true},
  29543. {name:'yellow', shade:'light', notAnOption: false}
  29544. ];
  29545. $scope.myColor = $scope.colors[2]; // red
  29546. }]);
  29547. </script>
  29548. <div ng-controller="ExampleController">
  29549. <ul>
  29550. <li ng-repeat="color in colors">
  29551. <label>Name: <input ng-model="color.name"></label>
  29552. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  29553. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  29554. </li>
  29555. <li>
  29556. <button ng-click="colors.push({})">add</button>
  29557. </li>
  29558. </ul>
  29559. <hr/>
  29560. <label>Color (null not allowed):
  29561. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  29562. </label><br/>
  29563. <label>Color (null allowed):
  29564. <span class="nullable">
  29565. <select ng-model="myColor" ng-options="color.name for color in colors">
  29566. <option value="">-- choose color --</option>
  29567. </select>
  29568. </span></label><br/>
  29569. <label>Color grouped by shade:
  29570. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  29571. </select>
  29572. </label><br/>
  29573. <label>Color grouped by shade, with some disabled:
  29574. <select ng-model="myColor"
  29575. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  29576. </select>
  29577. </label><br/>
  29578. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  29579. <br/>
  29580. <hr/>
  29581. Currently selected: {{ {selected_color:myColor} }}
  29582. <div style="border:solid 1px black; height:20px"
  29583. ng-style="{'background-color':myColor.name}">
  29584. </div>
  29585. </div>
  29586. </file>
  29587. <file name="protractor.js" type="protractor">
  29588. it('should check ng-options', function() {
  29589. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  29590. element.all(by.model('myColor')).first().click();
  29591. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  29592. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  29593. element(by.css('.nullable select[ng-model="myColor"]')).click();
  29594. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  29595. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  29596. });
  29597. </file>
  29598. </example>
  29599. */
  29600. /* eslint-disable max-len */
  29601. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  29602. 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]+?))?$/;
  29603. // 1: value expression (valueFn)
  29604. // 2: label expression (displayFn)
  29605. // 3: group by expression (groupByFn)
  29606. // 4: disable when expression (disableWhenFn)
  29607. // 5: array item variable name
  29608. // 6: object item key variable name
  29609. // 7: object item value variable name
  29610. // 8: collection expression
  29611. // 9: track by expression
  29612. /* eslint-enable */
  29613. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  29614. function parseOptionsExpression(optionsExp, selectElement, scope) {
  29615. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  29616. if (!(match)) {
  29617. throw ngOptionsMinErr('iexp',
  29618. 'Expected expression in form of ' +
  29619. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  29620. ' but got \'{0}\'. Element: {1}',
  29621. optionsExp, startingTag(selectElement));
  29622. }
  29623. // Extract the parts from the ngOptions expression
  29624. // The variable name for the value of the item in the collection
  29625. var valueName = match[5] || match[7];
  29626. // The variable name for the key of the item in the collection
  29627. var keyName = match[6];
  29628. // An expression that generates the viewValue for an option if there is a label expression
  29629. var selectAs = / as /.test(match[0]) && match[1];
  29630. // An expression that is used to track the id of each object in the options collection
  29631. var trackBy = match[9];
  29632. // An expression that generates the viewValue for an option if there is no label expression
  29633. var valueFn = $parse(match[2] ? match[1] : valueName);
  29634. var selectAsFn = selectAs && $parse(selectAs);
  29635. var viewValueFn = selectAsFn || valueFn;
  29636. var trackByFn = trackBy && $parse(trackBy);
  29637. // Get the value by which we are going to track the option
  29638. // if we have a trackFn then use that (passing scope and locals)
  29639. // otherwise just hash the given viewValue
  29640. var getTrackByValueFn = trackBy ?
  29641. function(value, locals) { return trackByFn(scope, locals); } :
  29642. function getHashOfValue(value) { return hashKey(value); };
  29643. var getTrackByValue = function(value, key) {
  29644. return getTrackByValueFn(value, getLocals(value, key));
  29645. };
  29646. var displayFn = $parse(match[2] || match[1]);
  29647. var groupByFn = $parse(match[3] || '');
  29648. var disableWhenFn = $parse(match[4] || '');
  29649. var valuesFn = $parse(match[8]);
  29650. var locals = {};
  29651. var getLocals = keyName ? function(value, key) {
  29652. locals[keyName] = key;
  29653. locals[valueName] = value;
  29654. return locals;
  29655. } : function(value) {
  29656. locals[valueName] = value;
  29657. return locals;
  29658. };
  29659. function Option(selectValue, viewValue, label, group, disabled) {
  29660. this.selectValue = selectValue;
  29661. this.viewValue = viewValue;
  29662. this.label = label;
  29663. this.group = group;
  29664. this.disabled = disabled;
  29665. }
  29666. function getOptionValuesKeys(optionValues) {
  29667. var optionValuesKeys;
  29668. if (!keyName && isArrayLike(optionValues)) {
  29669. optionValuesKeys = optionValues;
  29670. } else {
  29671. // if object, extract keys, in enumeration order, unsorted
  29672. optionValuesKeys = [];
  29673. for (var itemKey in optionValues) {
  29674. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  29675. optionValuesKeys.push(itemKey);
  29676. }
  29677. }
  29678. }
  29679. return optionValuesKeys;
  29680. }
  29681. return {
  29682. trackBy: trackBy,
  29683. getTrackByValue: getTrackByValue,
  29684. getWatchables: $parse(valuesFn, function(optionValues) {
  29685. // Create a collection of things that we would like to watch (watchedArray)
  29686. // so that they can all be watched using a single $watchCollection
  29687. // that only runs the handler once if anything changes
  29688. var watchedArray = [];
  29689. optionValues = optionValues || [];
  29690. var optionValuesKeys = getOptionValuesKeys(optionValues);
  29691. var optionValuesLength = optionValuesKeys.length;
  29692. for (var index = 0; index < optionValuesLength; index++) {
  29693. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  29694. var value = optionValues[key];
  29695. var locals = getLocals(value, key);
  29696. var selectValue = getTrackByValueFn(value, locals);
  29697. watchedArray.push(selectValue);
  29698. // Only need to watch the displayFn if there is a specific label expression
  29699. if (match[2] || match[1]) {
  29700. var label = displayFn(scope, locals);
  29701. watchedArray.push(label);
  29702. }
  29703. // Only need to watch the disableWhenFn if there is a specific disable expression
  29704. if (match[4]) {
  29705. var disableWhen = disableWhenFn(scope, locals);
  29706. watchedArray.push(disableWhen);
  29707. }
  29708. }
  29709. return watchedArray;
  29710. }),
  29711. getOptions: function() {
  29712. var optionItems = [];
  29713. var selectValueMap = {};
  29714. // The option values were already computed in the `getWatchables` fn,
  29715. // which must have been called to trigger `getOptions`
  29716. var optionValues = valuesFn(scope) || [];
  29717. var optionValuesKeys = getOptionValuesKeys(optionValues);
  29718. var optionValuesLength = optionValuesKeys.length;
  29719. for (var index = 0; index < optionValuesLength; index++) {
  29720. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  29721. var value = optionValues[key];
  29722. var locals = getLocals(value, key);
  29723. var viewValue = viewValueFn(scope, locals);
  29724. var selectValue = getTrackByValueFn(viewValue, locals);
  29725. var label = displayFn(scope, locals);
  29726. var group = groupByFn(scope, locals);
  29727. var disabled = disableWhenFn(scope, locals);
  29728. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  29729. optionItems.push(optionItem);
  29730. selectValueMap[selectValue] = optionItem;
  29731. }
  29732. return {
  29733. items: optionItems,
  29734. selectValueMap: selectValueMap,
  29735. getOptionFromViewValue: function(value) {
  29736. return selectValueMap[getTrackByValue(value)];
  29737. },
  29738. getViewValueFromOption: function(option) {
  29739. // If the viewValue could be an object that may be mutated by the application,
  29740. // we need to make a copy and not return the reference to the value on the option.
  29741. return trackBy ? copy(option.viewValue) : option.viewValue;
  29742. }
  29743. };
  29744. }
  29745. };
  29746. }
  29747. // Support: IE 9 only
  29748. // We can't just jqLite('<option>') since jqLite is not smart enough
  29749. // to create it in <select> and IE barfs otherwise.
  29750. var optionTemplate = window.document.createElement('option'),
  29751. optGroupTemplate = window.document.createElement('optgroup');
  29752. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  29753. var selectCtrl = ctrls[0];
  29754. var ngModelCtrl = ctrls[1];
  29755. var multiple = attr.multiple;
  29756. // The emptyOption allows the application developer to provide their own custom "empty"
  29757. // option when the viewValue does not match any of the option values.
  29758. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  29759. if (children[i].value === '') {
  29760. selectCtrl.hasEmptyOption = true;
  29761. selectCtrl.emptyOption = children.eq(i);
  29762. break;
  29763. }
  29764. }
  29765. // The empty option will be compiled and rendered before we first generate the options
  29766. selectElement.empty();
  29767. var providedEmptyOption = !!selectCtrl.emptyOption;
  29768. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  29769. unknownOption.val('?');
  29770. var options;
  29771. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  29772. // This stores the newly created options before they are appended to the select.
  29773. // Since the contents are removed from the fragment when it is appended,
  29774. // we only need to create it once.
  29775. var listFragment = $document[0].createDocumentFragment();
  29776. // Overwrite the implementation. ngOptions doesn't use hashes
  29777. selectCtrl.generateUnknownOptionValue = function(val) {
  29778. return '?';
  29779. };
  29780. // Update the controller methods for multiple selectable options
  29781. if (!multiple) {
  29782. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  29783. // The options might not be defined yet when ngModel tries to render
  29784. if (!options) return;
  29785. var selectedOption = selectElement[0].options[selectElement[0].selectedIndex];
  29786. var option = options.getOptionFromViewValue(value);
  29787. // Make sure to remove the selected attribute from the previously selected option
  29788. // Otherwise, screen readers might get confused
  29789. if (selectedOption) selectedOption.removeAttribute('selected');
  29790. if (option) {
  29791. // Don't update the option when it is already selected.
  29792. // For example, the browser will select the first option by default. In that case,
  29793. // most properties are set automatically - except the `selected` attribute, which we
  29794. // set always
  29795. if (selectElement[0].value !== option.selectValue) {
  29796. selectCtrl.removeUnknownOption();
  29797. selectElement[0].value = option.selectValue;
  29798. option.element.selected = true;
  29799. }
  29800. option.element.setAttribute('selected', 'selected');
  29801. } else {
  29802. selectCtrl.selectUnknownOrEmptyOption(value);
  29803. }
  29804. };
  29805. selectCtrl.readValue = function readNgOptionsValue() {
  29806. var selectedOption = options.selectValueMap[selectElement.val()];
  29807. if (selectedOption && !selectedOption.disabled) {
  29808. selectCtrl.unselectEmptyOption();
  29809. selectCtrl.removeUnknownOption();
  29810. return options.getViewValueFromOption(selectedOption);
  29811. }
  29812. return null;
  29813. };
  29814. // If we are using `track by` then we must watch the tracked value on the model
  29815. // since ngModel only watches for object identity change
  29816. // FIXME: When a user selects an option, this watch will fire needlessly
  29817. if (ngOptions.trackBy) {
  29818. scope.$watch(
  29819. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  29820. function() { ngModelCtrl.$render(); }
  29821. );
  29822. }
  29823. } else {
  29824. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  29825. // The options might not be defined yet when ngModel tries to render
  29826. if (!options) return;
  29827. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  29828. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  29829. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  29830. options.items.forEach(function(option) {
  29831. if (option.element.selected && !includes(selectedOptions, option)) {
  29832. option.element.selected = false;
  29833. }
  29834. });
  29835. };
  29836. selectCtrl.readValue = function readNgOptionsMultiple() {
  29837. var selectedValues = selectElement.val() || [],
  29838. selections = [];
  29839. forEach(selectedValues, function(value) {
  29840. var option = options.selectValueMap[value];
  29841. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  29842. });
  29843. return selections;
  29844. };
  29845. // If we are using `track by` then we must watch these tracked values on the model
  29846. // since ngModel only watches for object identity change
  29847. if (ngOptions.trackBy) {
  29848. scope.$watchCollection(function() {
  29849. if (isArray(ngModelCtrl.$viewValue)) {
  29850. return ngModelCtrl.$viewValue.map(function(value) {
  29851. return ngOptions.getTrackByValue(value);
  29852. });
  29853. }
  29854. }, function() {
  29855. ngModelCtrl.$render();
  29856. });
  29857. }
  29858. }
  29859. if (providedEmptyOption) {
  29860. // compile the element since there might be bindings in it
  29861. $compile(selectCtrl.emptyOption)(scope);
  29862. selectElement.prepend(selectCtrl.emptyOption);
  29863. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  29864. // This means the empty option has currently no actual DOM node, probably because
  29865. // it has been modified by a transclusion directive.
  29866. selectCtrl.hasEmptyOption = false;
  29867. // Redefine the registerOption function, which will catch
  29868. // options that are added by ngIf etc. (rendering of the node is async because of
  29869. // lazy transclusion)
  29870. selectCtrl.registerOption = function(optionScope, optionEl) {
  29871. if (optionEl.val() === '') {
  29872. selectCtrl.hasEmptyOption = true;
  29873. selectCtrl.emptyOption = optionEl;
  29874. selectCtrl.emptyOption.removeClass('ng-scope');
  29875. // This ensures the new empty option is selected if previously no option was selected
  29876. ngModelCtrl.$render();
  29877. optionEl.on('$destroy', function() {
  29878. var needsRerender = selectCtrl.$isEmptyOptionSelected();
  29879. selectCtrl.hasEmptyOption = false;
  29880. selectCtrl.emptyOption = undefined;
  29881. if (needsRerender) ngModelCtrl.$render();
  29882. });
  29883. }
  29884. };
  29885. } else {
  29886. // remove the class, which is added automatically because we recompile the element and it
  29887. // becomes the compilation root
  29888. selectCtrl.emptyOption.removeClass('ng-scope');
  29889. }
  29890. }
  29891. // We will re-render the option elements if the option values or labels change
  29892. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  29893. // ------------------------------------------------------------------ //
  29894. function addOptionElement(option, parent) {
  29895. var optionElement = optionTemplate.cloneNode(false);
  29896. parent.appendChild(optionElement);
  29897. updateOptionElement(option, optionElement);
  29898. }
  29899. function getAndUpdateSelectedOption(viewValue) {
  29900. var option = options.getOptionFromViewValue(viewValue);
  29901. var element = option && option.element;
  29902. if (element && !element.selected) element.selected = true;
  29903. return option;
  29904. }
  29905. function updateOptionElement(option, element) {
  29906. option.element = element;
  29907. element.disabled = option.disabled;
  29908. // Support: IE 11 only, Edge 12-13 only
  29909. // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive
  29910. // selects in certain circumstances when multiple selects are next to each other and display
  29911. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  29912. // See https://github.com/angular/angular.js/issues/11314 for more info.
  29913. // This is unfortunately untestable with unit / e2e tests
  29914. if (option.label !== element.label) {
  29915. element.label = option.label;
  29916. element.textContent = option.label;
  29917. }
  29918. element.value = option.selectValue;
  29919. }
  29920. function updateOptions() {
  29921. var previousValue = options && selectCtrl.readValue();
  29922. // We must remove all current options, but cannot simply set innerHTML = null
  29923. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  29924. // must preserve.
  29925. // Instead, iterate over the current option elements and remove them or their optgroup
  29926. // parents
  29927. if (options) {
  29928. for (var i = options.items.length - 1; i >= 0; i--) {
  29929. var option = options.items[i];
  29930. if (isDefined(option.group)) {
  29931. jqLiteRemove(option.element.parentNode);
  29932. } else {
  29933. jqLiteRemove(option.element);
  29934. }
  29935. }
  29936. }
  29937. options = ngOptions.getOptions();
  29938. var groupElementMap = {};
  29939. options.items.forEach(function addOption(option) {
  29940. var groupElement;
  29941. if (isDefined(option.group)) {
  29942. // This option is to live in a group
  29943. // See if we have already created this group
  29944. groupElement = groupElementMap[option.group];
  29945. if (!groupElement) {
  29946. groupElement = optGroupTemplate.cloneNode(false);
  29947. listFragment.appendChild(groupElement);
  29948. // Update the label on the group element
  29949. // "null" is special cased because of Safari
  29950. groupElement.label = option.group === null ? 'null' : option.group;
  29951. // Store it for use later
  29952. groupElementMap[option.group] = groupElement;
  29953. }
  29954. addOptionElement(option, groupElement);
  29955. } else {
  29956. // This option is not in a group
  29957. addOptionElement(option, listFragment);
  29958. }
  29959. });
  29960. selectElement[0].appendChild(listFragment);
  29961. ngModelCtrl.$render();
  29962. // Check to see if the value has changed due to the update to the options
  29963. if (!ngModelCtrl.$isEmpty(previousValue)) {
  29964. var nextValue = selectCtrl.readValue();
  29965. var isNotPrimitive = ngOptions.trackBy || multiple;
  29966. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  29967. ngModelCtrl.$setViewValue(nextValue);
  29968. ngModelCtrl.$render();
  29969. }
  29970. }
  29971. }
  29972. }
  29973. return {
  29974. restrict: 'A',
  29975. terminal: true,
  29976. require: ['select', 'ngModel'],
  29977. link: {
  29978. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  29979. // Deactivate the SelectController.register method to prevent
  29980. // option directives from accidentally registering themselves
  29981. // (and unwanted $destroy handlers etc.)
  29982. ctrls[0].registerOption = noop;
  29983. },
  29984. post: ngOptionsPostLink
  29985. }
  29986. };
  29987. }];
  29988. /**
  29989. * @ngdoc directive
  29990. * @name ngPluralize
  29991. * @restrict EA
  29992. *
  29993. * @description
  29994. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  29995. * These rules are bundled with angular.js, but can be overridden
  29996. * (see {@link guide/i18n AngularJS i18n} dev guide). You configure ngPluralize directive
  29997. * by specifying the mappings between
  29998. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  29999. * and the strings to be displayed.
  30000. *
  30001. * ## Plural categories and explicit number rules
  30002. * There are two
  30003. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  30004. * in AngularJS's default en-US locale: "one" and "other".
  30005. *
  30006. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  30007. * any number that is not 1), an explicit number rule can only match one number. For example, the
  30008. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  30009. * and explicit number rules throughout the rest of this documentation.
  30010. *
  30011. * ## Configuring ngPluralize
  30012. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  30013. * You can also provide an optional attribute, `offset`.
  30014. *
  30015. * The value of the `count` attribute can be either a string or an {@link guide/expression
  30016. * AngularJS expression}; these are evaluated on the current scope for its bound value.
  30017. *
  30018. * The `when` attribute specifies the mappings between plural categories and the actual
  30019. * string to be displayed. The value of the attribute should be a JSON object.
  30020. *
  30021. * The following example shows how to configure ngPluralize:
  30022. *
  30023. * ```html
  30024. * <ng-pluralize count="personCount"
  30025. when="{'0': 'Nobody is viewing.',
  30026. * 'one': '1 person is viewing.',
  30027. * 'other': '{} people are viewing.'}">
  30028. * </ng-pluralize>
  30029. *```
  30030. *
  30031. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  30032. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  30033. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  30034. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  30035. * show "a dozen people are viewing".
  30036. *
  30037. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  30038. * into pluralized strings. In the previous example, AngularJS will replace `{}` with
  30039. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  30040. * for <span ng-non-bindable>{{numberExpression}}</span>.
  30041. *
  30042. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  30043. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  30044. *
  30045. * ## Configuring ngPluralize with offset
  30046. * The `offset` attribute allows further customization of pluralized text, which can result in
  30047. * a better user experience. For example, instead of the message "4 people are viewing this document",
  30048. * you might display "John, Kate and 2 others are viewing this document".
  30049. * The offset attribute allows you to offset a number by any desired value.
  30050. * Let's take a look at an example:
  30051. *
  30052. * ```html
  30053. * <ng-pluralize count="personCount" offset=2
  30054. * when="{'0': 'Nobody is viewing.',
  30055. * '1': '{{person1}} is viewing.',
  30056. * '2': '{{person1}} and {{person2}} are viewing.',
  30057. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  30058. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  30059. * </ng-pluralize>
  30060. * ```
  30061. *
  30062. * Notice that we are still using two plural categories(one, other), but we added
  30063. * three explicit number rules 0, 1 and 2.
  30064. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  30065. * When three people view the document, no explicit number rule is found, so
  30066. * an offset of 2 is taken off 3, and AngularJS uses 1 to decide the plural category.
  30067. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  30068. * is shown.
  30069. *
  30070. * Note that when you specify offsets, you must provide explicit number rules for
  30071. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  30072. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  30073. * plural categories "one" and "other".
  30074. *
  30075. * @param {string|expression} count The variable to be bound to.
  30076. * @param {string} when The mapping between plural category to its corresponding strings.
  30077. * @param {number=} offset Offset to deduct from the total number.
  30078. *
  30079. * @example
  30080. <example module="pluralizeExample" name="ng-pluralize">
  30081. <file name="index.html">
  30082. <script>
  30083. angular.module('pluralizeExample', [])
  30084. .controller('ExampleController', ['$scope', function($scope) {
  30085. $scope.person1 = 'Igor';
  30086. $scope.person2 = 'Misko';
  30087. $scope.personCount = 1;
  30088. }]);
  30089. </script>
  30090. <div ng-controller="ExampleController">
  30091. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  30092. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  30093. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  30094. <!--- Example with simple pluralization rules for en locale --->
  30095. Without Offset:
  30096. <ng-pluralize count="personCount"
  30097. when="{'0': 'Nobody is viewing.',
  30098. 'one': '1 person is viewing.',
  30099. 'other': '{} people are viewing.'}">
  30100. </ng-pluralize><br>
  30101. <!--- Example with offset --->
  30102. With Offset(2):
  30103. <ng-pluralize count="personCount" offset=2
  30104. when="{'0': 'Nobody is viewing.',
  30105. '1': '{{person1}} is viewing.',
  30106. '2': '{{person1}} and {{person2}} are viewing.',
  30107. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  30108. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  30109. </ng-pluralize>
  30110. </div>
  30111. </file>
  30112. <file name="protractor.js" type="protractor">
  30113. it('should show correct pluralized string', function() {
  30114. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  30115. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  30116. var countInput = element(by.model('personCount'));
  30117. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  30118. expect(withOffset.getText()).toEqual('Igor is viewing.');
  30119. countInput.clear();
  30120. countInput.sendKeys('0');
  30121. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  30122. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  30123. countInput.clear();
  30124. countInput.sendKeys('2');
  30125. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  30126. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  30127. countInput.clear();
  30128. countInput.sendKeys('3');
  30129. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  30130. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  30131. countInput.clear();
  30132. countInput.sendKeys('4');
  30133. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  30134. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  30135. });
  30136. it('should show data-bound names', function() {
  30137. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  30138. var personCount = element(by.model('personCount'));
  30139. var person1 = element(by.model('person1'));
  30140. var person2 = element(by.model('person2'));
  30141. personCount.clear();
  30142. personCount.sendKeys('4');
  30143. person1.clear();
  30144. person1.sendKeys('Di');
  30145. person2.clear();
  30146. person2.sendKeys('Vojta');
  30147. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  30148. });
  30149. </file>
  30150. </example>
  30151. */
  30152. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  30153. var BRACE = /{}/g,
  30154. IS_WHEN = /^when(Minus)?(.+)$/;
  30155. return {
  30156. link: function(scope, element, attr) {
  30157. var numberExp = attr.count,
  30158. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  30159. offset = attr.offset || 0,
  30160. whens = scope.$eval(whenExp) || {},
  30161. whensExpFns = {},
  30162. startSymbol = $interpolate.startSymbol(),
  30163. endSymbol = $interpolate.endSymbol(),
  30164. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  30165. watchRemover = angular.noop,
  30166. lastCount;
  30167. forEach(attr, function(expression, attributeName) {
  30168. var tmpMatch = IS_WHEN.exec(attributeName);
  30169. if (tmpMatch) {
  30170. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  30171. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  30172. }
  30173. });
  30174. forEach(whens, function(expression, key) {
  30175. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  30176. });
  30177. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  30178. var count = parseFloat(newVal);
  30179. var countIsNaN = isNumberNaN(count);
  30180. if (!countIsNaN && !(count in whens)) {
  30181. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  30182. // Otherwise, check it against pluralization rules in $locale service.
  30183. count = $locale.pluralCat(count - offset);
  30184. }
  30185. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  30186. // In JS `NaN !== NaN`, so we have to explicitly check.
  30187. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  30188. watchRemover();
  30189. var whenExpFn = whensExpFns[count];
  30190. if (isUndefined(whenExpFn)) {
  30191. if (newVal != null) {
  30192. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  30193. }
  30194. watchRemover = noop;
  30195. updateElementText();
  30196. } else {
  30197. watchRemover = scope.$watch(whenExpFn, updateElementText);
  30198. }
  30199. lastCount = count;
  30200. }
  30201. });
  30202. function updateElementText(newText) {
  30203. element.text(newText || '');
  30204. }
  30205. }
  30206. };
  30207. }];
  30208. /**
  30209. * @ngdoc directive
  30210. * @name ngRef
  30211. * @restrict A
  30212. *
  30213. * @description
  30214. * The `ngRef` attribute tells AngularJS to assign the controller of a component (or a directive)
  30215. * to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM
  30216. * element to the scope.
  30217. *
  30218. * If the element with `ngRef` is destroyed `null` is assigned to the property.
  30219. *
  30220. * Note that if you want to assign from a child into the parent scope, you must initialize the
  30221. * target property on the parent scope, otherwise `ngRef` will assign on the child scope.
  30222. * This commonly happens when assigning elements or components wrapped in {@link ngIf} or
  30223. * {@link ngRepeat}. See the second example below.
  30224. *
  30225. *
  30226. * @element ANY
  30227. * @param {string} ngRef property name - A valid AngularJS expression identifier to which the
  30228. * controller or jqlite-wrapped DOM element will be bound.
  30229. * @param {string=} ngRefRead read value - The name of a directive (or component) on this element,
  30230. * or the special string `$element`. If a name is provided, `ngRef` will
  30231. * assign the matching controller. If `$element` is provided, the element
  30232. * itself is assigned (even if a controller is available).
  30233. *
  30234. *
  30235. * @example
  30236. * ### Simple toggle
  30237. * This example shows how the controller of the component toggle
  30238. * is reused in the template through the scope to use its logic.
  30239. * <example name="ng-ref-component" module="myApp">
  30240. * <file name="index.html">
  30241. * <my-toggle ng-ref="myToggle"></my-toggle>
  30242. * <button ng-click="myToggle.toggle()">Toggle</button>
  30243. * <div ng-show="myToggle.isOpen()">
  30244. * You are using a component in the same template to show it.
  30245. * </div>
  30246. * </file>
  30247. * <file name="index.js">
  30248. * angular.module('myApp', [])
  30249. * .component('myToggle', {
  30250. * controller: function ToggleController() {
  30251. * var opened = false;
  30252. * this.isOpen = function() { return opened; };
  30253. * this.toggle = function() { opened = !opened; };
  30254. * }
  30255. * });
  30256. * </file>
  30257. * <file name="protractor.js" type="protractor">
  30258. * it('should publish the toggle into the scope', function() {
  30259. * var toggle = element(by.buttonText('Toggle'));
  30260. * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(false);
  30261. * toggle.click();
  30262. * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(true);
  30263. * });
  30264. * </file>
  30265. * </example>
  30266. *
  30267. * @example
  30268. * ### ngRef inside scopes
  30269. * This example shows how `ngRef` works with child scopes. The `ngRepeat`-ed `myWrapper` components
  30270. * are assigned to the scope of `myRoot`, because the `toggles` property has been initialized.
  30271. * The repeated `myToggle` components are published to the child scopes created by `ngRepeat`.
  30272. * `ngIf` behaves similarly - the assignment of `myToggle` happens in the `ngIf` child scope,
  30273. * because the target property has not been initialized on the `myRoot` component controller.
  30274. *
  30275. * <example name="ng-ref-scopes" module="myApp">
  30276. * <file name="index.html">
  30277. * <my-root></my-root>
  30278. * </file>
  30279. * <file name="index.js">
  30280. * angular.module('myApp', [])
  30281. * .component('myRoot', {
  30282. * templateUrl: 'root.html',
  30283. * controller: function() {
  30284. * this.wrappers = []; // initialize the array so that the wrappers are assigned into the parent scope
  30285. * }
  30286. * })
  30287. * .component('myToggle', {
  30288. * template: '<strong>myToggle</strong><button ng-click="$ctrl.toggle()" ng-transclude></button>',
  30289. * transclude: true,
  30290. * controller: function ToggleController() {
  30291. * var opened = false;
  30292. * this.isOpen = function() { return opened; };
  30293. * this.toggle = function() { opened = !opened; };
  30294. * }
  30295. * })
  30296. * .component('myWrapper', {
  30297. * transclude: true,
  30298. * template: '<strong>myWrapper</strong>' +
  30299. * '<div>ngRepeatToggle.isOpen(): {{$ctrl.ngRepeatToggle.isOpen() | json}}</div>' +
  30300. * '<my-toggle ng-ref="$ctrl.ngRepeatToggle"><ng-transclude></ng-transclude></my-toggle>'
  30301. * });
  30302. * </file>
  30303. * <file name="root.html">
  30304. * <strong>myRoot</strong>
  30305. * <my-toggle ng-ref="$ctrl.outerToggle">Outer Toggle</my-toggle>
  30306. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30307. * <div><em>wrappers assigned to root</em><br>
  30308. * <div ng-repeat="wrapper in $ctrl.wrappers">
  30309. * wrapper.ngRepeatToggle.isOpen(): {{wrapper.ngRepeatToggle.isOpen() | json}}
  30310. * </div>
  30311. *
  30312. * <ul>
  30313. * <li ng-repeat="(index, value) in [1,2,3]">
  30314. * <strong>ngRepeat</strong>
  30315. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30316. * <my-wrapper ng-ref="$ctrl.wrappers[index]">ngRepeat Toggle {{$index + 1}}</my-wrapper>
  30317. * </li>
  30318. * </ul>
  30319. *
  30320. * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen()}} // This is always undefined because it's
  30321. * assigned to the child scope created by ngIf.
  30322. * </div>
  30323. * <div ng-if="true">
  30324. <strong>ngIf</strong>
  30325. * <my-toggle ng-ref="ngIfToggle">ngIf Toggle</my-toggle>
  30326. * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen() | json}}</div>
  30327. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30328. * </div>
  30329. * </file>
  30330. * <file name="styles.css">
  30331. * ul {
  30332. * list-style: none;
  30333. * padding-left: 0;
  30334. * }
  30335. *
  30336. * li[ng-repeat] {
  30337. * background: lightgreen;
  30338. * padding: 8px;
  30339. * margin: 8px;
  30340. * }
  30341. *
  30342. * [ng-if] {
  30343. * background: lightgrey;
  30344. * padding: 8px;
  30345. * }
  30346. *
  30347. * my-root {
  30348. * background: lightgoldenrodyellow;
  30349. * padding: 8px;
  30350. * display: block;
  30351. * }
  30352. *
  30353. * my-wrapper {
  30354. * background: lightsalmon;
  30355. * padding: 8px;
  30356. * display: block;
  30357. * }
  30358. *
  30359. * my-toggle {
  30360. * background: lightblue;
  30361. * padding: 8px;
  30362. * display: block;
  30363. * }
  30364. * </file>
  30365. * <file name="protractor.js" type="protractor">
  30366. * var OuterToggle = function() {
  30367. * this.toggle = function() {
  30368. * element(by.buttonText('Outer Toggle')).click();
  30369. * };
  30370. * this.isOpen = function() {
  30371. * return element.all(by.binding('outerToggle.isOpen()')).first().getText();
  30372. * };
  30373. * };
  30374. * var NgRepeatToggle = function(i) {
  30375. * var parent = element.all(by.repeater('(index, value) in [1,2,3]')).get(i - 1);
  30376. * this.toggle = function() {
  30377. * element(by.buttonText('ngRepeat Toggle ' + i)).click();
  30378. * };
  30379. * this.isOpen = function() {
  30380. * return parent.element(by.binding('ngRepeatToggle.isOpen() | json')).getText();
  30381. * };
  30382. * this.isOuterOpen = function() {
  30383. * return parent.element(by.binding('outerToggle.isOpen() | json')).getText();
  30384. * };
  30385. * };
  30386. * var NgRepeatToggles = function() {
  30387. * var toggles = [1,2,3].map(function(i) { return new NgRepeatToggle(i); });
  30388. * this.forEach = function(fn) {
  30389. * toggles.forEach(fn);
  30390. * };
  30391. * this.isOuterOpen = function(i) {
  30392. * return toggles[i - 1].isOuterOpen();
  30393. * };
  30394. * };
  30395. * var NgIfToggle = function() {
  30396. * var parent = element(by.css('[ng-if]'));
  30397. * this.toggle = function() {
  30398. * element(by.buttonText('ngIf Toggle')).click();
  30399. * };
  30400. * this.isOpen = function() {
  30401. * return by.binding('ngIfToggle.isOpen() | json').getText();
  30402. * };
  30403. * this.isOuterOpen = function() {
  30404. * return parent.element(by.binding('outerToggle.isOpen() | json')).getText();
  30405. * };
  30406. * };
  30407. *
  30408. * it('should toggle the outer toggle', function() {
  30409. * var outerToggle = new OuterToggle();
  30410. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');
  30411. * outerToggle.toggle();
  30412. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');
  30413. * });
  30414. *
  30415. * it('should toggle all outer toggles', function() {
  30416. * var outerToggle = new OuterToggle();
  30417. * var repeatToggles = new NgRepeatToggles();
  30418. * var ifToggle = new NgIfToggle();
  30419. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');
  30420. * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): false');
  30421. * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): false');
  30422. * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): false');
  30423. * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30424. * outerToggle.toggle();
  30425. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');
  30426. * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): true');
  30427. * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): true');
  30428. * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): true');
  30429. * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): true');
  30430. * });
  30431. *
  30432. * it('should toggle each repeat iteration separately', function() {
  30433. * var repeatToggles = new NgRepeatToggles();
  30434. *
  30435. * repeatToggles.forEach(function(repeatToggle) {
  30436. * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): false');
  30437. * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30438. * repeatToggle.toggle();
  30439. * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): true');
  30440. * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30441. * });
  30442. * });
  30443. * </file>
  30444. * </example>
  30445. *
  30446. */
  30447. var ngRefMinErr = minErr('ngRef');
  30448. var ngRefDirective = ['$parse', function($parse) {
  30449. return {
  30450. priority: -1, // Needed for compatibility with element transclusion on the same element
  30451. restrict: 'A',
  30452. compile: function(tElement, tAttrs) {
  30453. // Get the expected controller name, converts <data-some-thing> into "someThing"
  30454. var controllerName = directiveNormalize(nodeName_(tElement));
  30455. // Get the expression for value binding
  30456. var getter = $parse(tAttrs.ngRef);
  30457. var setter = getter.assign || function() {
  30458. throw ngRefMinErr('nonassign', 'Expression in ngRef="{0}" is non-assignable!', tAttrs.ngRef);
  30459. };
  30460. return function(scope, element, attrs) {
  30461. var refValue;
  30462. if (attrs.hasOwnProperty('ngRefRead')) {
  30463. if (attrs.ngRefRead === '$element') {
  30464. refValue = element;
  30465. } else {
  30466. refValue = element.data('$' + attrs.ngRefRead + 'Controller');
  30467. if (!refValue) {
  30468. throw ngRefMinErr(
  30469. 'noctrl',
  30470. 'The controller for ngRefRead="{0}" could not be found on ngRef="{1}"',
  30471. attrs.ngRefRead,
  30472. tAttrs.ngRef
  30473. );
  30474. }
  30475. }
  30476. } else {
  30477. refValue = element.data('$' + controllerName + 'Controller');
  30478. }
  30479. refValue = refValue || element;
  30480. setter(scope, refValue);
  30481. // when the element is removed, remove it (nullify it)
  30482. element.on('$destroy', function() {
  30483. // only remove it if value has not changed,
  30484. // because animations (and other procedures) may duplicate elements
  30485. if (getter(scope) === refValue) {
  30486. setter(scope, null);
  30487. }
  30488. });
  30489. };
  30490. }
  30491. };
  30492. }];
  30493. /* exported ngRepeatDirective */
  30494. /**
  30495. * @ngdoc directive
  30496. * @name ngRepeat
  30497. * @multiElement
  30498. * @restrict A
  30499. *
  30500. * @description
  30501. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  30502. * instance gets its own scope, where the given loop variable is set to the current collection item,
  30503. * and `$index` is set to the item index or key.
  30504. *
  30505. * Special properties are exposed on the local scope of each template instance, including:
  30506. *
  30507. * | Variable | Type | Details |
  30508. * |-----------|-----------------|-----------------------------------------------------------------------------|
  30509. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  30510. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  30511. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  30512. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  30513. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  30514. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  30515. *
  30516. * <div class="alert alert-info">
  30517. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  30518. * This may be useful when, for instance, nesting ngRepeats.
  30519. * </div>
  30520. *
  30521. *
  30522. * ## Iterating over object properties
  30523. *
  30524. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  30525. * syntax:
  30526. *
  30527. * ```js
  30528. * <div ng-repeat="(key, value) in myObj"> ... </div>
  30529. * ```
  30530. *
  30531. * However, there are a few limitations compared to array iteration:
  30532. *
  30533. * - The JavaScript specification does not define the order of keys
  30534. * returned for an object, so AngularJS relies on the order returned by the browser
  30535. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  30536. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  30537. * and reinstated. See the
  30538. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  30539. *
  30540. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  30541. * it's a prefix used by AngularJS for public (`$`) and private (`$$`) properties.
  30542. *
  30543. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  30544. * objects, and will throw an error if used with one.
  30545. *
  30546. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  30547. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  30548. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  30549. * or implement a `$watch` on the object yourself.
  30550. *
  30551. *
  30552. * ## Tracking and Duplicates
  30553. *
  30554. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  30555. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  30556. *
  30557. * * When an item is added, a new instance of the template is added to the DOM.
  30558. * * When an item is removed, its template instance is removed from the DOM.
  30559. * * When items are reordered, their respective templates are reordered in the DOM.
  30560. *
  30561. * To minimize creation of DOM elements, `ngRepeat` uses a function
  30562. * to "keep track" of all items in the collection and their corresponding DOM elements.
  30563. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  30564. * already have DOM elements, and will not re-render them.
  30565. *
  30566. * All different types of tracking functions, their syntax, and their support for duplicate
  30567. * items in collections can be found in the
  30568. * {@link ngRepeat#ngRepeat-arguments ngRepeat expression description}.
  30569. *
  30570. * <div class="alert alert-success">
  30571. * **Best Practice:** If you are working with objects that have a unique identifier property, you
  30572. * should track by this identifier instead of the object instance,
  30573. * e.g. `item in items track by item.id`.
  30574. * Should you reload your data later, `ngRepeat` will not have to rebuild the DOM elements for items
  30575. * it has already rendered, even if the JavaScript objects in the collection have been substituted
  30576. * for new ones. For large collections, this significantly improves rendering performance.
  30577. * </div>
  30578. *
  30579. * ### Effects of DOM Element re-use
  30580. *
  30581. * When DOM elements are re-used, ngRepeat updates the scope for the element, which will
  30582. * automatically update any active bindings on the template. However, other
  30583. * functionality will not be updated, because the element is not re-created:
  30584. *
  30585. * - Directives are not re-compiled
  30586. * - {@link guide/expression#one-time-binding one-time expressions} on the repeated template are not
  30587. * updated if they have stabilized.
  30588. *
  30589. * The above affects all kinds of element re-use due to tracking, but may be especially visible
  30590. * when tracking by `$index` due to the way ngRepeat re-uses elements.
  30591. *
  30592. * The following example shows the effects of different actions with tracking:
  30593. <example module="ngRepeat" name="ngRepeat-tracking" deps="angular-animate.js" animations="true">
  30594. <file name="script.js">
  30595. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  30596. var friends = [
  30597. {name:'John', age:25},
  30598. {name:'Mary', age:40},
  30599. {name:'Peter', age:85}
  30600. ];
  30601. $scope.removeFirst = function() {
  30602. $scope.friends.shift();
  30603. };
  30604. $scope.updateAge = function() {
  30605. $scope.friends.forEach(function(el) {
  30606. el.age = el.age + 5;
  30607. });
  30608. };
  30609. $scope.copy = function() {
  30610. $scope.friends = angular.copy($scope.friends);
  30611. };
  30612. $scope.reset = function() {
  30613. $scope.friends = angular.copy(friends);
  30614. };
  30615. $scope.reset();
  30616. });
  30617. </file>
  30618. <file name="index.html">
  30619. <div ng-controller="repeatController">
  30620. <ol>
  30621. <li>When you click "Update Age", only the first list updates the age, because all others have
  30622. a one-time binding on the age property. If you then click "Copy", the current friend list
  30623. is copied, and now the second list updates the age, because the identity of the collection items
  30624. has changed and the list must be re-rendered. The 3rd and 4th list stay the same, because all the
  30625. items are already known according to their tracking functions.
  30626. </li>
  30627. <li>When you click "Remove First", the 4th list has the wrong age on both remaining items. This is
  30628. due to tracking by $index: when the first collection item is removed, ngRepeat reuses the first
  30629. DOM element for the new first collection item, and so on. Since the age property is one-time
  30630. bound, the value remains from the collection item which was previously at this index.
  30631. </li>
  30632. </ol>
  30633. <button ng-click="removeFirst()">Remove First</button>
  30634. <button ng-click="updateAge()">Update Age</button>
  30635. <button ng-click="copy()">Copy</button>
  30636. <br><button ng-click="reset()">Reset List</button>
  30637. <br>
  30638. <code>track by $id(friend)</code> (default):
  30639. <ul class="example-animate-container">
  30640. <li class="animate-repeat" ng-repeat="friend in friends">
  30641. {{friend.name}} is {{friend.age}} years old.
  30642. </li>
  30643. </ul>
  30644. <code>track by $id(friend)</code> (default), with age one-time binding:
  30645. <ul class="example-animate-container">
  30646. <li class="animate-repeat" ng-repeat="friend in friends">
  30647. {{friend.name}} is {{::friend.age}} years old.
  30648. </li>
  30649. </ul>
  30650. <code>track by friend.name</code>, with age one-time binding:
  30651. <ul class="example-animate-container">
  30652. <li class="animate-repeat" ng-repeat="friend in friends track by friend.name">
  30653. {{friend.name}} is {{::friend.age}} years old.
  30654. </li>
  30655. </ul>
  30656. <code>track by $index</code>, with age one-time binding:
  30657. <ul class="example-animate-container">
  30658. <li class="animate-repeat" ng-repeat="friend in friends track by $index">
  30659. {{friend.name}} is {{::friend.age}} years old.
  30660. </li>
  30661. </ul>
  30662. </div>
  30663. </file>
  30664. <file name="animations.css">
  30665. .example-animate-container {
  30666. background:white;
  30667. border:1px solid black;
  30668. list-style:none;
  30669. margin:0;
  30670. padding:0 10px;
  30671. }
  30672. .animate-repeat {
  30673. line-height:30px;
  30674. list-style:none;
  30675. box-sizing:border-box;
  30676. }
  30677. .animate-repeat.ng-move,
  30678. .animate-repeat.ng-enter,
  30679. .animate-repeat.ng-leave {
  30680. transition:all linear 0.5s;
  30681. }
  30682. .animate-repeat.ng-leave.ng-leave-active,
  30683. .animate-repeat.ng-move,
  30684. .animate-repeat.ng-enter {
  30685. opacity:0;
  30686. max-height:0;
  30687. }
  30688. .animate-repeat.ng-leave,
  30689. .animate-repeat.ng-move.ng-move-active,
  30690. .animate-repeat.ng-enter.ng-enter-active {
  30691. opacity:1;
  30692. max-height:30px;
  30693. }
  30694. </file>
  30695. </example>
  30696. *
  30697. * ## Special repeat start and end points
  30698. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  30699. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  30700. * 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)
  30701. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  30702. *
  30703. * The example below makes use of this feature:
  30704. * ```html
  30705. * <header ng-repeat-start="item in items">
  30706. * Header {{ item }}
  30707. * </header>
  30708. * <div class="body">
  30709. * Body {{ item }}
  30710. * </div>
  30711. * <footer ng-repeat-end>
  30712. * Footer {{ item }}
  30713. * </footer>
  30714. * ```
  30715. *
  30716. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  30717. * ```html
  30718. * <header>
  30719. * Header A
  30720. * </header>
  30721. * <div class="body">
  30722. * Body A
  30723. * </div>
  30724. * <footer>
  30725. * Footer A
  30726. * </footer>
  30727. * <header>
  30728. * Header B
  30729. * </header>
  30730. * <div class="body">
  30731. * Body B
  30732. * </div>
  30733. * <footer>
  30734. * Footer B
  30735. * </footer>
  30736. * ```
  30737. *
  30738. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  30739. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  30740. *
  30741. * @animations
  30742. * | Animation | Occurs |
  30743. * |----------------------------------|-------------------------------------|
  30744. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  30745. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  30746. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  30747. *
  30748. * See the example below for defining CSS animations with ngRepeat.
  30749. *
  30750. * @element ANY
  30751. * @scope
  30752. * @priority 1000
  30753. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  30754. * formats are currently supported:
  30755. *
  30756. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  30757. * is a scope expression giving the collection to enumerate.
  30758. *
  30759. * For example: `album in artist.albums`.
  30760. *
  30761. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  30762. * and `expression` is the scope expression giving the collection to enumerate.
  30763. *
  30764. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  30765. *
  30766. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  30767. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  30768. * is specified, ng-repeat associates elements by identity. It is an error to have
  30769. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  30770. * mapped to the same DOM element, which is not possible.)
  30771. *
  30772. * *Default tracking: $id()*: `item in items` is equivalent to `item in items track by $id(item)`.
  30773. * This implies that the DOM elements will be associated by item identity in the collection.
  30774. *
  30775. * The built-in `$id()` function can be used to assign a unique
  30776. * `$$hashKey` property to each item in the collection. This property is then used as a key to associated DOM elements
  30777. * with the corresponding item in the collection by identity. Moving the same object would move
  30778. * the DOM element in the same way in the DOM.
  30779. * Note that the default id function does not support duplicate primitive values (`number`, `string`),
  30780. * but supports duplictae non-primitive values (`object`) that are *equal* in shape.
  30781. *
  30782. * *Custom Expression*: It is possible to use any AngularJS expression to compute the tracking
  30783. * id, for example with a function, or using a property on the collection items.
  30784. * `item in items track by item.id` is a typical pattern when the items have a unique identifier,
  30785. * e.g. database id. In this case the object identity does not matter. Two objects are considered
  30786. * equivalent as long as their `id` property is same.
  30787. * Tracking by unique identifier is the most performant way and should be used whenever possible.
  30788. *
  30789. * *$index*: This special property tracks the collection items by their index, and
  30790. * re-uses the DOM elements that match that index, e.g. `item in items track by $index`. This can
  30791. * be used for a performance improvement if no unique identfier is available and the identity of
  30792. * the collection items cannot be easily computed. It also allows duplicates.
  30793. *
  30794. * <div class="alert alert-warning">
  30795. * <strong>Note:</strong> Re-using DOM elements can have unforeseen effects. Read the
  30796. * {@link ngRepeat#tracking-and-duplicates section on tracking and duplicates} for
  30797. * more info.
  30798. * </div>
  30799. *
  30800. * <div class="alert alert-warning">
  30801. * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression:
  30802. * `item in items | filter:searchText as results track by item.id`
  30803. * </div>
  30804. *
  30805. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  30806. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  30807. * when a filter is active on the repeater, but the filtered result set is empty.
  30808. *
  30809. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  30810. * the items have been processed through the filter.
  30811. *
  30812. * Please note that `as [variable name]` is not an operator but rather a part of ngRepeat
  30813. * micro-syntax so it can be used only after all filters (and not as operator, inside an expression).
  30814. *
  30815. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results track by item.id` .
  30816. *
  30817. * @example
  30818. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  30819. * results by name or by age. New (entering) and removed (leaving) items are animated.
  30820. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  30821. <file name="index.html">
  30822. <div ng-controller="repeatController">
  30823. I have {{friends.length}} friends. They are:
  30824. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  30825. <ul class="example-animate-container">
  30826. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results track by friend.name">
  30827. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  30828. </li>
  30829. <li class="animate-repeat" ng-if="results.length === 0">
  30830. <strong>No results found...</strong>
  30831. </li>
  30832. </ul>
  30833. </div>
  30834. </file>
  30835. <file name="script.js">
  30836. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  30837. $scope.friends = [
  30838. {name:'John', age:25, gender:'boy'},
  30839. {name:'Jessie', age:30, gender:'girl'},
  30840. {name:'Johanna', age:28, gender:'girl'},
  30841. {name:'Joy', age:15, gender:'girl'},
  30842. {name:'Mary', age:28, gender:'girl'},
  30843. {name:'Peter', age:95, gender:'boy'},
  30844. {name:'Sebastian', age:50, gender:'boy'},
  30845. {name:'Erika', age:27, gender:'girl'},
  30846. {name:'Patrick', age:40, gender:'boy'},
  30847. {name:'Samantha', age:60, gender:'girl'}
  30848. ];
  30849. });
  30850. </file>
  30851. <file name="animations.css">
  30852. .example-animate-container {
  30853. background:white;
  30854. border:1px solid black;
  30855. list-style:none;
  30856. margin:0;
  30857. padding:0 10px;
  30858. }
  30859. .animate-repeat {
  30860. line-height:30px;
  30861. list-style:none;
  30862. box-sizing:border-box;
  30863. }
  30864. .animate-repeat.ng-move,
  30865. .animate-repeat.ng-enter,
  30866. .animate-repeat.ng-leave {
  30867. transition:all linear 0.5s;
  30868. }
  30869. .animate-repeat.ng-leave.ng-leave-active,
  30870. .animate-repeat.ng-move,
  30871. .animate-repeat.ng-enter {
  30872. opacity:0;
  30873. max-height:0;
  30874. }
  30875. .animate-repeat.ng-leave,
  30876. .animate-repeat.ng-move.ng-move-active,
  30877. .animate-repeat.ng-enter.ng-enter-active {
  30878. opacity:1;
  30879. max-height:30px;
  30880. }
  30881. </file>
  30882. <file name="protractor.js" type="protractor">
  30883. var friends = element.all(by.repeater('friend in friends'));
  30884. it('should render initial data set', function() {
  30885. expect(friends.count()).toBe(10);
  30886. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  30887. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  30888. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  30889. expect(element(by.binding('friends.length')).getText())
  30890. .toMatch("I have 10 friends. They are:");
  30891. });
  30892. it('should update repeater when filter predicate changes', function() {
  30893. expect(friends.count()).toBe(10);
  30894. element(by.model('q')).sendKeys('ma');
  30895. expect(friends.count()).toBe(2);
  30896. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  30897. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  30898. });
  30899. </file>
  30900. </example>
  30901. */
  30902. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  30903. var NG_REMOVED = '$$NG_REMOVED';
  30904. var ngRepeatMinErr = minErr('ngRepeat');
  30905. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  30906. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  30907. scope[valueIdentifier] = value;
  30908. if (keyIdentifier) scope[keyIdentifier] = key;
  30909. scope.$index = index;
  30910. scope.$first = (index === 0);
  30911. scope.$last = (index === (arrayLength - 1));
  30912. scope.$middle = !(scope.$first || scope.$last);
  30913. // eslint-disable-next-line no-bitwise
  30914. scope.$odd = !(scope.$even = (index & 1) === 0);
  30915. };
  30916. var getBlockStart = function(block) {
  30917. return block.clone[0];
  30918. };
  30919. var getBlockEnd = function(block) {
  30920. return block.clone[block.clone.length - 1];
  30921. };
  30922. var trackByIdArrayFn = function($scope, key, value) {
  30923. return hashKey(value);
  30924. };
  30925. var trackByIdObjFn = function($scope, key) {
  30926. return key;
  30927. };
  30928. return {
  30929. restrict: 'A',
  30930. multiElement: true,
  30931. transclude: 'element',
  30932. priority: 1000,
  30933. terminal: true,
  30934. $$tlb: true,
  30935. compile: function ngRepeatCompile($element, $attr) {
  30936. var expression = $attr.ngRepeat;
  30937. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  30938. 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*$/);
  30939. if (!match) {
  30940. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  30941. expression);
  30942. }
  30943. var lhs = match[1];
  30944. var rhs = match[2];
  30945. var aliasAs = match[3];
  30946. var trackByExp = match[4];
  30947. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  30948. if (!match) {
  30949. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  30950. lhs);
  30951. }
  30952. var valueIdentifier = match[3] || match[1];
  30953. var keyIdentifier = match[2];
  30954. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  30955. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  30956. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  30957. aliasAs);
  30958. }
  30959. var trackByIdExpFn;
  30960. if (trackByExp) {
  30961. var hashFnLocals = {$id: hashKey};
  30962. var trackByExpGetter = $parse(trackByExp);
  30963. trackByIdExpFn = function($scope, key, value, index) {
  30964. // assign key, value, and $index to the locals so that they can be used in hash functions
  30965. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  30966. hashFnLocals[valueIdentifier] = value;
  30967. hashFnLocals.$index = index;
  30968. return trackByExpGetter($scope, hashFnLocals);
  30969. };
  30970. }
  30971. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  30972. // Store a list of elements from previous run. This is a hash where key is the item from the
  30973. // iterator, and the value is objects with following properties.
  30974. // - scope: bound scope
  30975. // - clone: previous element.
  30976. // - index: position
  30977. //
  30978. // We are using no-proto object so that we don't need to guard against inherited props via
  30979. // hasOwnProperty.
  30980. var lastBlockMap = createMap();
  30981. //watch props
  30982. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  30983. var index, length,
  30984. previousNode = $element[0], // node that cloned nodes should be inserted after
  30985. // initialized to the comment node anchor
  30986. nextNode,
  30987. // Same as lastBlockMap but it has the current state. It will become the
  30988. // lastBlockMap on the next iteration.
  30989. nextBlockMap = createMap(),
  30990. collectionLength,
  30991. key, value, // key/value of iteration
  30992. trackById,
  30993. trackByIdFn,
  30994. collectionKeys,
  30995. block, // last object information {scope, element, id}
  30996. nextBlockOrder,
  30997. elementsToRemove;
  30998. if (aliasAs) {
  30999. $scope[aliasAs] = collection;
  31000. }
  31001. if (isArrayLike(collection)) {
  31002. collectionKeys = collection;
  31003. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  31004. } else {
  31005. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  31006. // if object, extract keys, in enumeration order, unsorted
  31007. collectionKeys = [];
  31008. for (var itemKey in collection) {
  31009. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  31010. collectionKeys.push(itemKey);
  31011. }
  31012. }
  31013. }
  31014. collectionLength = collectionKeys.length;
  31015. nextBlockOrder = new Array(collectionLength);
  31016. // locate existing items
  31017. for (index = 0; index < collectionLength; index++) {
  31018. key = (collection === collectionKeys) ? index : collectionKeys[index];
  31019. value = collection[key];
  31020. trackById = trackByIdFn($scope, key, value, index);
  31021. if (lastBlockMap[trackById]) {
  31022. // found previously seen block
  31023. block = lastBlockMap[trackById];
  31024. delete lastBlockMap[trackById];
  31025. nextBlockMap[trackById] = block;
  31026. nextBlockOrder[index] = block;
  31027. } else if (nextBlockMap[trackById]) {
  31028. // if collision detected. restore lastBlockMap and throw an error
  31029. forEach(nextBlockOrder, function(block) {
  31030. if (block && block.scope) lastBlockMap[block.id] = block;
  31031. });
  31032. throw ngRepeatMinErr('dupes',
  31033. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  31034. expression, trackById, value);
  31035. } else {
  31036. // new never before seen block
  31037. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  31038. nextBlockMap[trackById] = true;
  31039. }
  31040. }
  31041. // Clear the value property from the hashFnLocals object to prevent a reference to the last value
  31042. // being leaked into the ngRepeatCompile function scope
  31043. if (hashFnLocals) {
  31044. hashFnLocals[valueIdentifier] = undefined;
  31045. }
  31046. // remove leftover items
  31047. for (var blockKey in lastBlockMap) {
  31048. block = lastBlockMap[blockKey];
  31049. elementsToRemove = getBlockNodes(block.clone);
  31050. $animate.leave(elementsToRemove);
  31051. if (elementsToRemove[0].parentNode) {
  31052. // if the element was not removed yet because of pending animation, mark it as deleted
  31053. // so that we can ignore it later
  31054. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  31055. elementsToRemove[index][NG_REMOVED] = true;
  31056. }
  31057. }
  31058. block.scope.$destroy();
  31059. }
  31060. // we are not using forEach for perf reasons (trying to avoid #call)
  31061. for (index = 0; index < collectionLength; index++) {
  31062. key = (collection === collectionKeys) ? index : collectionKeys[index];
  31063. value = collection[key];
  31064. block = nextBlockOrder[index];
  31065. if (block.scope) {
  31066. // if we have already seen this object, then we need to reuse the
  31067. // associated scope/element
  31068. nextNode = previousNode;
  31069. // skip nodes that are already pending removal via leave animation
  31070. do {
  31071. nextNode = nextNode.nextSibling;
  31072. } while (nextNode && nextNode[NG_REMOVED]);
  31073. if (getBlockStart(block) !== nextNode) {
  31074. // existing item which got moved
  31075. $animate.move(getBlockNodes(block.clone), null, previousNode);
  31076. }
  31077. previousNode = getBlockEnd(block);
  31078. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  31079. } else {
  31080. // new item which we don't know about
  31081. $transclude(function ngRepeatTransclude(clone, scope) {
  31082. block.scope = scope;
  31083. // http://jsperf.com/clone-vs-createcomment
  31084. var endNode = ngRepeatEndComment.cloneNode(false);
  31085. clone[clone.length++] = endNode;
  31086. $animate.enter(clone, null, previousNode);
  31087. previousNode = endNode;
  31088. // Note: We only need the first/last node of the cloned nodes.
  31089. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  31090. // by a directive with templateUrl when its template arrives.
  31091. block.clone = clone;
  31092. nextBlockMap[block.id] = block;
  31093. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  31094. });
  31095. }
  31096. }
  31097. lastBlockMap = nextBlockMap;
  31098. });
  31099. };
  31100. }
  31101. };
  31102. }];
  31103. var NG_HIDE_CLASS = 'ng-hide';
  31104. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  31105. /**
  31106. * @ngdoc directive
  31107. * @name ngShow
  31108. * @multiElement
  31109. *
  31110. * @description
  31111. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  31112. * the `ngShow` attribute.
  31113. *
  31114. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  31115. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  31116. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  31117. * {@link ng.directive:ngCsp ngCsp}).
  31118. *
  31119. * ```html
  31120. * <!-- when $scope.myValue is truthy (element is visible) -->
  31121. * <div ng-show="myValue"></div>
  31122. *
  31123. * <!-- when $scope.myValue is falsy (element is hidden) -->
  31124. * <div ng-show="myValue" class="ng-hide"></div>
  31125. * ```
  31126. *
  31127. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  31128. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  31129. * CSS class is removed from the element causing the element not to appear hidden.
  31130. *
  31131. * ## Why is `!important` used?
  31132. *
  31133. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  31134. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  31135. * simple as changing the display style on a HTML list item would make hidden elements appear
  31136. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  31137. *
  31138. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  31139. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  31140. * developer chooses to override the styling to change how to hide an element then it is just a
  31141. * matter of using `!important` in their own CSS code.
  31142. *
  31143. * ### Overriding `.ng-hide`
  31144. *
  31145. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  31146. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  31147. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  31148. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  31149. *
  31150. * ```css
  31151. * .ng-hide:not(.ng-hide-animate) {
  31152. * /&#42; These are just alternative ways of hiding an element &#42;/
  31153. * display: block!important;
  31154. * position: absolute;
  31155. * top: -9999px;
  31156. * left: -9999px;
  31157. * }
  31158. * ```
  31159. *
  31160. * By default you don't need to override anything in CSS and the animations will work around the
  31161. * display style.
  31162. *
  31163. * @animations
  31164. * | Animation | Occurs |
  31165. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  31166. * | {@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. |
  31167. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  31168. *
  31169. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  31170. * directive expression is true and false. This system works like the animation system present with
  31171. * `ngClass` except that you must also include the `!important` flag to override the display
  31172. * property so that the elements are not actually hidden during the animation.
  31173. *
  31174. * ```css
  31175. * /&#42; A working example can be found at the bottom of this page. &#42;/
  31176. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  31177. * transition: all 0.5s linear;
  31178. * }
  31179. *
  31180. * .my-element.ng-hide-add { ... }
  31181. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  31182. * .my-element.ng-hide-remove { ... }
  31183. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  31184. * ```
  31185. *
  31186. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  31187. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  31188. *
  31189. * @element ANY
  31190. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  31191. * element is shown/hidden respectively.
  31192. *
  31193. * @example
  31194. * A simple example, animating the element's opacity:
  31195. *
  31196. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  31197. <file name="index.html">
  31198. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  31199. <div class="check-element animate-show-hide" ng-show="checked">
  31200. I show up when your checkbox is checked.
  31201. </div>
  31202. </file>
  31203. <file name="animations.css">
  31204. .animate-show-hide.ng-hide {
  31205. opacity: 0;
  31206. }
  31207. .animate-show-hide.ng-hide-add,
  31208. .animate-show-hide.ng-hide-remove {
  31209. transition: all linear 0.5s;
  31210. }
  31211. .check-element {
  31212. border: 1px solid black;
  31213. opacity: 1;
  31214. padding: 10px;
  31215. }
  31216. </file>
  31217. <file name="protractor.js" type="protractor">
  31218. it('should check ngShow', function() {
  31219. var checkbox = element(by.model('checked'));
  31220. var checkElem = element(by.css('.check-element'));
  31221. expect(checkElem.isDisplayed()).toBe(false);
  31222. checkbox.click();
  31223. expect(checkElem.isDisplayed()).toBe(true);
  31224. });
  31225. </file>
  31226. </example>
  31227. *
  31228. * <hr />
  31229. * @example
  31230. * A more complex example, featuring different show/hide animations:
  31231. *
  31232. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  31233. <file name="index.html">
  31234. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  31235. <div class="check-element funky-show-hide" ng-show="checked">
  31236. I show up when your checkbox is checked.
  31237. </div>
  31238. </file>
  31239. <file name="animations.css">
  31240. body {
  31241. overflow: hidden;
  31242. perspective: 1000px;
  31243. }
  31244. .funky-show-hide.ng-hide-add {
  31245. transform: rotateZ(0);
  31246. transform-origin: right;
  31247. transition: all 0.5s ease-in-out;
  31248. }
  31249. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  31250. transform: rotateZ(-135deg);
  31251. }
  31252. .funky-show-hide.ng-hide-remove {
  31253. transform: rotateY(90deg);
  31254. transform-origin: left;
  31255. transition: all 0.5s ease;
  31256. }
  31257. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  31258. transform: rotateY(0);
  31259. }
  31260. .check-element {
  31261. border: 1px solid black;
  31262. opacity: 1;
  31263. padding: 10px;
  31264. }
  31265. </file>
  31266. <file name="protractor.js" type="protractor">
  31267. it('should check ngShow', function() {
  31268. var checkbox = element(by.model('checked'));
  31269. var checkElem = element(by.css('.check-element'));
  31270. expect(checkElem.isDisplayed()).toBe(false);
  31271. checkbox.click();
  31272. expect(checkElem.isDisplayed()).toBe(true);
  31273. });
  31274. </file>
  31275. </example>
  31276. *
  31277. * @knownIssue
  31278. *
  31279. * ### Flickering when using ngShow to toggle between elements
  31280. *
  31281. * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
  31282. * happen that both the element to show and the element to hide are visible for a very short time.
  31283. *
  31284. * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
  31285. * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
  31286. * other browsers.
  31287. *
  31288. * There are several way to mitigate this problem:
  31289. *
  31290. * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
  31291. * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
  31292. * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
  31293. * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
  31294. * - Define an animation on the affected elements.
  31295. */
  31296. var ngShowDirective = ['$animate', function($animate) {
  31297. return {
  31298. restrict: 'A',
  31299. multiElement: true,
  31300. link: function(scope, element, attr) {
  31301. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  31302. // we're adding a temporary, animation-specific class for ng-hide since this way
  31303. // we can control when the element is actually displayed on screen without having
  31304. // to have a global/greedy CSS selector that breaks when other animations are run.
  31305. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  31306. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  31307. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  31308. });
  31309. });
  31310. }
  31311. };
  31312. }];
  31313. /**
  31314. * @ngdoc directive
  31315. * @name ngHide
  31316. * @multiElement
  31317. *
  31318. * @description
  31319. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  31320. * the `ngHide` attribute.
  31321. *
  31322. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  31323. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  31324. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  31325. * {@link ng.directive:ngCsp ngCsp}).
  31326. *
  31327. * ```html
  31328. * <!-- when $scope.myValue is truthy (element is hidden) -->
  31329. * <div ng-hide="myValue" class="ng-hide"></div>
  31330. *
  31331. * <!-- when $scope.myValue is falsy (element is visible) -->
  31332. * <div ng-hide="myValue"></div>
  31333. * ```
  31334. *
  31335. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  31336. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  31337. * CSS class is removed from the element causing the element not to appear hidden.
  31338. *
  31339. * ## Why is `!important` used?
  31340. *
  31341. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  31342. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  31343. * simple as changing the display style on a HTML list item would make hidden elements appear
  31344. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  31345. *
  31346. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  31347. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  31348. * developer chooses to override the styling to change how to hide an element then it is just a
  31349. * matter of using `!important` in their own CSS code.
  31350. *
  31351. * ### Overriding `.ng-hide`
  31352. *
  31353. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  31354. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  31355. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  31356. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  31357. *
  31358. * ```css
  31359. * .ng-hide:not(.ng-hide-animate) {
  31360. * /&#42; These are just alternative ways of hiding an element &#42;/
  31361. * display: block!important;
  31362. * position: absolute;
  31363. * top: -9999px;
  31364. * left: -9999px;
  31365. * }
  31366. * ```
  31367. *
  31368. * By default you don't need to override in CSS anything and the animations will work around the
  31369. * display style.
  31370. *
  31371. * @animations
  31372. * | Animation | Occurs |
  31373. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  31374. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  31375. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  31376. *
  31377. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  31378. * directive expression is true and false. This system works like the animation system present with
  31379. * `ngClass` except that you must also include the `!important` flag to override the display
  31380. * property so that the elements are not actually hidden during the animation.
  31381. *
  31382. * ```css
  31383. * /&#42; A working example can be found at the bottom of this page. &#42;/
  31384. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  31385. * transition: all 0.5s linear;
  31386. * }
  31387. *
  31388. * .my-element.ng-hide-add { ... }
  31389. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  31390. * .my-element.ng-hide-remove { ... }
  31391. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  31392. * ```
  31393. *
  31394. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  31395. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  31396. *
  31397. * @element ANY
  31398. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  31399. * element is hidden/shown respectively.
  31400. *
  31401. * @example
  31402. * A simple example, animating the element's opacity:
  31403. *
  31404. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  31405. <file name="index.html">
  31406. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  31407. <div class="check-element animate-show-hide" ng-hide="checked">
  31408. I hide when your checkbox is checked.
  31409. </div>
  31410. </file>
  31411. <file name="animations.css">
  31412. .animate-show-hide.ng-hide {
  31413. opacity: 0;
  31414. }
  31415. .animate-show-hide.ng-hide-add,
  31416. .animate-show-hide.ng-hide-remove {
  31417. transition: all linear 0.5s;
  31418. }
  31419. .check-element {
  31420. border: 1px solid black;
  31421. opacity: 1;
  31422. padding: 10px;
  31423. }
  31424. </file>
  31425. <file name="protractor.js" type="protractor">
  31426. it('should check ngHide', function() {
  31427. var checkbox = element(by.model('checked'));
  31428. var checkElem = element(by.css('.check-element'));
  31429. expect(checkElem.isDisplayed()).toBe(true);
  31430. checkbox.click();
  31431. expect(checkElem.isDisplayed()).toBe(false);
  31432. });
  31433. </file>
  31434. </example>
  31435. *
  31436. * <hr />
  31437. * @example
  31438. * A more complex example, featuring different show/hide animations:
  31439. *
  31440. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  31441. <file name="index.html">
  31442. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  31443. <div class="check-element funky-show-hide" ng-hide="checked">
  31444. I hide when your checkbox is checked.
  31445. </div>
  31446. </file>
  31447. <file name="animations.css">
  31448. body {
  31449. overflow: hidden;
  31450. perspective: 1000px;
  31451. }
  31452. .funky-show-hide.ng-hide-add {
  31453. transform: rotateZ(0);
  31454. transform-origin: right;
  31455. transition: all 0.5s ease-in-out;
  31456. }
  31457. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  31458. transform: rotateZ(-135deg);
  31459. }
  31460. .funky-show-hide.ng-hide-remove {
  31461. transform: rotateY(90deg);
  31462. transform-origin: left;
  31463. transition: all 0.5s ease;
  31464. }
  31465. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  31466. transform: rotateY(0);
  31467. }
  31468. .check-element {
  31469. border: 1px solid black;
  31470. opacity: 1;
  31471. padding: 10px;
  31472. }
  31473. </file>
  31474. <file name="protractor.js" type="protractor">
  31475. it('should check ngHide', function() {
  31476. var checkbox = element(by.model('checked'));
  31477. var checkElem = element(by.css('.check-element'));
  31478. expect(checkElem.isDisplayed()).toBe(true);
  31479. checkbox.click();
  31480. expect(checkElem.isDisplayed()).toBe(false);
  31481. });
  31482. </file>
  31483. </example>
  31484. *
  31485. * @knownIssue
  31486. *
  31487. * ### Flickering when using ngHide to toggle between elements
  31488. *
  31489. * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
  31490. * happen that both the element to show and the element to hide are visible for a very short time.
  31491. *
  31492. * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
  31493. * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
  31494. * other browsers.
  31495. *
  31496. * There are several way to mitigate this problem:
  31497. *
  31498. * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
  31499. * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
  31500. * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
  31501. * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
  31502. * - Define an animation on the affected elements.
  31503. */
  31504. var ngHideDirective = ['$animate', function($animate) {
  31505. return {
  31506. restrict: 'A',
  31507. multiElement: true,
  31508. link: function(scope, element, attr) {
  31509. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  31510. // The comment inside of the ngShowDirective explains why we add and
  31511. // remove a temporary class for the show/hide animation
  31512. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  31513. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  31514. });
  31515. });
  31516. }
  31517. };
  31518. }];
  31519. /**
  31520. * @ngdoc directive
  31521. * @name ngStyle
  31522. * @restrict AC
  31523. *
  31524. * @description
  31525. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  31526. *
  31527. * @knownIssue
  31528. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  31529. * attribute, when using the `ngStyle` directive on the same element.
  31530. * See {@link guide/interpolation#known-issues here} for more info.
  31531. *
  31532. * @element ANY
  31533. * @param {expression} ngStyle
  31534. *
  31535. * {@link guide/expression Expression} which evals to an
  31536. * object whose keys are CSS style names and values are corresponding values for those CSS
  31537. * keys.
  31538. *
  31539. * Since some CSS style names are not valid keys for an object, they must be quoted.
  31540. * See the 'background-color' style in the example below.
  31541. *
  31542. * @example
  31543. <example name="ng-style">
  31544. <file name="index.html">
  31545. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  31546. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  31547. <input type="button" value="clear" ng-click="myStyle={}">
  31548. <br/>
  31549. <span ng-style="myStyle">Sample Text</span>
  31550. <pre>myStyle={{myStyle}}</pre>
  31551. </file>
  31552. <file name="style.css">
  31553. span {
  31554. color: black;
  31555. }
  31556. </file>
  31557. <file name="protractor.js" type="protractor">
  31558. var colorSpan = element(by.css('span'));
  31559. it('should check ng-style', function() {
  31560. expect(colorSpan.getCssValue('color')).toMatch(/rgba\(0, 0, 0, 1\)|rgb\(0, 0, 0\)/);
  31561. element(by.css('input[value=\'set color\']')).click();
  31562. expect(colorSpan.getCssValue('color')).toMatch(/rgba\(255, 0, 0, 1\)|rgb\(255, 0, 0\)/);
  31563. element(by.css('input[value=clear]')).click();
  31564. expect(colorSpan.getCssValue('color')).toMatch(/rgba\(0, 0, 0, 1\)|rgb\(0, 0, 0\)/);
  31565. });
  31566. </file>
  31567. </example>
  31568. */
  31569. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  31570. scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  31571. if (oldStyles && (newStyles !== oldStyles)) {
  31572. forEach(oldStyles, function(val, style) { element.css(style, ''); });
  31573. }
  31574. if (newStyles) element.css(newStyles);
  31575. });
  31576. });
  31577. /**
  31578. * @ngdoc directive
  31579. * @name ngSwitch
  31580. * @restrict EA
  31581. *
  31582. * @description
  31583. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  31584. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  31585. * as specified in the template.
  31586. *
  31587. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  31588. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  31589. * matches the value obtained from the evaluated expression. In other words, you define a container element
  31590. * (where you place the directive), place an expression on the **`on="..."` attribute**
  31591. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  31592. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  31593. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  31594. * attribute is displayed.
  31595. *
  31596. * <div class="alert alert-info">
  31597. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  31598. * as literal string values to match against.
  31599. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  31600. * value of the expression `$scope.someVal`.
  31601. * </div>
  31602. * @animations
  31603. * | Animation | Occurs |
  31604. * |----------------------------------|-------------------------------------|
  31605. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  31606. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  31607. *
  31608. * @usage
  31609. *
  31610. * ```
  31611. * <ANY ng-switch="expression">
  31612. * <ANY ng-switch-when="matchValue1">...</ANY>
  31613. * <ANY ng-switch-when="matchValue2">...</ANY>
  31614. * <ANY ng-switch-default>...</ANY>
  31615. * </ANY>
  31616. * ```
  31617. *
  31618. *
  31619. * @scope
  31620. * @priority 1200
  31621. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  31622. * On child elements add:
  31623. *
  31624. * * `ngSwitchWhen`: the case statement to match against. If match then this
  31625. * case will be displayed. If the same match appears multiple times, all the
  31626. * elements will be displayed. It is possible to associate multiple values to
  31627. * the same `ngSwitchWhen` by defining the optional attribute
  31628. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  31629. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  31630. * if any of the `ngSwitch` evaluates to any of these tokens.
  31631. * * `ngSwitchDefault`: the default case when no other case match. If there
  31632. * are multiple default cases, all of them will be displayed when no other
  31633. * case match.
  31634. *
  31635. *
  31636. * @example
  31637. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  31638. <file name="index.html">
  31639. <div ng-controller="ExampleController">
  31640. <select ng-model="selection" ng-options="item for item in items">
  31641. </select>
  31642. <code>selection={{selection}}</code>
  31643. <hr/>
  31644. <div class="animate-switch-container"
  31645. ng-switch on="selection">
  31646. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  31647. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  31648. <div class="animate-switch" ng-switch-default>default</div>
  31649. </div>
  31650. </div>
  31651. </file>
  31652. <file name="script.js">
  31653. angular.module('switchExample', ['ngAnimate'])
  31654. .controller('ExampleController', ['$scope', function($scope) {
  31655. $scope.items = ['settings', 'home', 'options', 'other'];
  31656. $scope.selection = $scope.items[0];
  31657. }]);
  31658. </file>
  31659. <file name="animations.css">
  31660. .animate-switch-container {
  31661. position:relative;
  31662. background:white;
  31663. border:1px solid black;
  31664. height:40px;
  31665. overflow:hidden;
  31666. }
  31667. .animate-switch {
  31668. padding:10px;
  31669. }
  31670. .animate-switch.ng-animate {
  31671. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  31672. position:absolute;
  31673. top:0;
  31674. left:0;
  31675. right:0;
  31676. bottom:0;
  31677. }
  31678. .animate-switch.ng-leave.ng-leave-active,
  31679. .animate-switch.ng-enter {
  31680. top:-50px;
  31681. }
  31682. .animate-switch.ng-leave,
  31683. .animate-switch.ng-enter.ng-enter-active {
  31684. top:0;
  31685. }
  31686. </file>
  31687. <file name="protractor.js" type="protractor">
  31688. var switchElem = element(by.css('[ng-switch]'));
  31689. var select = element(by.model('selection'));
  31690. it('should start in settings', function() {
  31691. expect(switchElem.getText()).toMatch(/Settings Div/);
  31692. });
  31693. it('should change to home', function() {
  31694. select.all(by.css('option')).get(1).click();
  31695. expect(switchElem.getText()).toMatch(/Home Span/);
  31696. });
  31697. it('should change to settings via "options"', function() {
  31698. select.all(by.css('option')).get(2).click();
  31699. expect(switchElem.getText()).toMatch(/Settings Div/);
  31700. });
  31701. it('should select default', function() {
  31702. select.all(by.css('option')).get(3).click();
  31703. expect(switchElem.getText()).toMatch(/default/);
  31704. });
  31705. </file>
  31706. </example>
  31707. */
  31708. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  31709. return {
  31710. require: 'ngSwitch',
  31711. // asks for $scope to fool the BC controller module
  31712. controller: ['$scope', function NgSwitchController() {
  31713. this.cases = {};
  31714. }],
  31715. link: function(scope, element, attr, ngSwitchController) {
  31716. var watchExpr = attr.ngSwitch || attr.on,
  31717. selectedTranscludes = [],
  31718. selectedElements = [],
  31719. previousLeaveAnimations = [],
  31720. selectedScopes = [];
  31721. var spliceFactory = function(array, index) {
  31722. return function(response) {
  31723. if (response !== false) array.splice(index, 1);
  31724. };
  31725. };
  31726. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  31727. var i, ii;
  31728. // Start with the last, in case the array is modified during the loop
  31729. while (previousLeaveAnimations.length) {
  31730. $animate.cancel(previousLeaveAnimations.pop());
  31731. }
  31732. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  31733. var selected = getBlockNodes(selectedElements[i].clone);
  31734. selectedScopes[i].$destroy();
  31735. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  31736. runner.done(spliceFactory(previousLeaveAnimations, i));
  31737. }
  31738. selectedElements.length = 0;
  31739. selectedScopes.length = 0;
  31740. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  31741. forEach(selectedTranscludes, function(selectedTransclude) {
  31742. selectedTransclude.transclude(function(caseElement, selectedScope) {
  31743. selectedScopes.push(selectedScope);
  31744. var anchor = selectedTransclude.element;
  31745. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  31746. var block = { clone: caseElement };
  31747. selectedElements.push(block);
  31748. $animate.enter(caseElement, anchor.parent(), anchor);
  31749. });
  31750. });
  31751. }
  31752. });
  31753. }
  31754. };
  31755. }];
  31756. var ngSwitchWhenDirective = ngDirective({
  31757. transclude: 'element',
  31758. priority: 1200,
  31759. require: '^ngSwitch',
  31760. multiElement: true,
  31761. link: function(scope, element, attrs, ctrl, $transclude) {
  31762. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  31763. // Filter duplicate cases
  31764. function(element, index, array) { return array[index - 1] !== element; }
  31765. );
  31766. forEach(cases, function(whenCase) {
  31767. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  31768. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  31769. });
  31770. }
  31771. });
  31772. var ngSwitchDefaultDirective = ngDirective({
  31773. transclude: 'element',
  31774. priority: 1200,
  31775. require: '^ngSwitch',
  31776. multiElement: true,
  31777. link: function(scope, element, attr, ctrl, $transclude) {
  31778. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  31779. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  31780. }
  31781. });
  31782. /**
  31783. * @ngdoc directive
  31784. * @name ngTransclude
  31785. * @restrict EAC
  31786. *
  31787. * @description
  31788. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  31789. *
  31790. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  31791. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  31792. *
  31793. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  31794. * content of this element will be removed before the transcluded content is inserted.
  31795. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  31796. * content in the case that no transcluded content is provided.
  31797. *
  31798. * @element ANY
  31799. *
  31800. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  31801. * or its value is the same as the name of the attribute then the default slot is used.
  31802. *
  31803. * @example
  31804. * ### Basic transclusion
  31805. * This example demonstrates basic transclusion of content into a component directive.
  31806. * <example name="simpleTranscludeExample" module="transcludeExample">
  31807. * <file name="index.html">
  31808. * <script>
  31809. * angular.module('transcludeExample', [])
  31810. * .directive('pane', function(){
  31811. * return {
  31812. * restrict: 'E',
  31813. * transclude: true,
  31814. * scope: { title:'@' },
  31815. * template: '<div style="border: 1px solid black;">' +
  31816. * '<div style="background-color: gray">{{title}}</div>' +
  31817. * '<ng-transclude></ng-transclude>' +
  31818. * '</div>'
  31819. * };
  31820. * })
  31821. * .controller('ExampleController', ['$scope', function($scope) {
  31822. * $scope.title = 'Lorem Ipsum';
  31823. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  31824. * }]);
  31825. * </script>
  31826. * <div ng-controller="ExampleController">
  31827. * <input ng-model="title" aria-label="title"> <br/>
  31828. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  31829. * <pane title="{{title}}"><span>{{text}}</span></pane>
  31830. * </div>
  31831. * </file>
  31832. * <file name="protractor.js" type="protractor">
  31833. * it('should have transcluded', function() {
  31834. * var titleElement = element(by.model('title'));
  31835. * titleElement.clear();
  31836. * titleElement.sendKeys('TITLE');
  31837. * var textElement = element(by.model('text'));
  31838. * textElement.clear();
  31839. * textElement.sendKeys('TEXT');
  31840. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  31841. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  31842. * });
  31843. * </file>
  31844. * </example>
  31845. *
  31846. * @example
  31847. * ### Transclude fallback content
  31848. * This example shows how to use `NgTransclude` with fallback content, that
  31849. * is displayed if no transcluded content is provided.
  31850. *
  31851. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  31852. * <file name="index.html">
  31853. * <script>
  31854. * angular.module('transcludeFallbackContentExample', [])
  31855. * .directive('myButton', function(){
  31856. * return {
  31857. * restrict: 'E',
  31858. * transclude: true,
  31859. * scope: true,
  31860. * template: '<button style="cursor: pointer;">' +
  31861. * '<ng-transclude>' +
  31862. * '<b style="color: red;">Button1</b>' +
  31863. * '</ng-transclude>' +
  31864. * '</button>'
  31865. * };
  31866. * });
  31867. * </script>
  31868. * <!-- fallback button content -->
  31869. * <my-button id="fallback"></my-button>
  31870. * <!-- modified button content -->
  31871. * <my-button id="modified">
  31872. * <i style="color: green;">Button2</i>
  31873. * </my-button>
  31874. * </file>
  31875. * <file name="protractor.js" type="protractor">
  31876. * it('should have different transclude element content', function() {
  31877. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  31878. * expect(element(by.id('modified')).getText()).toBe('Button2');
  31879. * });
  31880. * </file>
  31881. * </example>
  31882. *
  31883. * @example
  31884. * ### Multi-slot transclusion
  31885. * This example demonstrates using multi-slot transclusion in a component directive.
  31886. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  31887. * <file name="index.html">
  31888. * <style>
  31889. * .title, .footer {
  31890. * background-color: gray
  31891. * }
  31892. * </style>
  31893. * <div ng-controller="ExampleController">
  31894. * <input ng-model="title" aria-label="title"> <br/>
  31895. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  31896. * <pane>
  31897. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  31898. * <pane-body><p>{{text}}</p></pane-body>
  31899. * </pane>
  31900. * </div>
  31901. * </file>
  31902. * <file name="app.js">
  31903. * angular.module('multiSlotTranscludeExample', [])
  31904. * .directive('pane', function() {
  31905. * return {
  31906. * restrict: 'E',
  31907. * transclude: {
  31908. * 'title': '?paneTitle',
  31909. * 'body': 'paneBody',
  31910. * 'footer': '?paneFooter'
  31911. * },
  31912. * template: '<div style="border: 1px solid black;">' +
  31913. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  31914. * '<div ng-transclude="body"></div>' +
  31915. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  31916. * '</div>'
  31917. * };
  31918. * })
  31919. * .controller('ExampleController', ['$scope', function($scope) {
  31920. * $scope.title = 'Lorem Ipsum';
  31921. * $scope.link = 'https://google.com';
  31922. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  31923. * }]);
  31924. * </file>
  31925. * <file name="protractor.js" type="protractor">
  31926. * it('should have transcluded the title and the body', function() {
  31927. * var titleElement = element(by.model('title'));
  31928. * titleElement.clear();
  31929. * titleElement.sendKeys('TITLE');
  31930. * var textElement = element(by.model('text'));
  31931. * textElement.clear();
  31932. * textElement.sendKeys('TEXT');
  31933. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  31934. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  31935. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  31936. * });
  31937. * </file>
  31938. * </example>
  31939. */
  31940. var ngTranscludeMinErr = minErr('ngTransclude');
  31941. var ngTranscludeDirective = ['$compile', function($compile) {
  31942. return {
  31943. restrict: 'EAC',
  31944. compile: function ngTranscludeCompile(tElement) {
  31945. // Remove and cache any original content to act as a fallback
  31946. var fallbackLinkFn = $compile(tElement.contents());
  31947. tElement.empty();
  31948. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  31949. if (!$transclude) {
  31950. throw ngTranscludeMinErr('orphan',
  31951. 'Illegal use of ngTransclude directive in the template! ' +
  31952. 'No parent directive that requires a transclusion found. ' +
  31953. 'Element: {0}',
  31954. startingTag($element));
  31955. }
  31956. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  31957. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  31958. $attrs.ngTransclude = '';
  31959. }
  31960. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  31961. // If the slot is required and no transclusion content is provided then this call will throw an error
  31962. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  31963. // If the slot is optional and no transclusion content is provided then use the fallback content
  31964. if (slotName && !$transclude.isSlotFilled(slotName)) {
  31965. useFallbackContent();
  31966. }
  31967. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  31968. if (clone.length && notWhitespace(clone)) {
  31969. $element.append(clone);
  31970. } else {
  31971. useFallbackContent();
  31972. // There is nothing linked against the transcluded scope since no content was available,
  31973. // so it should be safe to clean up the generated scope.
  31974. transcludedScope.$destroy();
  31975. }
  31976. }
  31977. function useFallbackContent() {
  31978. // Since this is the fallback content rather than the transcluded content,
  31979. // we link against the scope of this directive rather than the transcluded scope
  31980. fallbackLinkFn($scope, function(clone) {
  31981. $element.append(clone);
  31982. });
  31983. }
  31984. function notWhitespace(nodes) {
  31985. for (var i = 0, ii = nodes.length; i < ii; i++) {
  31986. var node = nodes[i];
  31987. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  31988. return true;
  31989. }
  31990. }
  31991. }
  31992. };
  31993. }
  31994. };
  31995. }];
  31996. /**
  31997. * @ngdoc directive
  31998. * @name script
  31999. * @restrict E
  32000. *
  32001. * @description
  32002. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  32003. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  32004. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  32005. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  32006. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  32007. *
  32008. * @param {string} type Must be set to `'text/ng-template'`.
  32009. * @param {string} id Cache name of the template.
  32010. *
  32011. * @example
  32012. <example name="script-tag">
  32013. <file name="index.html">
  32014. <script type="text/ng-template" id="/tpl.html">
  32015. Content of the template.
  32016. </script>
  32017. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  32018. <div id="tpl-content" ng-include src="currentTpl"></div>
  32019. </file>
  32020. <file name="protractor.js" type="protractor">
  32021. it('should load template defined inside script tag', function() {
  32022. element(by.css('#tpl-link')).click();
  32023. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  32024. });
  32025. </file>
  32026. </example>
  32027. */
  32028. var scriptDirective = ['$templateCache', function($templateCache) {
  32029. return {
  32030. restrict: 'E',
  32031. terminal: true,
  32032. compile: function(element, attr) {
  32033. if (attr.type === 'text/ng-template') {
  32034. var templateUrl = attr.id,
  32035. text = element[0].text;
  32036. $templateCache.put(templateUrl, text);
  32037. }
  32038. }
  32039. };
  32040. }];
  32041. /* exported selectDirective, optionDirective */
  32042. var noopNgModelController = { $setViewValue: noop, $render: noop };
  32043. function setOptionSelectedStatus(optionEl, value) {
  32044. optionEl.prop('selected', value);
  32045. /**
  32046. * When unselecting an option, setting the property to null / false should be enough
  32047. * However, screenreaders might react to the selected attribute instead, see
  32048. * https://github.com/angular/angular.js/issues/14419
  32049. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  32050. * or null
  32051. */
  32052. optionEl.attr('selected', value);
  32053. }
  32054. /**
  32055. * @ngdoc type
  32056. * @name select.SelectController
  32057. *
  32058. * @description
  32059. * The controller for the {@link ng.select select} directive. The controller exposes
  32060. * a few utility methods that can be used to augment the behavior of a regular or an
  32061. * {@link ng.ngOptions ngOptions} select element.
  32062. *
  32063. * @example
  32064. * ### Set a custom error when the unknown option is selected
  32065. *
  32066. * This example sets a custom error "unknownValue" on the ngModelController
  32067. * when the select element's unknown option is selected, i.e. when the model is set to a value
  32068. * that is not matched by any option.
  32069. *
  32070. * <example name="select-unknown-value-error" module="staticSelect">
  32071. * <file name="index.html">
  32072. * <div ng-controller="ExampleController">
  32073. * <form name="myForm">
  32074. * <label for="testSelect"> Single select: </label><br>
  32075. * <select name="testSelect" ng-model="selected" unknown-value-error>
  32076. * <option value="option-1">Option 1</option>
  32077. * <option value="option-2">Option 2</option>
  32078. * </select><br>
  32079. * <span class="error" ng-if="myForm.testSelect.$error.unknownValue">
  32080. * Error: The current model doesn't match any option</span><br>
  32081. *
  32082. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  32083. * </form>
  32084. * </div>
  32085. * </file>
  32086. * <file name="app.js">
  32087. * angular.module('staticSelect', [])
  32088. * .controller('ExampleController', ['$scope', function($scope) {
  32089. * $scope.selected = null;
  32090. *
  32091. * $scope.forceUnknownOption = function() {
  32092. * $scope.selected = 'nonsense';
  32093. * };
  32094. * }])
  32095. * .directive('unknownValueError', function() {
  32096. * return {
  32097. * require: ['ngModel', 'select'],
  32098. * link: function(scope, element, attrs, ctrls) {
  32099. * var ngModelCtrl = ctrls[0];
  32100. * var selectCtrl = ctrls[1];
  32101. *
  32102. * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) {
  32103. * if (selectCtrl.$isUnknownOptionSelected()) {
  32104. * return false;
  32105. * }
  32106. *
  32107. * return true;
  32108. * };
  32109. * }
  32110. *
  32111. * };
  32112. * });
  32113. * </file>
  32114. *</example>
  32115. *
  32116. *
  32117. * @example
  32118. * ### Set the "required" error when the unknown option is selected.
  32119. *
  32120. * By default, the "required" error on the ngModelController is only set on a required select
  32121. * when the empty option is selected. This example adds a custom directive that also sets the
  32122. * error when the unknown option is selected.
  32123. *
  32124. * <example name="select-unknown-value-required" module="staticSelect">
  32125. * <file name="index.html">
  32126. * <div ng-controller="ExampleController">
  32127. * <form name="myForm">
  32128. * <label for="testSelect"> Select: </label><br>
  32129. * <select name="testSelect" ng-model="selected" required unknown-value-required>
  32130. * <option value="option-1">Option 1</option>
  32131. * <option value="option-2">Option 2</option>
  32132. * </select><br>
  32133. * <span class="error" ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br>
  32134. *
  32135. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  32136. * </form>
  32137. * </div>
  32138. * </file>
  32139. * <file name="app.js">
  32140. * angular.module('staticSelect', [])
  32141. * .controller('ExampleController', ['$scope', function($scope) {
  32142. * $scope.selected = null;
  32143. *
  32144. * $scope.forceUnknownOption = function() {
  32145. * $scope.selected = 'nonsense';
  32146. * };
  32147. * }])
  32148. * .directive('unknownValueRequired', function() {
  32149. * return {
  32150. * priority: 1, // This directive must run after the required directive has added its validator
  32151. * require: ['ngModel', 'select'],
  32152. * link: function(scope, element, attrs, ctrls) {
  32153. * var ngModelCtrl = ctrls[0];
  32154. * var selectCtrl = ctrls[1];
  32155. *
  32156. * var originalRequiredValidator = ngModelCtrl.$validators.required;
  32157. *
  32158. * ngModelCtrl.$validators.required = function() {
  32159. * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) {
  32160. * return false;
  32161. * }
  32162. *
  32163. * return originalRequiredValidator.apply(this, arguments);
  32164. * };
  32165. * }
  32166. * };
  32167. * });
  32168. * </file>
  32169. * <file name="protractor.js" type="protractor">
  32170. * it('should show the error message when the unknown option is selected', function() {
  32171. var error = element(by.className('error'));
  32172. expect(error.getText()).toBe('Error: Please select a value');
  32173. element(by.cssContainingText('option', 'Option 1')).click();
  32174. expect(error.isPresent()).toBe(false);
  32175. element(by.tagName('button')).click();
  32176. expect(error.getText()).toBe('Error: Please select a value');
  32177. });
  32178. * </file>
  32179. *</example>
  32180. *
  32181. *
  32182. */
  32183. var SelectController =
  32184. ['$element', '$scope', /** @this */ function($element, $scope) {
  32185. var self = this,
  32186. optionsMap = new NgMap();
  32187. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  32188. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  32189. self.ngModelCtrl = noopNgModelController;
  32190. self.multiple = false;
  32191. // The "unknown" option is one that is prepended to the list if the viewValue
  32192. // does not match any of the options. When it is rendered the value of the unknown
  32193. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  32194. //
  32195. // Support: IE 9 only
  32196. // We can't just jqLite('<option>') since jqLite is not smart enough
  32197. // to create it in <select> and IE barfs otherwise.
  32198. self.unknownOption = jqLite(window.document.createElement('option'));
  32199. // The empty option is an option with the value '' that the application developer can
  32200. // provide inside the select. It is always selectable and indicates that a "null" selection has
  32201. // been made by the user.
  32202. // If the select has an empty option, and the model of the select is set to "undefined" or "null",
  32203. // the empty option is selected.
  32204. // If the model is set to a different unmatched value, the unknown option is rendered and
  32205. // selected, i.e both are present, because a "null" selection and an unknown value are different.
  32206. self.hasEmptyOption = false;
  32207. self.emptyOption = undefined;
  32208. self.renderUnknownOption = function(val) {
  32209. var unknownVal = self.generateUnknownOptionValue(val);
  32210. self.unknownOption.val(unknownVal);
  32211. $element.prepend(self.unknownOption);
  32212. setOptionSelectedStatus(self.unknownOption, true);
  32213. $element.val(unknownVal);
  32214. };
  32215. self.updateUnknownOption = function(val) {
  32216. var unknownVal = self.generateUnknownOptionValue(val);
  32217. self.unknownOption.val(unknownVal);
  32218. setOptionSelectedStatus(self.unknownOption, true);
  32219. $element.val(unknownVal);
  32220. };
  32221. self.generateUnknownOptionValue = function(val) {
  32222. return '? ' + hashKey(val) + ' ?';
  32223. };
  32224. self.removeUnknownOption = function() {
  32225. if (self.unknownOption.parent()) self.unknownOption.remove();
  32226. };
  32227. self.selectEmptyOption = function() {
  32228. if (self.emptyOption) {
  32229. $element.val('');
  32230. setOptionSelectedStatus(self.emptyOption, true);
  32231. }
  32232. };
  32233. self.unselectEmptyOption = function() {
  32234. if (self.hasEmptyOption) {
  32235. setOptionSelectedStatus(self.emptyOption, false);
  32236. }
  32237. };
  32238. $scope.$on('$destroy', function() {
  32239. // disable unknown option so that we don't do work when the whole select is being destroyed
  32240. self.renderUnknownOption = noop;
  32241. });
  32242. // Read the value of the select control, the implementation of this changes depending
  32243. // upon whether the select can have multiple values and whether ngOptions is at work.
  32244. self.readValue = function readSingleValue() {
  32245. var val = $element.val();
  32246. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  32247. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  32248. if (self.hasOption(realVal)) {
  32249. return realVal;
  32250. }
  32251. return null;
  32252. };
  32253. // Write the value to the select control, the implementation of this changes depending
  32254. // upon whether the select can have multiple values and whether ngOptions is at work.
  32255. self.writeValue = function writeSingleValue(value) {
  32256. // Make sure to remove the selected attribute from the previously selected option
  32257. // Otherwise, screen readers might get confused
  32258. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  32259. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  32260. if (self.hasOption(value)) {
  32261. self.removeUnknownOption();
  32262. var hashedVal = hashKey(value);
  32263. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  32264. // Set selected attribute and property on selected option for screen readers
  32265. var selectedOption = $element[0].options[$element[0].selectedIndex];
  32266. setOptionSelectedStatus(jqLite(selectedOption), true);
  32267. } else {
  32268. self.selectUnknownOrEmptyOption(value);
  32269. }
  32270. };
  32271. // Tell the select control that an option, with the given value, has been added
  32272. self.addOption = function(value, element) {
  32273. // Skip comment nodes, as they only pollute the `optionsMap`
  32274. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  32275. assertNotHasOwnProperty(value, '"option value"');
  32276. if (value === '') {
  32277. self.hasEmptyOption = true;
  32278. self.emptyOption = element;
  32279. }
  32280. var count = optionsMap.get(value) || 0;
  32281. optionsMap.set(value, count + 1);
  32282. // Only render at the end of a digest. This improves render performance when many options
  32283. // are added during a digest and ensures all relevant options are correctly marked as selected
  32284. scheduleRender();
  32285. };
  32286. // Tell the select control that an option, with the given value, has been removed
  32287. self.removeOption = function(value) {
  32288. var count = optionsMap.get(value);
  32289. if (count) {
  32290. if (count === 1) {
  32291. optionsMap.delete(value);
  32292. if (value === '') {
  32293. self.hasEmptyOption = false;
  32294. self.emptyOption = undefined;
  32295. }
  32296. } else {
  32297. optionsMap.set(value, count - 1);
  32298. }
  32299. }
  32300. };
  32301. // Check whether the select control has an option matching the given value
  32302. self.hasOption = function(value) {
  32303. return !!optionsMap.get(value);
  32304. };
  32305. /**
  32306. * @ngdoc method
  32307. * @name select.SelectController#$hasEmptyOption
  32308. *
  32309. * @description
  32310. *
  32311. * Returns `true` if the select element currently has an empty option
  32312. * element, i.e. an option that signifies that the select is empty / the selection is null.
  32313. *
  32314. */
  32315. self.$hasEmptyOption = function() {
  32316. return self.hasEmptyOption;
  32317. };
  32318. /**
  32319. * @ngdoc method
  32320. * @name select.SelectController#$isUnknownOptionSelected
  32321. *
  32322. * @description
  32323. *
  32324. * Returns `true` if the select element's unknown option is selected. The unknown option is added
  32325. * and automatically selected whenever the select model doesn't match any option.
  32326. *
  32327. */
  32328. self.$isUnknownOptionSelected = function() {
  32329. // Presence of the unknown option means it is selected
  32330. return $element[0].options[0] === self.unknownOption[0];
  32331. };
  32332. /**
  32333. * @ngdoc method
  32334. * @name select.SelectController#$isEmptyOptionSelected
  32335. *
  32336. * @description
  32337. *
  32338. * Returns `true` if the select element has an empty option and this empty option is currently
  32339. * selected. Returns `false` if the select element has no empty option or it is not selected.
  32340. *
  32341. */
  32342. self.$isEmptyOptionSelected = function() {
  32343. return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0];
  32344. };
  32345. self.selectUnknownOrEmptyOption = function(value) {
  32346. if (value == null && self.emptyOption) {
  32347. self.removeUnknownOption();
  32348. self.selectEmptyOption();
  32349. } else if (self.unknownOption.parent().length) {
  32350. self.updateUnknownOption(value);
  32351. } else {
  32352. self.renderUnknownOption(value);
  32353. }
  32354. };
  32355. var renderScheduled = false;
  32356. function scheduleRender() {
  32357. if (renderScheduled) return;
  32358. renderScheduled = true;
  32359. $scope.$$postDigest(function() {
  32360. renderScheduled = false;
  32361. self.ngModelCtrl.$render();
  32362. });
  32363. }
  32364. var updateScheduled = false;
  32365. function scheduleViewValueUpdate(renderAfter) {
  32366. if (updateScheduled) return;
  32367. updateScheduled = true;
  32368. $scope.$$postDigest(function() {
  32369. if ($scope.$$destroyed) return;
  32370. updateScheduled = false;
  32371. self.ngModelCtrl.$setViewValue(self.readValue());
  32372. if (renderAfter) self.ngModelCtrl.$render();
  32373. });
  32374. }
  32375. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  32376. if (optionAttrs.$attr.ngValue) {
  32377. // The value attribute is set by ngValue
  32378. var oldVal, hashedVal;
  32379. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  32380. var removal;
  32381. var previouslySelected = optionElement.prop('selected');
  32382. if (isDefined(hashedVal)) {
  32383. self.removeOption(oldVal);
  32384. delete self.selectValueMap[hashedVal];
  32385. removal = true;
  32386. }
  32387. hashedVal = hashKey(newVal);
  32388. oldVal = newVal;
  32389. self.selectValueMap[hashedVal] = newVal;
  32390. self.addOption(newVal, optionElement);
  32391. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  32392. // from firing a second time. Other $observers on value will also get the result of the
  32393. // ngValue expression, not the hashed value
  32394. optionElement.attr('value', hashedVal);
  32395. if (removal && previouslySelected) {
  32396. scheduleViewValueUpdate();
  32397. }
  32398. });
  32399. } else if (interpolateValueFn) {
  32400. // The value attribute is interpolated
  32401. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  32402. // This method is overwritten in ngOptions and has side-effects!
  32403. self.readValue();
  32404. var removal;
  32405. var previouslySelected = optionElement.prop('selected');
  32406. if (isDefined(oldVal)) {
  32407. self.removeOption(oldVal);
  32408. removal = true;
  32409. }
  32410. oldVal = newVal;
  32411. self.addOption(newVal, optionElement);
  32412. if (removal && previouslySelected) {
  32413. scheduleViewValueUpdate();
  32414. }
  32415. });
  32416. } else if (interpolateTextFn) {
  32417. // The text content is interpolated
  32418. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  32419. optionAttrs.$set('value', newVal);
  32420. var previouslySelected = optionElement.prop('selected');
  32421. if (oldVal !== newVal) {
  32422. self.removeOption(oldVal);
  32423. }
  32424. self.addOption(newVal, optionElement);
  32425. if (oldVal && previouslySelected) {
  32426. scheduleViewValueUpdate();
  32427. }
  32428. });
  32429. } else {
  32430. // The value attribute is static
  32431. self.addOption(optionAttrs.value, optionElement);
  32432. }
  32433. optionAttrs.$observe('disabled', function(newVal) {
  32434. // Since model updates will also select disabled options (like ngOptions),
  32435. // we only have to handle options becoming disabled, not enabled
  32436. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  32437. if (self.multiple) {
  32438. scheduleViewValueUpdate(true);
  32439. } else {
  32440. self.ngModelCtrl.$setViewValue(null);
  32441. self.ngModelCtrl.$render();
  32442. }
  32443. }
  32444. });
  32445. optionElement.on('$destroy', function() {
  32446. var currentValue = self.readValue();
  32447. var removeValue = optionAttrs.value;
  32448. self.removeOption(removeValue);
  32449. scheduleRender();
  32450. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  32451. currentValue === removeValue
  32452. ) {
  32453. // When multiple (selected) options are destroyed at the same time, we don't want
  32454. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  32455. scheduleViewValueUpdate(true);
  32456. }
  32457. });
  32458. };
  32459. }];
  32460. /**
  32461. * @ngdoc directive
  32462. * @name select
  32463. * @restrict E
  32464. *
  32465. * @description
  32466. * HTML `select` element with AngularJS data-binding.
  32467. *
  32468. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  32469. * between the scope and the `<select>` control (including setting default values).
  32470. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  32471. * {@link ngOptions `ngOptions`} directives.
  32472. *
  32473. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  32474. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  32475. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  32476. * Value and textContent can be interpolated.
  32477. *
  32478. * The {@link select.SelectController select controller} exposes utility functions that can be used
  32479. * to manipulate the select's behavior.
  32480. *
  32481. * ## Matching model and option values
  32482. *
  32483. * In general, the match between the model and an option is evaluated by strictly comparing the model
  32484. * value against the value of the available options.
  32485. *
  32486. * If you are setting the option value with the option's `value` attribute, or textContent, the
  32487. * value will always be a `string` which means that the model value must also be a string.
  32488. * Otherwise the `select` directive cannot match them correctly.
  32489. *
  32490. * To bind the model to a non-string value, you can use one of the following strategies:
  32491. * - the {@link ng.ngOptions `ngOptions`} directive
  32492. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  32493. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  32494. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  32495. * - model $parsers / $formatters to convert the string value
  32496. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  32497. *
  32498. * If the viewValue of `ngModel` does not match any of the options, then the control
  32499. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  32500. *
  32501. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  32502. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  32503. * option. See example below for demonstration.
  32504. *
  32505. * ## Choosing between `ngRepeat` and `ngOptions`
  32506. *
  32507. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  32508. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  32509. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  32510. * comprehension expression
  32511. * - reduced memory consumption by not creating a new scope for each repeated instance
  32512. * - increased render speed by creating the options in a documentFragment instead of individually
  32513. *
  32514. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  32515. * Chrome and Internet Explorer / Edge.
  32516. *
  32517. *
  32518. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  32519. * @param {string=} name Property name of the form under which the control is published.
  32520. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  32521. * bound to the model as an array.
  32522. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32523. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  32524. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  32525. * when you want to data-bind to the required attribute.
  32526. * @param {string=} ngChange AngularJS expression to be executed when selected option(s) changes due to user
  32527. * interaction with the select element.
  32528. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  32529. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  32530. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  32531. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  32532. *
  32533. *
  32534. * @example
  32535. * ### Simple `select` elements with static options
  32536. *
  32537. * <example name="static-select" module="staticSelect">
  32538. * <file name="index.html">
  32539. * <div ng-controller="ExampleController">
  32540. * <form name="myForm">
  32541. * <label for="singleSelect"> Single select: </label><br>
  32542. * <select name="singleSelect" ng-model="data.singleSelect">
  32543. * <option value="option-1">Option 1</option>
  32544. * <option value="option-2">Option 2</option>
  32545. * </select><br>
  32546. *
  32547. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  32548. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  32549. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  32550. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  32551. * <option value="option-2">Option 2</option>
  32552. * </select><br>
  32553. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  32554. * <tt>singleSelect = {{data.singleSelect}}</tt>
  32555. *
  32556. * <hr>
  32557. * <label for="multipleSelect"> Multiple select: </label><br>
  32558. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  32559. * <option value="option-1">Option 1</option>
  32560. * <option value="option-2">Option 2</option>
  32561. * <option value="option-3">Option 3</option>
  32562. * </select><br>
  32563. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  32564. * </form>
  32565. * </div>
  32566. * </file>
  32567. * <file name="app.js">
  32568. * angular.module('staticSelect', [])
  32569. * .controller('ExampleController', ['$scope', function($scope) {
  32570. * $scope.data = {
  32571. * singleSelect: null,
  32572. * multipleSelect: [],
  32573. * option1: 'option-1'
  32574. * };
  32575. *
  32576. * $scope.forceUnknownOption = function() {
  32577. * $scope.data.singleSelect = 'nonsense';
  32578. * };
  32579. * }]);
  32580. * </file>
  32581. *</example>
  32582. *
  32583. * @example
  32584. * ### Using `ngRepeat` to generate `select` options
  32585. * <example name="select-ngrepeat" module="ngrepeatSelect">
  32586. * <file name="index.html">
  32587. * <div ng-controller="ExampleController">
  32588. * <form name="myForm">
  32589. * <label for="repeatSelect"> Repeat select: </label>
  32590. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  32591. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  32592. * </select>
  32593. * </form>
  32594. * <hr>
  32595. * <tt>model = {{data.model}}</tt><br/>
  32596. * </div>
  32597. * </file>
  32598. * <file name="app.js">
  32599. * angular.module('ngrepeatSelect', [])
  32600. * .controller('ExampleController', ['$scope', function($scope) {
  32601. * $scope.data = {
  32602. * model: null,
  32603. * availableOptions: [
  32604. * {id: '1', name: 'Option A'},
  32605. * {id: '2', name: 'Option B'},
  32606. * {id: '3', name: 'Option C'}
  32607. * ]
  32608. * };
  32609. * }]);
  32610. * </file>
  32611. *</example>
  32612. *
  32613. * @example
  32614. * ### Using `ngValue` to bind the model to an array of objects
  32615. * <example name="select-ngvalue" module="ngvalueSelect">
  32616. * <file name="index.html">
  32617. * <div ng-controller="ExampleController">
  32618. * <form name="myForm">
  32619. * <label for="ngvalueselect"> ngvalue select: </label>
  32620. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  32621. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  32622. * </select>
  32623. * </form>
  32624. * <hr>
  32625. * <pre>model = {{data.model | json}}</pre><br/>
  32626. * </div>
  32627. * </file>
  32628. * <file name="app.js">
  32629. * angular.module('ngvalueSelect', [])
  32630. * .controller('ExampleController', ['$scope', function($scope) {
  32631. * $scope.data = {
  32632. * model: null,
  32633. * availableOptions: [
  32634. {value: 'myString', name: 'string'},
  32635. {value: 1, name: 'integer'},
  32636. {value: true, name: 'boolean'},
  32637. {value: null, name: 'null'},
  32638. {value: {prop: 'value'}, name: 'object'},
  32639. {value: ['a'], name: 'array'}
  32640. * ]
  32641. * };
  32642. * }]);
  32643. * </file>
  32644. *</example>
  32645. *
  32646. * @example
  32647. * ### Using `select` with `ngOptions` and setting a default value
  32648. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  32649. *
  32650. * <example name="select-with-default-values" module="defaultValueSelect">
  32651. * <file name="index.html">
  32652. * <div ng-controller="ExampleController">
  32653. * <form name="myForm">
  32654. * <label for="mySelect">Make a choice:</label>
  32655. * <select name="mySelect" id="mySelect"
  32656. * ng-options="option.name for option in data.availableOptions track by option.id"
  32657. * ng-model="data.selectedOption"></select>
  32658. * </form>
  32659. * <hr>
  32660. * <tt>option = {{data.selectedOption}}</tt><br/>
  32661. * </div>
  32662. * </file>
  32663. * <file name="app.js">
  32664. * angular.module('defaultValueSelect', [])
  32665. * .controller('ExampleController', ['$scope', function($scope) {
  32666. * $scope.data = {
  32667. * availableOptions: [
  32668. * {id: '1', name: 'Option A'},
  32669. * {id: '2', name: 'Option B'},
  32670. * {id: '3', name: 'Option C'}
  32671. * ],
  32672. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  32673. * };
  32674. * }]);
  32675. * </file>
  32676. *</example>
  32677. *
  32678. * @example
  32679. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  32680. *
  32681. * <example name="select-with-non-string-options" module="nonStringSelect">
  32682. * <file name="index.html">
  32683. * <select ng-model="model.id" convert-to-number>
  32684. * <option value="0">Zero</option>
  32685. * <option value="1">One</option>
  32686. * <option value="2">Two</option>
  32687. * </select>
  32688. * {{ model }}
  32689. * </file>
  32690. * <file name="app.js">
  32691. * angular.module('nonStringSelect', [])
  32692. * .run(function($rootScope) {
  32693. * $rootScope.model = { id: 2 };
  32694. * })
  32695. * .directive('convertToNumber', function() {
  32696. * return {
  32697. * require: 'ngModel',
  32698. * link: function(scope, element, attrs, ngModel) {
  32699. * ngModel.$parsers.push(function(val) {
  32700. * return parseInt(val, 10);
  32701. * });
  32702. * ngModel.$formatters.push(function(val) {
  32703. * return '' + val;
  32704. * });
  32705. * }
  32706. * };
  32707. * });
  32708. * </file>
  32709. * <file name="protractor.js" type="protractor">
  32710. * it('should initialize to model', function() {
  32711. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  32712. * });
  32713. * </file>
  32714. * </example>
  32715. *
  32716. */
  32717. var selectDirective = function() {
  32718. return {
  32719. restrict: 'E',
  32720. require: ['select', '?ngModel'],
  32721. controller: SelectController,
  32722. priority: 1,
  32723. link: {
  32724. pre: selectPreLink,
  32725. post: selectPostLink
  32726. }
  32727. };
  32728. function selectPreLink(scope, element, attr, ctrls) {
  32729. var selectCtrl = ctrls[0];
  32730. var ngModelCtrl = ctrls[1];
  32731. // if ngModel is not defined, we don't need to do anything but set the registerOption
  32732. // function to noop, so options don't get added internally
  32733. if (!ngModelCtrl) {
  32734. selectCtrl.registerOption = noop;
  32735. return;
  32736. }
  32737. selectCtrl.ngModelCtrl = ngModelCtrl;
  32738. // When the selected item(s) changes we delegate getting the value of the select control
  32739. // to the `readValue` method, which can be changed if the select can have multiple
  32740. // selected values or if the options are being generated by `ngOptions`
  32741. element.on('change', function() {
  32742. selectCtrl.removeUnknownOption();
  32743. scope.$apply(function() {
  32744. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  32745. });
  32746. });
  32747. // If the select allows multiple values then we need to modify how we read and write
  32748. // values from and to the control; also what it means for the value to be empty and
  32749. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  32750. // doesn't trigger rendering if only an item in the array changes.
  32751. if (attr.multiple) {
  32752. selectCtrl.multiple = true;
  32753. // Read value now needs to check each option to see if it is selected
  32754. selectCtrl.readValue = function readMultipleValue() {
  32755. var array = [];
  32756. forEach(element.find('option'), function(option) {
  32757. if (option.selected && !option.disabled) {
  32758. var val = option.value;
  32759. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  32760. }
  32761. });
  32762. return array;
  32763. };
  32764. // Write value now needs to set the selected property of each matching option
  32765. selectCtrl.writeValue = function writeMultipleValue(value) {
  32766. forEach(element.find('option'), function(option) {
  32767. var shouldBeSelected = !!value && (includes(value, option.value) ||
  32768. includes(value, selectCtrl.selectValueMap[option.value]));
  32769. var currentlySelected = option.selected;
  32770. // Support: IE 9-11 only, Edge 12-15+
  32771. // In IE and Edge adding options to the selection via shift+click/UP/DOWN
  32772. // will de-select already selected options if "selected" on those options was set
  32773. // more than once (i.e. when the options were already selected)
  32774. // So we only modify the selected property if necessary.
  32775. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  32776. // actual user interface.
  32777. if (shouldBeSelected !== currentlySelected) {
  32778. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  32779. }
  32780. });
  32781. };
  32782. // we have to do it on each watch since ngModel watches reference, but
  32783. // we need to work of an array, so we need to see if anything was inserted/removed
  32784. var lastView, lastViewRef = NaN;
  32785. scope.$watch(function selectMultipleWatch() {
  32786. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  32787. lastView = shallowCopy(ngModelCtrl.$viewValue);
  32788. ngModelCtrl.$render();
  32789. }
  32790. lastViewRef = ngModelCtrl.$viewValue;
  32791. });
  32792. // If we are a multiple select then value is now a collection
  32793. // so the meaning of $isEmpty changes
  32794. ngModelCtrl.$isEmpty = function(value) {
  32795. return !value || value.length === 0;
  32796. };
  32797. }
  32798. }
  32799. function selectPostLink(scope, element, attrs, ctrls) {
  32800. // if ngModel is not defined, we don't need to do anything
  32801. var ngModelCtrl = ctrls[1];
  32802. if (!ngModelCtrl) return;
  32803. var selectCtrl = ctrls[0];
  32804. // We delegate rendering to the `writeValue` method, which can be changed
  32805. // if the select can have multiple selected values or if the options are being
  32806. // generated by `ngOptions`.
  32807. // This must be done in the postLink fn to prevent $render to be called before
  32808. // all nodes have been linked correctly.
  32809. ngModelCtrl.$render = function() {
  32810. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  32811. };
  32812. }
  32813. };
  32814. // The option directive is purely designed to communicate the existence (or lack of)
  32815. // of dynamically created (and destroyed) option elements to their containing select
  32816. // directive via its controller.
  32817. var optionDirective = ['$interpolate', function($interpolate) {
  32818. return {
  32819. restrict: 'E',
  32820. priority: 100,
  32821. compile: function(element, attr) {
  32822. var interpolateValueFn, interpolateTextFn;
  32823. if (isDefined(attr.ngValue)) {
  32824. // Will be handled by registerOption
  32825. } else if (isDefined(attr.value)) {
  32826. // If the value attribute is defined, check if it contains an interpolation
  32827. interpolateValueFn = $interpolate(attr.value, true);
  32828. } else {
  32829. // If the value attribute is not defined then we fall back to the
  32830. // text content of the option element, which may be interpolated
  32831. interpolateTextFn = $interpolate(element.text(), true);
  32832. if (!interpolateTextFn) {
  32833. attr.$set('value', element.text());
  32834. }
  32835. }
  32836. return function(scope, element, attr) {
  32837. // This is an optimization over using ^^ since we don't want to have to search
  32838. // all the way to the root of the DOM for every single option element
  32839. var selectCtrlName = '$selectController',
  32840. parent = element.parent(),
  32841. selectCtrl = parent.data(selectCtrlName) ||
  32842. parent.parent().data(selectCtrlName); // in case we are in optgroup
  32843. if (selectCtrl) {
  32844. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  32845. }
  32846. };
  32847. }
  32848. };
  32849. }];
  32850. /**
  32851. * @ngdoc directive
  32852. * @name ngRequired
  32853. * @restrict A
  32854. *
  32855. * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the
  32856. * `required` attribute to the element and adds the `required`
  32857. * {@link ngModel.NgModelController#$validators `validator`}.
  32858. *
  32859. * @description
  32860. *
  32861. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32862. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  32863. * applied to custom controls.
  32864. *
  32865. * The directive sets the `required` attribute on the element if the AngularJS expression inside
  32866. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  32867. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  32868. * for more info.
  32869. *
  32870. * The validator will set the `required` error key to true if the `required` attribute is set and
  32871. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  32872. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  32873. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  32874. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  32875. *
  32876. * @example
  32877. * <example name="ngRequiredDirective" module="ngRequiredExample">
  32878. * <file name="index.html">
  32879. * <script>
  32880. * angular.module('ngRequiredExample', [])
  32881. * .controller('ExampleController', ['$scope', function($scope) {
  32882. * $scope.required = true;
  32883. * }]);
  32884. * </script>
  32885. * <div ng-controller="ExampleController">
  32886. * <form name="form">
  32887. * <label for="required">Toggle required: </label>
  32888. * <input type="checkbox" ng-model="required" id="required" />
  32889. * <br>
  32890. * <label for="input">This input must be filled if `required` is true: </label>
  32891. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  32892. * <hr>
  32893. * required error set? = <code>{{form.input.$error.required}}</code><br>
  32894. * model = <code>{{model}}</code>
  32895. * </form>
  32896. * </div>
  32897. * </file>
  32898. * <file name="protractor.js" type="protractor">
  32899. var required = element(by.binding('form.input.$error.required'));
  32900. var model = element(by.binding('model'));
  32901. var input = element(by.id('input'));
  32902. it('should set the required error', function() {
  32903. expect(required.getText()).toContain('true');
  32904. input.sendKeys('123');
  32905. expect(required.getText()).not.toContain('true');
  32906. expect(model.getText()).toContain('123');
  32907. });
  32908. * </file>
  32909. * </example>
  32910. */
  32911. var requiredDirective = ['$parse', function($parse) {
  32912. return {
  32913. restrict: 'A',
  32914. require: '?ngModel',
  32915. link: function(scope, elm, attr, ctrl) {
  32916. if (!ctrl) return;
  32917. // For boolean attributes like required, presence means true
  32918. var value = attr.hasOwnProperty('required') || $parse(attr.ngRequired)(scope);
  32919. if (!attr.ngRequired) {
  32920. // force truthy in case we are on non input element
  32921. // (input elements do this automatically for boolean attributes like required)
  32922. attr.required = true;
  32923. }
  32924. ctrl.$validators.required = function(modelValue, viewValue) {
  32925. return !value || !ctrl.$isEmpty(viewValue);
  32926. };
  32927. attr.$observe('required', function(newVal) {
  32928. if (value !== newVal) {
  32929. value = newVal;
  32930. ctrl.$validate();
  32931. }
  32932. });
  32933. }
  32934. };
  32935. }];
  32936. /**
  32937. * @ngdoc directive
  32938. * @name ngPattern
  32939. * @restrict A
  32940. *
  32941. * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String`
  32942. * parsable into a `RegExp`, or a `RegExp` literal. See above for
  32943. * more details.
  32944. *
  32945. * @description
  32946. *
  32947. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32948. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  32949. *
  32950. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  32951. * does not match a RegExp which is obtained from the `ngPattern` attribute value:
  32952. * - the value is an AngularJS expression:
  32953. * - If the expression evaluates to a RegExp object, then this is used directly.
  32954. * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  32955. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  32956. * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly.
  32957. *
  32958. * <div class="alert alert-info">
  32959. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32960. * start at the index of the last search's match, thus not taking the whole input value into
  32961. * account.
  32962. * </div>
  32963. *
  32964. * <div class="alert alert-info">
  32965. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  32966. * differences:
  32967. * <ol>
  32968. * <li>
  32969. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  32970. * not available.
  32971. * </li>
  32972. * <li>
  32973. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  32974. * interpolated.
  32975. * </li>
  32976. * </ol>
  32977. * </div>
  32978. *
  32979. * @example
  32980. * <example name="ngPatternDirective" module="ngPatternExample">
  32981. * <file name="index.html">
  32982. * <script>
  32983. * angular.module('ngPatternExample', [])
  32984. * .controller('ExampleController', ['$scope', function($scope) {
  32985. * $scope.regex = '\\d+';
  32986. * }]);
  32987. * </script>
  32988. * <div ng-controller="ExampleController">
  32989. * <form name="form">
  32990. * <label for="regex">Set a pattern (regex string): </label>
  32991. * <input type="text" ng-model="regex" id="regex" />
  32992. * <br>
  32993. * <label for="input">This input is restricted by the current pattern: </label>
  32994. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  32995. * <hr>
  32996. * input valid? = <code>{{form.input.$valid}}</code><br>
  32997. * model = <code>{{model}}</code>
  32998. * </form>
  32999. * </div>
  33000. * </file>
  33001. * <file name="protractor.js" type="protractor">
  33002. var model = element(by.binding('model'));
  33003. var input = element(by.id('input'));
  33004. it('should validate the input with the default pattern', function() {
  33005. input.sendKeys('aaa');
  33006. expect(model.getText()).not.toContain('aaa');
  33007. input.clear().then(function() {
  33008. input.sendKeys('123');
  33009. expect(model.getText()).toContain('123');
  33010. });
  33011. });
  33012. * </file>
  33013. * </example>
  33014. */
  33015. var patternDirective = ['$parse', function($parse) {
  33016. return {
  33017. restrict: 'A',
  33018. require: '?ngModel',
  33019. compile: function(tElm, tAttr) {
  33020. var patternExp;
  33021. var parseFn;
  33022. if (tAttr.ngPattern) {
  33023. patternExp = tAttr.ngPattern;
  33024. // ngPattern might be a scope expression, or an inlined regex, which is not parsable.
  33025. // We get value of the attribute here, so we can compare the old and the new value
  33026. // in the observer to avoid unnecessary validations
  33027. if (tAttr.ngPattern.charAt(0) === '/' && REGEX_STRING_REGEXP.test(tAttr.ngPattern)) {
  33028. parseFn = function() { return tAttr.ngPattern; };
  33029. } else {
  33030. parseFn = $parse(tAttr.ngPattern);
  33031. }
  33032. }
  33033. return function(scope, elm, attr, ctrl) {
  33034. if (!ctrl) return;
  33035. var attrVal = attr.pattern;
  33036. if (attr.ngPattern) {
  33037. attrVal = parseFn(scope);
  33038. } else {
  33039. patternExp = attr.pattern;
  33040. }
  33041. var regexp = parsePatternAttr(attrVal, patternExp, elm);
  33042. attr.$observe('pattern', function(newVal) {
  33043. var oldRegexp = regexp;
  33044. regexp = parsePatternAttr(newVal, patternExp, elm);
  33045. if ((oldRegexp && oldRegexp.toString()) !== (regexp && regexp.toString())) {
  33046. ctrl.$validate();
  33047. }
  33048. });
  33049. ctrl.$validators.pattern = function(modelValue, viewValue) {
  33050. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  33051. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  33052. };
  33053. };
  33054. }
  33055. };
  33056. }];
  33057. /**
  33058. * @ngdoc directive
  33059. * @name ngMaxlength
  33060. * @restrict A
  33061. *
  33062. * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String`
  33063. * parsable into a `Number`. Used as value for the `maxlength`
  33064. * {@link ngModel.NgModelController#$validators validator}.
  33065. *
  33066. * @description
  33067. *
  33068. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  33069. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  33070. *
  33071. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  33072. * is longer than the integer obtained by evaluating the AngularJS expression given in the
  33073. * `ngMaxlength` attribute value.
  33074. *
  33075. * <div class="alert alert-info">
  33076. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  33077. * differences:
  33078. * <ol>
  33079. * <li>
  33080. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  33081. * validation is not available.
  33082. * </li>
  33083. * <li>
  33084. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  33085. * interpolated.
  33086. * </li>
  33087. * </ol>
  33088. * </div>
  33089. *
  33090. * @example
  33091. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  33092. * <file name="index.html">
  33093. * <script>
  33094. * angular.module('ngMaxlengthExample', [])
  33095. * .controller('ExampleController', ['$scope', function($scope) {
  33096. * $scope.maxlength = 5;
  33097. * }]);
  33098. * </script>
  33099. * <div ng-controller="ExampleController">
  33100. * <form name="form">
  33101. * <label for="maxlength">Set a maxlength: </label>
  33102. * <input type="number" ng-model="maxlength" id="maxlength" />
  33103. * <br>
  33104. * <label for="input">This input is restricted by the current maxlength: </label>
  33105. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  33106. * <hr>
  33107. * input valid? = <code>{{form.input.$valid}}</code><br>
  33108. * model = <code>{{model}}</code>
  33109. * </form>
  33110. * </div>
  33111. * </file>
  33112. * <file name="protractor.js" type="protractor">
  33113. var model = element(by.binding('model'));
  33114. var input = element(by.id('input'));
  33115. it('should validate the input with the default maxlength', function() {
  33116. input.sendKeys('abcdef');
  33117. expect(model.getText()).not.toContain('abcdef');
  33118. input.clear().then(function() {
  33119. input.sendKeys('abcde');
  33120. expect(model.getText()).toContain('abcde');
  33121. });
  33122. });
  33123. * </file>
  33124. * </example>
  33125. */
  33126. var maxlengthDirective = ['$parse', function($parse) {
  33127. return {
  33128. restrict: 'A',
  33129. require: '?ngModel',
  33130. link: function(scope, elm, attr, ctrl) {
  33131. if (!ctrl) return;
  33132. var maxlength = attr.maxlength || $parse(attr.ngMaxlength)(scope);
  33133. var maxlengthParsed = parseLength(maxlength);
  33134. attr.$observe('maxlength', function(value) {
  33135. if (maxlength !== value) {
  33136. maxlengthParsed = parseLength(value);
  33137. maxlength = value;
  33138. ctrl.$validate();
  33139. }
  33140. });
  33141. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  33142. return (maxlengthParsed < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlengthParsed);
  33143. };
  33144. }
  33145. };
  33146. }];
  33147. /**
  33148. * @ngdoc directive
  33149. * @name ngMinlength
  33150. * @restrict A
  33151. *
  33152. * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String`
  33153. * parsable into a `Number`. Used as value for the `minlength`
  33154. * {@link ngModel.NgModelController#$validators validator}.
  33155. *
  33156. * @description
  33157. *
  33158. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  33159. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  33160. *
  33161. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  33162. * is shorter than the integer obtained by evaluating the AngularJS expression given in the
  33163. * `ngMinlength` attribute value.
  33164. *
  33165. * <div class="alert alert-info">
  33166. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  33167. * differences:
  33168. * <ol>
  33169. * <li>
  33170. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  33171. * validation is not available.
  33172. * </li>
  33173. * <li>
  33174. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  33175. * interpolated.
  33176. * </li>
  33177. * </ol>
  33178. * </div>
  33179. *
  33180. * @example
  33181. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  33182. * <file name="index.html">
  33183. * <script>
  33184. * angular.module('ngMinlengthExample', [])
  33185. * .controller('ExampleController', ['$scope', function($scope) {
  33186. * $scope.minlength = 3;
  33187. * }]);
  33188. * </script>
  33189. * <div ng-controller="ExampleController">
  33190. * <form name="form">
  33191. * <label for="minlength">Set a minlength: </label>
  33192. * <input type="number" ng-model="minlength" id="minlength" />
  33193. * <br>
  33194. * <label for="input">This input is restricted by the current minlength: </label>
  33195. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  33196. * <hr>
  33197. * input valid? = <code>{{form.input.$valid}}</code><br>
  33198. * model = <code>{{model}}</code>
  33199. * </form>
  33200. * </div>
  33201. * </file>
  33202. * <file name="protractor.js" type="protractor">
  33203. var model = element(by.binding('model'));
  33204. var input = element(by.id('input'));
  33205. it('should validate the input with the default minlength', function() {
  33206. input.sendKeys('ab');
  33207. expect(model.getText()).not.toContain('ab');
  33208. input.sendKeys('abc');
  33209. expect(model.getText()).toContain('abc');
  33210. });
  33211. * </file>
  33212. * </example>
  33213. */
  33214. var minlengthDirective = ['$parse', function($parse) {
  33215. return {
  33216. restrict: 'A',
  33217. require: '?ngModel',
  33218. link: function(scope, elm, attr, ctrl) {
  33219. if (!ctrl) return;
  33220. var minlength = attr.minlength || $parse(attr.ngMinlength)(scope);
  33221. var minlengthParsed = parseLength(minlength) || -1;
  33222. attr.$observe('minlength', function(value) {
  33223. if (minlength !== value) {
  33224. minlengthParsed = parseLength(value) || -1;
  33225. minlength = value;
  33226. ctrl.$validate();
  33227. }
  33228. });
  33229. ctrl.$validators.minlength = function(modelValue, viewValue) {
  33230. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlengthParsed;
  33231. };
  33232. }
  33233. };
  33234. }];
  33235. function parsePatternAttr(regex, patternExp, elm) {
  33236. if (!regex) return undefined;
  33237. if (isString(regex)) {
  33238. regex = new RegExp('^' + regex + '$');
  33239. }
  33240. if (!regex.test) {
  33241. throw minErr('ngPattern')('noregexp',
  33242. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  33243. regex, startingTag(elm));
  33244. }
  33245. return regex;
  33246. }
  33247. function parseLength(val) {
  33248. var intVal = toInt(val);
  33249. return isNumberNaN(intVal) ? -1 : intVal;
  33250. }
  33251. if (window.angular.bootstrap) {
  33252. // AngularJS is already loaded, so we can return here...
  33253. if (window.console) {
  33254. console.log('WARNING: Tried to load AngularJS more than once.');
  33255. }
  33256. return;
  33257. }
  33258. // try to bind to jquery now so that one can write jqLite(fn)
  33259. // but we will rebind on bootstrap again.
  33260. bindJQuery();
  33261. publishExternalAPI(angular);
  33262. angular.module("ngLocale", [], ["$provide", function($provide) {
  33263. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  33264. function getDecimals(n) {
  33265. n = n + '';
  33266. var i = n.indexOf('.');
  33267. return (i == -1) ? 0 : n.length - i - 1;
  33268. }
  33269. function getVF(n, opt_precision) {
  33270. var v = opt_precision;
  33271. if (undefined === v) {
  33272. v = Math.min(getDecimals(n), 3);
  33273. }
  33274. var base = Math.pow(10, v);
  33275. var f = ((n * base) | 0) % base;
  33276. return {v: v, f: f};
  33277. }
  33278. $provide.value("$locale", {
  33279. "DATETIME_FORMATS": {
  33280. "AMPMS": [
  33281. "AM",
  33282. "PM"
  33283. ],
  33284. "DAY": [
  33285. "Sunday",
  33286. "Monday",
  33287. "Tuesday",
  33288. "Wednesday",
  33289. "Thursday",
  33290. "Friday",
  33291. "Saturday"
  33292. ],
  33293. "ERANAMES": [
  33294. "Before Christ",
  33295. "Anno Domini"
  33296. ],
  33297. "ERAS": [
  33298. "BC",
  33299. "AD"
  33300. ],
  33301. "FIRSTDAYOFWEEK": 6,
  33302. "MONTH": [
  33303. "January",
  33304. "February",
  33305. "March",
  33306. "April",
  33307. "May",
  33308. "June",
  33309. "July",
  33310. "August",
  33311. "September",
  33312. "October",
  33313. "November",
  33314. "December"
  33315. ],
  33316. "SHORTDAY": [
  33317. "Sun",
  33318. "Mon",
  33319. "Tue",
  33320. "Wed",
  33321. "Thu",
  33322. "Fri",
  33323. "Sat"
  33324. ],
  33325. "SHORTMONTH": [
  33326. "Jan",
  33327. "Feb",
  33328. "Mar",
  33329. "Apr",
  33330. "May",
  33331. "Jun",
  33332. "Jul",
  33333. "Aug",
  33334. "Sep",
  33335. "Oct",
  33336. "Nov",
  33337. "Dec"
  33338. ],
  33339. "STANDALONEMONTH": [
  33340. "January",
  33341. "February",
  33342. "March",
  33343. "April",
  33344. "May",
  33345. "June",
  33346. "July",
  33347. "August",
  33348. "September",
  33349. "October",
  33350. "November",
  33351. "December"
  33352. ],
  33353. "WEEKENDRANGE": [
  33354. 5,
  33355. 6
  33356. ],
  33357. "fullDate": "EEEE, MMMM d, y",
  33358. "longDate": "MMMM d, y",
  33359. "medium": "MMM d, y h:mm:ss a",
  33360. "mediumDate": "MMM d, y",
  33361. "mediumTime": "h:mm:ss a",
  33362. "short": "M/d/yy h:mm a",
  33363. "shortDate": "M/d/yy",
  33364. "shortTime": "h:mm a"
  33365. },
  33366. "NUMBER_FORMATS": {
  33367. "CURRENCY_SYM": "$",
  33368. "DECIMAL_SEP": ".",
  33369. "GROUP_SEP": ",",
  33370. "PATTERNS": [
  33371. {
  33372. "gSize": 3,
  33373. "lgSize": 3,
  33374. "maxFrac": 3,
  33375. "minFrac": 0,
  33376. "minInt": 1,
  33377. "negPre": "-",
  33378. "negSuf": "",
  33379. "posPre": "",
  33380. "posSuf": ""
  33381. },
  33382. {
  33383. "gSize": 3,
  33384. "lgSize": 3,
  33385. "maxFrac": 2,
  33386. "minFrac": 2,
  33387. "minInt": 1,
  33388. "negPre": "-\u00a4",
  33389. "negSuf": "",
  33390. "posPre": "\u00a4",
  33391. "posSuf": ""
  33392. }
  33393. ]
  33394. },
  33395. "id": "en-us",
  33396. "localeID": "en_US",
  33397. "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;}
  33398. });
  33399. }]);
  33400. jqLite(function() {
  33401. angularInit(window.document, bootstrap);
  33402. });
  33403. })(window);
  33404. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend(window.angular.element('<style>').text('@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;}'));