angular.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359
  1. /**
  2. * @license AngularJS v1.6.9
  3. * (c) 2010-2018 Google, Inc. 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. };
  15. /**
  16. * @ngdoc function
  17. * @name angular.errorHandlingConfig
  18. * @module ng
  19. * @kind function
  20. *
  21. * @description
  22. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  23. * current configuration if used as a getter. The following options are supported:
  24. *
  25. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  26. *
  27. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  28. *
  29. * @param {Object=} config - The configuration object. May only contain the options that need to be
  30. * updated. Supported keys:
  31. *
  32. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  33. * non-positive or non-numeric value, removes the max depth limit.
  34. * Default: 5
  35. */
  36. function errorHandlingConfig(config) {
  37. if (isObject(config)) {
  38. if (isDefined(config.objectMaxDepth)) {
  39. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  40. }
  41. } else {
  42. return minErrConfig;
  43. }
  44. }
  45. /**
  46. * @private
  47. * @param {Number} maxDepth
  48. * @return {boolean}
  49. */
  50. function isValidObjectMaxDepth(maxDepth) {
  51. return isNumber(maxDepth) && maxDepth > 0;
  52. }
  53. /**
  54. * @description
  55. *
  56. * This object provides a utility for producing rich Error messages within
  57. * AngularJS. It can be called as follows:
  58. *
  59. * var exampleMinErr = minErr('example');
  60. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  61. *
  62. * The above creates an instance of minErr in the example namespace. The
  63. * resulting error will have a namespaced error code of example.one. The
  64. * resulting error will replace {0} with the value of foo, and {1} with the
  65. * value of bar. The object is not restricted in the number of arguments it can
  66. * take.
  67. *
  68. * If fewer arguments are specified than necessary for interpolation, the extra
  69. * interpolation markers will be preserved in the final string.
  70. *
  71. * Since data will be parsed statically during a build step, some restrictions
  72. * are applied with respect to how minErr instances are created and called.
  73. * Instances should have names of the form namespaceMinErr for a minErr created
  74. * using minErr('namespace') . Error codes, namespaces and template strings
  75. * should all be static strings, not variables or general expressions.
  76. *
  77. * @param {string} module The namespace to use for the new minErr instance.
  78. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  79. * error from returned function, for cases when a particular type of error is useful.
  80. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  81. */
  82. function minErr(module, ErrorConstructor) {
  83. ErrorConstructor = ErrorConstructor || Error;
  84. return function() {
  85. var code = arguments[0],
  86. template = arguments[1],
  87. message = '[' + (module ? module + ':' : '') + code + '] ',
  88. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  89. return toDebugString(arg, minErrConfig.objectMaxDepth);
  90. }),
  91. paramPrefix, i;
  92. message += template.replace(/\{\d+\}/g, function(match) {
  93. var index = +match.slice(1, -1);
  94. if (index < templateArgs.length) {
  95. return templateArgs[index];
  96. }
  97. return match;
  98. });
  99. message += '\nhttp://errors.angularjs.org/1.6.9/' +
  100. (module ? module + '/' : '') + code;
  101. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  102. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  103. }
  104. return new ErrorConstructor(message);
  105. };
  106. }
  107. /* We need to tell ESLint what variables are being exported */
  108. /* exported
  109. angular,
  110. msie,
  111. jqLite,
  112. jQuery,
  113. slice,
  114. splice,
  115. push,
  116. toString,
  117. minErrConfig,
  118. errorHandlingConfig,
  119. isValidObjectMaxDepth,
  120. ngMinErr,
  121. angularModule,
  122. uid,
  123. REGEX_STRING_REGEXP,
  124. VALIDITY_STATE_PROPERTY,
  125. lowercase,
  126. uppercase,
  127. manualLowercase,
  128. manualUppercase,
  129. nodeName_,
  130. isArrayLike,
  131. forEach,
  132. forEachSorted,
  133. reverseParams,
  134. nextUid,
  135. setHashKey,
  136. extend,
  137. toInt,
  138. inherit,
  139. merge,
  140. noop,
  141. identity,
  142. valueFn,
  143. isUndefined,
  144. isDefined,
  145. isObject,
  146. isBlankObject,
  147. isString,
  148. isNumber,
  149. isNumberNaN,
  150. isDate,
  151. isError,
  152. isArray,
  153. isFunction,
  154. isRegExp,
  155. isWindow,
  156. isScope,
  157. isFile,
  158. isFormData,
  159. isBlob,
  160. isBoolean,
  161. isPromiseLike,
  162. trim,
  163. escapeForRegexp,
  164. isElement,
  165. makeMap,
  166. includes,
  167. arrayRemove,
  168. copy,
  169. simpleCompare,
  170. equals,
  171. csp,
  172. jq,
  173. concat,
  174. sliceArgs,
  175. bind,
  176. toJsonReplacer,
  177. toJson,
  178. fromJson,
  179. convertTimezoneToLocal,
  180. timezoneToOffset,
  181. startingTag,
  182. tryDecodeURIComponent,
  183. parseKeyValue,
  184. toKeyValue,
  185. encodeUriSegment,
  186. encodeUriQuery,
  187. angularInit,
  188. bootstrap,
  189. getTestability,
  190. snake_case,
  191. bindJQuery,
  192. assertArg,
  193. assertArgFn,
  194. assertNotHasOwnProperty,
  195. getter,
  196. getBlockNodes,
  197. hasOwnProperty,
  198. createMap,
  199. stringify,
  200. NODE_TYPE_ELEMENT,
  201. NODE_TYPE_ATTRIBUTE,
  202. NODE_TYPE_TEXT,
  203. NODE_TYPE_COMMENT,
  204. NODE_TYPE_DOCUMENT,
  205. NODE_TYPE_DOCUMENT_FRAGMENT
  206. */
  207. ////////////////////////////////////
  208. /**
  209. * @ngdoc module
  210. * @name ng
  211. * @module ng
  212. * @installation
  213. * @description
  214. *
  215. * The ng module is loaded by default when an AngularJS application is started. The module itself
  216. * contains the essential components for an AngularJS application to function. The table below
  217. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  218. * components available within this core module.
  219. *
  220. */
  221. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  222. // The name of a form control's ValidityState property.
  223. // This is used so that it's possible for internal tests to create mock ValidityStates.
  224. var VALIDITY_STATE_PROPERTY = 'validity';
  225. var hasOwnProperty = Object.prototype.hasOwnProperty;
  226. /**
  227. * @ngdoc function
  228. * @name angular.lowercase
  229. * @module ng
  230. * @kind function
  231. *
  232. * @deprecated
  233. * sinceVersion="1.5.0"
  234. * removeVersion="1.7.0"
  235. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  236. *
  237. * @description Converts the specified string to lowercase.
  238. * @param {string} string String to be converted to lowercase.
  239. * @returns {string} Lowercased string.
  240. */
  241. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  242. /**
  243. * @ngdoc function
  244. * @name angular.uppercase
  245. * @module ng
  246. * @kind function
  247. *
  248. * @deprecated
  249. * sinceVersion="1.5.0"
  250. * removeVersion="1.7.0"
  251. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  252. *
  253. * @description Converts the specified string to uppercase.
  254. * @param {string} string String to be converted to uppercase.
  255. * @returns {string} Uppercased string.
  256. */
  257. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  258. var manualLowercase = function(s) {
  259. /* eslint-disable no-bitwise */
  260. return isString(s)
  261. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  262. : s;
  263. /* eslint-enable */
  264. };
  265. var manualUppercase = function(s) {
  266. /* eslint-disable no-bitwise */
  267. return isString(s)
  268. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  269. : s;
  270. /* eslint-enable */
  271. };
  272. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  273. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  274. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  275. if ('i' !== 'I'.toLowerCase()) {
  276. lowercase = manualLowercase;
  277. uppercase = manualUppercase;
  278. }
  279. var
  280. msie, // holds major version number for IE, or NaN if UA is not IE.
  281. jqLite, // delay binding since jQuery could be loaded after us.
  282. jQuery, // delay binding
  283. slice = [].slice,
  284. splice = [].splice,
  285. push = [].push,
  286. toString = Object.prototype.toString,
  287. getPrototypeOf = Object.getPrototypeOf,
  288. ngMinErr = minErr('ng'),
  289. /** @name angular */
  290. angular = window.angular || (window.angular = {}),
  291. angularModule,
  292. uid = 0;
  293. // Support: IE 9-11 only
  294. /**
  295. * documentMode is an IE-only property
  296. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  297. */
  298. msie = window.document.documentMode;
  299. /**
  300. * @private
  301. * @param {*} obj
  302. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  303. * String ...)
  304. */
  305. function isArrayLike(obj) {
  306. // `null`, `undefined` and `window` are not array-like
  307. if (obj == null || isWindow(obj)) return false;
  308. // arrays, strings and jQuery/jqLite objects are array like
  309. // * jqLite is either the jQuery or jqLite constructor function
  310. // * we have to check the existence of jqLite first as this method is called
  311. // via the forEach method when constructing the jqLite object in the first place
  312. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  313. // Support: iOS 8.2 (not reproducible in simulator)
  314. // "length" in obj used to prevent JIT error (gh-11508)
  315. var length = 'length' in Object(obj) && obj.length;
  316. // NodeList objects (with `item` method) and
  317. // other objects with suitable length characteristics are array-like
  318. return isNumber(length) &&
  319. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  320. }
  321. /**
  322. * @ngdoc function
  323. * @name angular.forEach
  324. * @module ng
  325. * @kind function
  326. *
  327. * @description
  328. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  329. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  330. * is the value of an object property or an array element, `key` is the object property key or
  331. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  332. *
  333. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  334. * using the `hasOwnProperty` method.
  335. *
  336. * Unlike ES262's
  337. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  338. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  339. * return the value provided.
  340. *
  341. ```js
  342. var values = {name: 'misko', gender: 'male'};
  343. var log = [];
  344. angular.forEach(values, function(value, key) {
  345. this.push(key + ': ' + value);
  346. }, log);
  347. expect(log).toEqual(['name: misko', 'gender: male']);
  348. ```
  349. *
  350. * @param {Object|Array} obj Object to iterate over.
  351. * @param {Function} iterator Iterator function.
  352. * @param {Object=} context Object to become context (`this`) for the iterator function.
  353. * @returns {Object|Array} Reference to `obj`.
  354. */
  355. function forEach(obj, iterator, context) {
  356. var key, length;
  357. if (obj) {
  358. if (isFunction(obj)) {
  359. for (key in obj) {
  360. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  361. iterator.call(context, obj[key], key, obj);
  362. }
  363. }
  364. } else if (isArray(obj) || isArrayLike(obj)) {
  365. var isPrimitive = typeof obj !== 'object';
  366. for (key = 0, length = obj.length; key < length; key++) {
  367. if (isPrimitive || key in obj) {
  368. iterator.call(context, obj[key], key, obj);
  369. }
  370. }
  371. } else if (obj.forEach && obj.forEach !== forEach) {
  372. obj.forEach(iterator, context, obj);
  373. } else if (isBlankObject(obj)) {
  374. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  375. for (key in obj) {
  376. iterator.call(context, obj[key], key, obj);
  377. }
  378. } else if (typeof obj.hasOwnProperty === 'function') {
  379. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  380. for (key in obj) {
  381. if (obj.hasOwnProperty(key)) {
  382. iterator.call(context, obj[key], key, obj);
  383. }
  384. }
  385. } else {
  386. // Slow path for objects which do not have a method `hasOwnProperty`
  387. for (key in obj) {
  388. if (hasOwnProperty.call(obj, key)) {
  389. iterator.call(context, obj[key], key, obj);
  390. }
  391. }
  392. }
  393. }
  394. return obj;
  395. }
  396. function forEachSorted(obj, iterator, context) {
  397. var keys = Object.keys(obj).sort();
  398. for (var i = 0; i < keys.length; i++) {
  399. iterator.call(context, obj[keys[i]], keys[i]);
  400. }
  401. return keys;
  402. }
  403. /**
  404. * when using forEach the params are value, key, but it is often useful to have key, value.
  405. * @param {function(string, *)} iteratorFn
  406. * @returns {function(*, string)}
  407. */
  408. function reverseParams(iteratorFn) {
  409. return function(value, key) {iteratorFn(key, value);};
  410. }
  411. /**
  412. * A consistent way of creating unique IDs in angular.
  413. *
  414. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  415. * we hit number precision issues in JavaScript.
  416. *
  417. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  418. *
  419. * @returns {number} an unique alpha-numeric string
  420. */
  421. function nextUid() {
  422. return ++uid;
  423. }
  424. /**
  425. * Set or clear the hashkey for an object.
  426. * @param obj object
  427. * @param h the hashkey (!truthy to delete the hashkey)
  428. */
  429. function setHashKey(obj, h) {
  430. if (h) {
  431. obj.$$hashKey = h;
  432. } else {
  433. delete obj.$$hashKey;
  434. }
  435. }
  436. function baseExtend(dst, objs, deep) {
  437. var h = dst.$$hashKey;
  438. for (var i = 0, ii = objs.length; i < ii; ++i) {
  439. var obj = objs[i];
  440. if (!isObject(obj) && !isFunction(obj)) continue;
  441. var keys = Object.keys(obj);
  442. for (var j = 0, jj = keys.length; j < jj; j++) {
  443. var key = keys[j];
  444. var src = obj[key];
  445. if (deep && isObject(src)) {
  446. if (isDate(src)) {
  447. dst[key] = new Date(src.valueOf());
  448. } else if (isRegExp(src)) {
  449. dst[key] = new RegExp(src);
  450. } else if (src.nodeName) {
  451. dst[key] = src.cloneNode(true);
  452. } else if (isElement(src)) {
  453. dst[key] = src.clone();
  454. } else {
  455. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  456. baseExtend(dst[key], [src], true);
  457. }
  458. } else {
  459. dst[key] = src;
  460. }
  461. }
  462. }
  463. setHashKey(dst, h);
  464. return dst;
  465. }
  466. /**
  467. * @ngdoc function
  468. * @name angular.extend
  469. * @module ng
  470. * @kind function
  471. *
  472. * @description
  473. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  474. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  475. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  476. *
  477. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  478. * {@link angular.merge} for this.
  479. *
  480. * @param {Object} dst Destination object.
  481. * @param {...Object} src Source object(s).
  482. * @returns {Object} Reference to `dst`.
  483. */
  484. function extend(dst) {
  485. return baseExtend(dst, slice.call(arguments, 1), false);
  486. }
  487. /**
  488. * @ngdoc function
  489. * @name angular.merge
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  495. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  496. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  497. *
  498. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  499. * objects, performing a deep copy.
  500. *
  501. * @deprecated
  502. * sinceVersion="1.6.5"
  503. * This function is deprecated, but will not be removed in the 1.x lifecycle.
  504. * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
  505. * supported by this function. We suggest
  506. * using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead.
  507. *
  508. * @knownIssue
  509. * This is a list of (known) object types that are not handled correctly by this function:
  510. * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
  511. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  512. * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
  513. * - AngularJS {@link $rootScope.Scope scopes};
  514. *
  515. * @param {Object} dst Destination object.
  516. * @param {...Object} src Source object(s).
  517. * @returns {Object} Reference to `dst`.
  518. */
  519. function merge(dst) {
  520. return baseExtend(dst, slice.call(arguments, 1), true);
  521. }
  522. function toInt(str) {
  523. return parseInt(str, 10);
  524. }
  525. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  526. // eslint-disable-next-line no-self-compare
  527. return num !== num;
  528. };
  529. function inherit(parent, extra) {
  530. return extend(Object.create(parent), extra);
  531. }
  532. /**
  533. * @ngdoc function
  534. * @name angular.noop
  535. * @module ng
  536. * @kind function
  537. *
  538. * @description
  539. * A function that performs no operations. This function can be useful when writing code in the
  540. * functional style.
  541. ```js
  542. function foo(callback) {
  543. var result = calculateResult();
  544. (callback || angular.noop)(result);
  545. }
  546. ```
  547. */
  548. function noop() {}
  549. noop.$inject = [];
  550. /**
  551. * @ngdoc function
  552. * @name angular.identity
  553. * @module ng
  554. * @kind function
  555. *
  556. * @description
  557. * A function that returns its first argument. This function is useful when writing code in the
  558. * functional style.
  559. *
  560. ```js
  561. function transformer(transformationFn, value) {
  562. return (transformationFn || angular.identity)(value);
  563. };
  564. // E.g.
  565. function getResult(fn, input) {
  566. return (fn || angular.identity)(input);
  567. };
  568. getResult(function(n) { return n * 2; }, 21); // returns 42
  569. getResult(null, 21); // returns 21
  570. getResult(undefined, 21); // returns 21
  571. ```
  572. *
  573. * @param {*} value to be returned.
  574. * @returns {*} the value passed in.
  575. */
  576. function identity($) {return $;}
  577. identity.$inject = [];
  578. function valueFn(value) {return function valueRef() {return value;};}
  579. function hasCustomToString(obj) {
  580. return isFunction(obj.toString) && obj.toString !== toString;
  581. }
  582. /**
  583. * @ngdoc function
  584. * @name angular.isUndefined
  585. * @module ng
  586. * @kind function
  587. *
  588. * @description
  589. * Determines if a reference is undefined.
  590. *
  591. * @param {*} value Reference to check.
  592. * @returns {boolean} True if `value` is undefined.
  593. */
  594. function isUndefined(value) {return typeof value === 'undefined';}
  595. /**
  596. * @ngdoc function
  597. * @name angular.isDefined
  598. * @module ng
  599. * @kind function
  600. *
  601. * @description
  602. * Determines if a reference is defined.
  603. *
  604. * @param {*} value Reference to check.
  605. * @returns {boolean} True if `value` is defined.
  606. */
  607. function isDefined(value) {return typeof value !== 'undefined';}
  608. /**
  609. * @ngdoc function
  610. * @name angular.isObject
  611. * @module ng
  612. * @kind function
  613. *
  614. * @description
  615. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  616. * considered to be objects. Note that JavaScript arrays are objects.
  617. *
  618. * @param {*} value Reference to check.
  619. * @returns {boolean} True if `value` is an `Object` but not `null`.
  620. */
  621. function isObject(value) {
  622. // http://jsperf.com/isobject4
  623. return value !== null && typeof value === 'object';
  624. }
  625. /**
  626. * Determine if a value is an object with a null prototype
  627. *
  628. * @returns {boolean} True if `value` is an `Object` with a null prototype
  629. */
  630. function isBlankObject(value) {
  631. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  632. }
  633. /**
  634. * @ngdoc function
  635. * @name angular.isString
  636. * @module ng
  637. * @kind function
  638. *
  639. * @description
  640. * Determines if a reference is a `String`.
  641. *
  642. * @param {*} value Reference to check.
  643. * @returns {boolean} True if `value` is a `String`.
  644. */
  645. function isString(value) {return typeof value === 'string';}
  646. /**
  647. * @ngdoc function
  648. * @name angular.isNumber
  649. * @module ng
  650. * @kind function
  651. *
  652. * @description
  653. * Determines if a reference is a `Number`.
  654. *
  655. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  656. *
  657. * If you wish to exclude these then you can use the native
  658. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  659. * method.
  660. *
  661. * @param {*} value Reference to check.
  662. * @returns {boolean} True if `value` is a `Number`.
  663. */
  664. function isNumber(value) {return typeof value === 'number';}
  665. /**
  666. * @ngdoc function
  667. * @name angular.isDate
  668. * @module ng
  669. * @kind function
  670. *
  671. * @description
  672. * Determines if a value is a date.
  673. *
  674. * @param {*} value Reference to check.
  675. * @returns {boolean} True if `value` is a `Date`.
  676. */
  677. function isDate(value) {
  678. return toString.call(value) === '[object Date]';
  679. }
  680. /**
  681. * @ngdoc function
  682. * @name angular.isArray
  683. * @module ng
  684. * @kind function
  685. *
  686. * @description
  687. * Determines if a reference is an `Array`. Alias of Array.isArray.
  688. *
  689. * @param {*} value Reference to check.
  690. * @returns {boolean} True if `value` is an `Array`.
  691. */
  692. var isArray = Array.isArray;
  693. /**
  694. * @description
  695. * Determines if a reference is an `Error`.
  696. * Loosely based on https://www.npmjs.com/package/iserror
  697. *
  698. * @param {*} value Reference to check.
  699. * @returns {boolean} True if `value` is an `Error`.
  700. */
  701. function isError(value) {
  702. var tag = toString.call(value);
  703. switch (tag) {
  704. case '[object Error]': return true;
  705. case '[object Exception]': return true;
  706. case '[object DOMException]': return true;
  707. default: return value instanceof Error;
  708. }
  709. }
  710. /**
  711. * @ngdoc function
  712. * @name angular.isFunction
  713. * @module ng
  714. * @kind function
  715. *
  716. * @description
  717. * Determines if a reference is a `Function`.
  718. *
  719. * @param {*} value Reference to check.
  720. * @returns {boolean} True if `value` is a `Function`.
  721. */
  722. function isFunction(value) {return typeof value === 'function';}
  723. /**
  724. * Determines if a value is a regular expression object.
  725. *
  726. * @private
  727. * @param {*} value Reference to check.
  728. * @returns {boolean} True if `value` is a `RegExp`.
  729. */
  730. function isRegExp(value) {
  731. return toString.call(value) === '[object RegExp]';
  732. }
  733. /**
  734. * Checks if `obj` is a window object.
  735. *
  736. * @private
  737. * @param {*} obj Object to check
  738. * @returns {boolean} True if `obj` is a window obj.
  739. */
  740. function isWindow(obj) {
  741. return obj && obj.window === obj;
  742. }
  743. function isScope(obj) {
  744. return obj && obj.$evalAsync && obj.$watch;
  745. }
  746. function isFile(obj) {
  747. return toString.call(obj) === '[object File]';
  748. }
  749. function isFormData(obj) {
  750. return toString.call(obj) === '[object FormData]';
  751. }
  752. function isBlob(obj) {
  753. return toString.call(obj) === '[object Blob]';
  754. }
  755. function isBoolean(value) {
  756. return typeof value === 'boolean';
  757. }
  758. function isPromiseLike(obj) {
  759. return obj && isFunction(obj.then);
  760. }
  761. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  762. function isTypedArray(value) {
  763. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  764. }
  765. function isArrayBuffer(obj) {
  766. return toString.call(obj) === '[object ArrayBuffer]';
  767. }
  768. var trim = function(value) {
  769. return isString(value) ? value.trim() : value;
  770. };
  771. // Copied from:
  772. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  773. // Prereq: s is a string.
  774. var escapeForRegexp = function(s) {
  775. return s
  776. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  777. // eslint-disable-next-line no-control-regex
  778. .replace(/\x08/g, '\\x08');
  779. };
  780. /**
  781. * @ngdoc function
  782. * @name angular.isElement
  783. * @module ng
  784. * @kind function
  785. *
  786. * @description
  787. * Determines if a reference is a DOM element (or wrapped jQuery element).
  788. *
  789. * @param {*} value Reference to check.
  790. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  791. */
  792. function isElement(node) {
  793. return !!(node &&
  794. (node.nodeName // We are a direct element.
  795. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  796. }
  797. /**
  798. * @param str 'key1,key2,...'
  799. * @returns {object} in the form of {key1:true, key2:true, ...}
  800. */
  801. function makeMap(str) {
  802. var obj = {}, items = str.split(','), i;
  803. for (i = 0; i < items.length; i++) {
  804. obj[items[i]] = true;
  805. }
  806. return obj;
  807. }
  808. function nodeName_(element) {
  809. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  810. }
  811. function includes(array, obj) {
  812. return Array.prototype.indexOf.call(array, obj) !== -1;
  813. }
  814. function arrayRemove(array, value) {
  815. var index = array.indexOf(value);
  816. if (index >= 0) {
  817. array.splice(index, 1);
  818. }
  819. return index;
  820. }
  821. /**
  822. * @ngdoc function
  823. * @name angular.copy
  824. * @module ng
  825. * @kind function
  826. *
  827. * @description
  828. * Creates a deep copy of `source`, which should be an object or an array.
  829. *
  830. * * If no destination is supplied, a copy of the object or array is created.
  831. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  832. * are deleted and then all elements/properties from the source are copied to it.
  833. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  834. * * If `source` is identical to `destination` an exception will be thrown.
  835. *
  836. * <br />
  837. * <div class="alert alert-warning">
  838. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  839. * and on `destination`) will be ignored.
  840. * </div>
  841. *
  842. * @param {*} source The source that will be used to make a copy.
  843. * Can be any type, including primitives, `null`, and `undefined`.
  844. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  845. * provided, must be of the same type as `source`.
  846. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  847. *
  848. * @example
  849. <example module="copyExample" name="angular-copy">
  850. <file name="index.html">
  851. <div ng-controller="ExampleController">
  852. <form novalidate class="simple-form">
  853. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  854. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  855. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  856. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  857. <button ng-click="reset()">RESET</button>
  858. <button ng-click="update(user)">SAVE</button>
  859. </form>
  860. <pre>form = {{user | json}}</pre>
  861. <pre>leader = {{leader | json}}</pre>
  862. </div>
  863. </file>
  864. <file name="script.js">
  865. // Module: copyExample
  866. angular.
  867. module('copyExample', []).
  868. controller('ExampleController', ['$scope', function($scope) {
  869. $scope.leader = {};
  870. $scope.reset = function() {
  871. // Example with 1 argument
  872. $scope.user = angular.copy($scope.leader);
  873. };
  874. $scope.update = function(user) {
  875. // Example with 2 arguments
  876. angular.copy(user, $scope.leader);
  877. };
  878. $scope.reset();
  879. }]);
  880. </file>
  881. </example>
  882. */
  883. function copy(source, destination, maxDepth) {
  884. var stackSource = [];
  885. var stackDest = [];
  886. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  887. if (destination) {
  888. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  889. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  890. }
  891. if (source === destination) {
  892. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  893. }
  894. // Empty the destination object
  895. if (isArray(destination)) {
  896. destination.length = 0;
  897. } else {
  898. forEach(destination, function(value, key) {
  899. if (key !== '$$hashKey') {
  900. delete destination[key];
  901. }
  902. });
  903. }
  904. stackSource.push(source);
  905. stackDest.push(destination);
  906. return copyRecurse(source, destination, maxDepth);
  907. }
  908. return copyElement(source, maxDepth);
  909. function copyRecurse(source, destination, maxDepth) {
  910. maxDepth--;
  911. if (maxDepth < 0) {
  912. return '...';
  913. }
  914. var h = destination.$$hashKey;
  915. var key;
  916. if (isArray(source)) {
  917. for (var i = 0, ii = source.length; i < ii; i++) {
  918. destination.push(copyElement(source[i], maxDepth));
  919. }
  920. } else if (isBlankObject(source)) {
  921. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  922. for (key in source) {
  923. destination[key] = copyElement(source[key], maxDepth);
  924. }
  925. } else if (source && typeof source.hasOwnProperty === 'function') {
  926. // Slow path, which must rely on hasOwnProperty
  927. for (key in source) {
  928. if (source.hasOwnProperty(key)) {
  929. destination[key] = copyElement(source[key], maxDepth);
  930. }
  931. }
  932. } else {
  933. // Slowest path --- hasOwnProperty can't be called as a method
  934. for (key in source) {
  935. if (hasOwnProperty.call(source, key)) {
  936. destination[key] = copyElement(source[key], maxDepth);
  937. }
  938. }
  939. }
  940. setHashKey(destination, h);
  941. return destination;
  942. }
  943. function copyElement(source, maxDepth) {
  944. // Simple values
  945. if (!isObject(source)) {
  946. return source;
  947. }
  948. // Already copied values
  949. var index = stackSource.indexOf(source);
  950. if (index !== -1) {
  951. return stackDest[index];
  952. }
  953. if (isWindow(source) || isScope(source)) {
  954. throw ngMinErr('cpws',
  955. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  956. }
  957. var needsRecurse = false;
  958. var destination = copyType(source);
  959. if (destination === undefined) {
  960. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  961. needsRecurse = true;
  962. }
  963. stackSource.push(source);
  964. stackDest.push(destination);
  965. return needsRecurse
  966. ? copyRecurse(source, destination, maxDepth)
  967. : destination;
  968. }
  969. function copyType(source) {
  970. switch (toString.call(source)) {
  971. case '[object Int8Array]':
  972. case '[object Int16Array]':
  973. case '[object Int32Array]':
  974. case '[object Float32Array]':
  975. case '[object Float64Array]':
  976. case '[object Uint8Array]':
  977. case '[object Uint8ClampedArray]':
  978. case '[object Uint16Array]':
  979. case '[object Uint32Array]':
  980. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  981. case '[object ArrayBuffer]':
  982. // Support: IE10
  983. if (!source.slice) {
  984. // If we're in this case we know the environment supports ArrayBuffer
  985. /* eslint-disable no-undef */
  986. var copied = new ArrayBuffer(source.byteLength);
  987. new Uint8Array(copied).set(new Uint8Array(source));
  988. /* eslint-enable */
  989. return copied;
  990. }
  991. return source.slice(0);
  992. case '[object Boolean]':
  993. case '[object Number]':
  994. case '[object String]':
  995. case '[object Date]':
  996. return new source.constructor(source.valueOf());
  997. case '[object RegExp]':
  998. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  999. re.lastIndex = source.lastIndex;
  1000. return re;
  1001. case '[object Blob]':
  1002. return new source.constructor([source], {type: source.type});
  1003. }
  1004. if (isFunction(source.cloneNode)) {
  1005. return source.cloneNode(true);
  1006. }
  1007. }
  1008. }
  1009. // eslint-disable-next-line no-self-compare
  1010. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  1011. /**
  1012. * @ngdoc function
  1013. * @name angular.equals
  1014. * @module ng
  1015. * @kind function
  1016. *
  1017. * @description
  1018. * Determines if two objects or two values are equivalent. Supports value types, regular
  1019. * expressions, arrays and objects.
  1020. *
  1021. * Two objects or values are considered equivalent if at least one of the following is true:
  1022. *
  1023. * * Both objects or values pass `===` comparison.
  1024. * * Both objects or values are of the same type and all of their properties are equal by
  1025. * comparing them with `angular.equals`.
  1026. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  1027. * * Both values represent the same regular expression (In JavaScript,
  1028. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  1029. * representation matches).
  1030. *
  1031. * During a property comparison, properties of `function` type and properties with names
  1032. * that begin with `$` are ignored.
  1033. *
  1034. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1035. *
  1036. * @param {*} o1 Object or value to compare.
  1037. * @param {*} o2 Object or value to compare.
  1038. * @returns {boolean} True if arguments are equal.
  1039. *
  1040. * @example
  1041. <example module="equalsExample" name="equalsExample">
  1042. <file name="index.html">
  1043. <div ng-controller="ExampleController">
  1044. <form novalidate>
  1045. <h3>User 1</h3>
  1046. Name: <input type="text" ng-model="user1.name">
  1047. Age: <input type="number" ng-model="user1.age">
  1048. <h3>User 2</h3>
  1049. Name: <input type="text" ng-model="user2.name">
  1050. Age: <input type="number" ng-model="user2.age">
  1051. <div>
  1052. <br/>
  1053. <input type="button" value="Compare" ng-click="compare()">
  1054. </div>
  1055. User 1: <pre>{{user1 | json}}</pre>
  1056. User 2: <pre>{{user2 | json}}</pre>
  1057. Equal: <pre>{{result}}</pre>
  1058. </form>
  1059. </div>
  1060. </file>
  1061. <file name="script.js">
  1062. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1063. $scope.user1 = {};
  1064. $scope.user2 = {};
  1065. $scope.compare = function() {
  1066. $scope.result = angular.equals($scope.user1, $scope.user2);
  1067. };
  1068. }]);
  1069. </file>
  1070. </example>
  1071. */
  1072. function equals(o1, o2) {
  1073. if (o1 === o2) return true;
  1074. if (o1 === null || o2 === null) return false;
  1075. // eslint-disable-next-line no-self-compare
  1076. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1077. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1078. if (t1 === t2 && t1 === 'object') {
  1079. if (isArray(o1)) {
  1080. if (!isArray(o2)) return false;
  1081. if ((length = o1.length) === o2.length) {
  1082. for (key = 0; key < length; key++) {
  1083. if (!equals(o1[key], o2[key])) return false;
  1084. }
  1085. return true;
  1086. }
  1087. } else if (isDate(o1)) {
  1088. if (!isDate(o2)) return false;
  1089. return simpleCompare(o1.getTime(), o2.getTime());
  1090. } else if (isRegExp(o1)) {
  1091. if (!isRegExp(o2)) return false;
  1092. return o1.toString() === o2.toString();
  1093. } else {
  1094. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1095. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1096. keySet = createMap();
  1097. for (key in o1) {
  1098. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1099. if (!equals(o1[key], o2[key])) return false;
  1100. keySet[key] = true;
  1101. }
  1102. for (key in o2) {
  1103. if (!(key in keySet) &&
  1104. key.charAt(0) !== '$' &&
  1105. isDefined(o2[key]) &&
  1106. !isFunction(o2[key])) return false;
  1107. }
  1108. return true;
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. var csp = function() {
  1114. if (!isDefined(csp.rules)) {
  1115. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1116. window.document.querySelector('[data-ng-csp]'));
  1117. if (ngCspElement) {
  1118. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1119. ngCspElement.getAttribute('data-ng-csp');
  1120. csp.rules = {
  1121. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1122. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1123. };
  1124. } else {
  1125. csp.rules = {
  1126. noUnsafeEval: noUnsafeEval(),
  1127. noInlineStyle: false
  1128. };
  1129. }
  1130. }
  1131. return csp.rules;
  1132. function noUnsafeEval() {
  1133. try {
  1134. // eslint-disable-next-line no-new, no-new-func
  1135. new Function('');
  1136. return false;
  1137. } catch (e) {
  1138. return true;
  1139. }
  1140. }
  1141. };
  1142. /**
  1143. * @ngdoc directive
  1144. * @module ng
  1145. * @name ngJq
  1146. *
  1147. * @element ANY
  1148. * @param {string=} ngJq the name of the library available under `window`
  1149. * to be used for angular.element
  1150. * @description
  1151. * Use this directive to force the angular.element library. This should be
  1152. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1153. * the jquery variable under window (eg. jQuery).
  1154. *
  1155. * Since AngularJS looks for this directive when it is loaded (doesn't wait for the
  1156. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1157. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1158. * others ignored.
  1159. *
  1160. * @example
  1161. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1162. ```html
  1163. <!doctype html>
  1164. <html ng-app ng-jq>
  1165. ...
  1166. ...
  1167. </html>
  1168. ```
  1169. * @example
  1170. * This example shows how to use a jQuery based library of a different name.
  1171. * The library name must be available at the top most 'window'.
  1172. ```html
  1173. <!doctype html>
  1174. <html ng-app ng-jq="jQueryLib">
  1175. ...
  1176. ...
  1177. </html>
  1178. ```
  1179. */
  1180. var jq = function() {
  1181. if (isDefined(jq.name_)) return jq.name_;
  1182. var el;
  1183. var i, ii = ngAttrPrefixes.length, prefix, name;
  1184. for (i = 0; i < ii; ++i) {
  1185. prefix = ngAttrPrefixes[i];
  1186. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1187. if (el) {
  1188. name = el.getAttribute(prefix + 'jq');
  1189. break;
  1190. }
  1191. }
  1192. return (jq.name_ = name);
  1193. };
  1194. function concat(array1, array2, index) {
  1195. return array1.concat(slice.call(array2, index));
  1196. }
  1197. function sliceArgs(args, startIndex) {
  1198. return slice.call(args, startIndex || 0);
  1199. }
  1200. /**
  1201. * @ngdoc function
  1202. * @name angular.bind
  1203. * @module ng
  1204. * @kind function
  1205. *
  1206. * @description
  1207. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1208. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1209. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1210. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1211. *
  1212. * @param {Object} self Context which `fn` should be evaluated in.
  1213. * @param {function()} fn Function to be bound.
  1214. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1215. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1216. */
  1217. function bind(self, fn) {
  1218. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1219. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1220. return curryArgs.length
  1221. ? function() {
  1222. return arguments.length
  1223. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1224. : fn.apply(self, curryArgs);
  1225. }
  1226. : function() {
  1227. return arguments.length
  1228. ? fn.apply(self, arguments)
  1229. : fn.call(self);
  1230. };
  1231. } else {
  1232. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1233. return fn;
  1234. }
  1235. }
  1236. function toJsonReplacer(key, value) {
  1237. var val = value;
  1238. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1239. val = undefined;
  1240. } else if (isWindow(value)) {
  1241. val = '$WINDOW';
  1242. } else if (value && window.document === value) {
  1243. val = '$DOCUMENT';
  1244. } else if (isScope(value)) {
  1245. val = '$SCOPE';
  1246. }
  1247. return val;
  1248. }
  1249. /**
  1250. * @ngdoc function
  1251. * @name angular.toJson
  1252. * @module ng
  1253. * @kind function
  1254. *
  1255. * @description
  1256. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1257. * stripped since AngularJS uses this notation internally.
  1258. *
  1259. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1260. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1261. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1262. * @returns {string|undefined} JSON-ified string representing `obj`.
  1263. * @knownIssue
  1264. *
  1265. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1266. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1267. * `Date.prototype.toJSON` method as follows:
  1268. *
  1269. * ```
  1270. * var _DatetoJSON = Date.prototype.toJSON;
  1271. * Date.prototype.toJSON = function() {
  1272. * try {
  1273. * return _DatetoJSON.call(this);
  1274. * } catch(e) {
  1275. * if (e instanceof RangeError) {
  1276. * return null;
  1277. * }
  1278. * throw e;
  1279. * }
  1280. * };
  1281. * ```
  1282. *
  1283. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1284. */
  1285. function toJson(obj, pretty) {
  1286. if (isUndefined(obj)) return undefined;
  1287. if (!isNumber(pretty)) {
  1288. pretty = pretty ? 2 : null;
  1289. }
  1290. return JSON.stringify(obj, toJsonReplacer, pretty);
  1291. }
  1292. /**
  1293. * @ngdoc function
  1294. * @name angular.fromJson
  1295. * @module ng
  1296. * @kind function
  1297. *
  1298. * @description
  1299. * Deserializes a JSON string.
  1300. *
  1301. * @param {string} json JSON string to deserialize.
  1302. * @returns {Object|Array|string|number} Deserialized JSON string.
  1303. */
  1304. function fromJson(json) {
  1305. return isString(json)
  1306. ? JSON.parse(json)
  1307. : json;
  1308. }
  1309. var ALL_COLONS = /:/g;
  1310. function timezoneToOffset(timezone, fallback) {
  1311. // Support: IE 9-11 only, Edge 13-15+
  1312. // IE/Edge do not "understand" colon (`:`) in timezone
  1313. timezone = timezone.replace(ALL_COLONS, '');
  1314. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1315. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1316. }
  1317. function addDateMinutes(date, minutes) {
  1318. date = new Date(date.getTime());
  1319. date.setMinutes(date.getMinutes() + minutes);
  1320. return date;
  1321. }
  1322. function convertTimezoneToLocal(date, timezone, reverse) {
  1323. reverse = reverse ? -1 : 1;
  1324. var dateTimezoneOffset = date.getTimezoneOffset();
  1325. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1326. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1327. }
  1328. /**
  1329. * @returns {string} Returns the string representation of the element.
  1330. */
  1331. function startingTag(element) {
  1332. element = jqLite(element).clone().empty();
  1333. var elemHtml = jqLite('<div>').append(element).html();
  1334. try {
  1335. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1336. elemHtml.
  1337. match(/^(<[^>]+>)/)[1].
  1338. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1339. } catch (e) {
  1340. return lowercase(elemHtml);
  1341. }
  1342. }
  1343. /////////////////////////////////////////////////
  1344. /**
  1345. * Tries to decode the URI component without throwing an exception.
  1346. *
  1347. * @private
  1348. * @param str value potential URI component to check.
  1349. * @returns {boolean} True if `value` can be decoded
  1350. * with the decodeURIComponent function.
  1351. */
  1352. function tryDecodeURIComponent(value) {
  1353. try {
  1354. return decodeURIComponent(value);
  1355. } catch (e) {
  1356. // Ignore any invalid uri component.
  1357. }
  1358. }
  1359. /**
  1360. * Parses an escaped url query string into key-value pairs.
  1361. * @returns {Object.<string,boolean|Array>}
  1362. */
  1363. function parseKeyValue(/**string*/keyValue) {
  1364. var obj = {};
  1365. forEach((keyValue || '').split('&'), function(keyValue) {
  1366. var splitPoint, key, val;
  1367. if (keyValue) {
  1368. key = keyValue = keyValue.replace(/\+/g,'%20');
  1369. splitPoint = keyValue.indexOf('=');
  1370. if (splitPoint !== -1) {
  1371. key = keyValue.substring(0, splitPoint);
  1372. val = keyValue.substring(splitPoint + 1);
  1373. }
  1374. key = tryDecodeURIComponent(key);
  1375. if (isDefined(key)) {
  1376. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1377. if (!hasOwnProperty.call(obj, key)) {
  1378. obj[key] = val;
  1379. } else if (isArray(obj[key])) {
  1380. obj[key].push(val);
  1381. } else {
  1382. obj[key] = [obj[key],val];
  1383. }
  1384. }
  1385. }
  1386. });
  1387. return obj;
  1388. }
  1389. function toKeyValue(obj) {
  1390. var parts = [];
  1391. forEach(obj, function(value, key) {
  1392. if (isArray(value)) {
  1393. forEach(value, function(arrayValue) {
  1394. parts.push(encodeUriQuery(key, true) +
  1395. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1396. });
  1397. } else {
  1398. parts.push(encodeUriQuery(key, true) +
  1399. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1400. }
  1401. });
  1402. return parts.length ? parts.join('&') : '';
  1403. }
  1404. /**
  1405. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1406. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1407. * segments:
  1408. * segment = *pchar
  1409. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1410. * pct-encoded = "%" HEXDIG HEXDIG
  1411. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1412. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1413. * / "*" / "+" / "," / ";" / "="
  1414. */
  1415. function encodeUriSegment(val) {
  1416. return encodeUriQuery(val, true).
  1417. replace(/%26/gi, '&').
  1418. replace(/%3D/gi, '=').
  1419. replace(/%2B/gi, '+');
  1420. }
  1421. /**
  1422. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1423. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1424. * encoded per http://tools.ietf.org/html/rfc3986:
  1425. * query = *( pchar / "/" / "?" )
  1426. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1427. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1428. * pct-encoded = "%" HEXDIG HEXDIG
  1429. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1430. * / "*" / "+" / "," / ";" / "="
  1431. */
  1432. function encodeUriQuery(val, pctEncodeSpaces) {
  1433. return encodeURIComponent(val).
  1434. replace(/%40/gi, '@').
  1435. replace(/%3A/gi, ':').
  1436. replace(/%24/g, '$').
  1437. replace(/%2C/gi, ',').
  1438. replace(/%3B/gi, ';').
  1439. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1440. }
  1441. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1442. function getNgAttribute(element, ngAttr) {
  1443. var attr, i, ii = ngAttrPrefixes.length;
  1444. for (i = 0; i < ii; ++i) {
  1445. attr = ngAttrPrefixes[i] + ngAttr;
  1446. if (isString(attr = element.getAttribute(attr))) {
  1447. return attr;
  1448. }
  1449. }
  1450. return null;
  1451. }
  1452. function allowAutoBootstrap(document) {
  1453. var script = document.currentScript;
  1454. if (!script) {
  1455. // Support: IE 9-11 only
  1456. // IE does not have `document.currentScript`
  1457. return true;
  1458. }
  1459. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1460. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1461. return false;
  1462. }
  1463. var attributes = script.attributes;
  1464. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1465. return srcs.every(function(src) {
  1466. if (!src) {
  1467. return true;
  1468. }
  1469. if (!src.value) {
  1470. return false;
  1471. }
  1472. var link = document.createElement('a');
  1473. link.href = src.value;
  1474. if (document.location.origin === link.origin) {
  1475. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1476. return true;
  1477. }
  1478. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1479. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1480. // content security policy in web pages and other browser extensions.
  1481. switch (link.protocol) {
  1482. case 'http:':
  1483. case 'https:':
  1484. case 'ftp:':
  1485. case 'blob:':
  1486. case 'file:':
  1487. case 'data:':
  1488. return true;
  1489. default:
  1490. return false;
  1491. }
  1492. });
  1493. }
  1494. // Cached as it has to run during loading so that document.currentScript is available.
  1495. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1496. /**
  1497. * @ngdoc directive
  1498. * @name ngApp
  1499. * @module ng
  1500. *
  1501. * @element ANY
  1502. * @param {angular.Module} ngApp an optional application
  1503. * {@link angular.module module} name to load.
  1504. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1505. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1506. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1507. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1508. * tracking down the root of these bugs.
  1509. *
  1510. * @description
  1511. *
  1512. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1513. * designates the **root element** of the application and is typically placed near the root element
  1514. * of the page - e.g. on the `<body>` or `<html>` tags.
  1515. *
  1516. * There are a few things to keep in mind when using `ngApp`:
  1517. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1518. * found in the document will be used to define the root element to auto-bootstrap as an
  1519. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1520. * {@link angular.bootstrap} instead.
  1521. * - AngularJS applications cannot be nested within each other.
  1522. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1523. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1524. * {@link ngRoute.ngView `ngView`}.
  1525. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1526. * causing animations to stop working and making the injector inaccessible from outside the app.
  1527. *
  1528. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1529. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1530. * should contain the application code needed or have dependencies on other modules that will
  1531. * contain the code. See {@link angular.module} for more information.
  1532. *
  1533. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1534. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1535. * would not be resolved to `3`.
  1536. *
  1537. * @example
  1538. *
  1539. * ### Simple Usage
  1540. *
  1541. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1542. *
  1543. <example module="ngAppDemo" name="ng-app">
  1544. <file name="index.html">
  1545. <div ng-controller="ngAppDemoController">
  1546. I can add: {{a}} + {{b}} = {{ a+b }}
  1547. </div>
  1548. </file>
  1549. <file name="script.js">
  1550. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1551. $scope.a = 1;
  1552. $scope.b = 2;
  1553. });
  1554. </file>
  1555. </example>
  1556. *
  1557. * @example
  1558. *
  1559. * ### With `ngStrictDi`
  1560. *
  1561. * Using `ngStrictDi`, you would see something like this:
  1562. *
  1563. <example ng-app-included="true" name="strict-di">
  1564. <file name="index.html">
  1565. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1566. <div ng-controller="GoodController1">
  1567. I can add: {{a}} + {{b}} = {{ a+b }}
  1568. <p>This renders because the controller does not fail to
  1569. instantiate, by using explicit annotation style (see
  1570. script.js for details)
  1571. </p>
  1572. </div>
  1573. <div ng-controller="GoodController2">
  1574. Name: <input ng-model="name"><br />
  1575. Hello, {{name}}!
  1576. <p>This renders because the controller does not fail to
  1577. instantiate, by using explicit annotation style
  1578. (see script.js for details)
  1579. </p>
  1580. </div>
  1581. <div ng-controller="BadController">
  1582. I can add: {{a}} + {{b}} = {{ a+b }}
  1583. <p>The controller could not be instantiated, due to relying
  1584. on automatic function annotations (which are disabled in
  1585. strict mode). As such, the content of this section is not
  1586. interpolated, and there should be an error in your web console.
  1587. </p>
  1588. </div>
  1589. </div>
  1590. </file>
  1591. <file name="script.js">
  1592. angular.module('ngAppStrictDemo', [])
  1593. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1594. // rather than an explicit annotation
  1595. .controller('BadController', function($scope) {
  1596. $scope.a = 1;
  1597. $scope.b = 2;
  1598. })
  1599. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1600. // due to using explicit annotations using the array style and $inject property, respectively.
  1601. .controller('GoodController1', ['$scope', function($scope) {
  1602. $scope.a = 1;
  1603. $scope.b = 2;
  1604. }])
  1605. .controller('GoodController2', GoodController2);
  1606. function GoodController2($scope) {
  1607. $scope.name = 'World';
  1608. }
  1609. GoodController2.$inject = ['$scope'];
  1610. </file>
  1611. <file name="style.css">
  1612. div[ng-controller] {
  1613. margin-bottom: 1em;
  1614. -webkit-border-radius: 4px;
  1615. border-radius: 4px;
  1616. border: 1px solid;
  1617. padding: .5em;
  1618. }
  1619. div[ng-controller^=Good] {
  1620. border-color: #d6e9c6;
  1621. background-color: #dff0d8;
  1622. color: #3c763d;
  1623. }
  1624. div[ng-controller^=Bad] {
  1625. border-color: #ebccd1;
  1626. background-color: #f2dede;
  1627. color: #a94442;
  1628. margin-bottom: 0;
  1629. }
  1630. </file>
  1631. </example>
  1632. */
  1633. function angularInit(element, bootstrap) {
  1634. var appElement,
  1635. module,
  1636. config = {};
  1637. // The element `element` has priority over any other element.
  1638. forEach(ngAttrPrefixes, function(prefix) {
  1639. var name = prefix + 'app';
  1640. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1641. appElement = element;
  1642. module = element.getAttribute(name);
  1643. }
  1644. });
  1645. forEach(ngAttrPrefixes, function(prefix) {
  1646. var name = prefix + 'app';
  1647. var candidate;
  1648. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1649. appElement = candidate;
  1650. module = candidate.getAttribute(name);
  1651. }
  1652. });
  1653. if (appElement) {
  1654. if (!isAutoBootstrapAllowed) {
  1655. window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' +
  1656. 'an extension, document.location.href does not match.');
  1657. return;
  1658. }
  1659. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1660. bootstrap(appElement, module ? [module] : [], config);
  1661. }
  1662. }
  1663. /**
  1664. * @ngdoc function
  1665. * @name angular.bootstrap
  1666. * @module ng
  1667. * @description
  1668. * Use this function to manually start up AngularJS application.
  1669. *
  1670. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1671. *
  1672. * AngularJS will detect if it has been loaded into the browser more than once and only allow the
  1673. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1674. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1675. * multiple instances of AngularJS try to work on the DOM.
  1676. *
  1677. * <div class="alert alert-warning">
  1678. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1679. * They must use {@link ng.directive:ngApp ngApp}.
  1680. * </div>
  1681. *
  1682. * <div class="alert alert-warning">
  1683. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1684. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1685. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1686. * causing animations to stop working and making the injector inaccessible from outside the app.
  1687. * </div>
  1688. *
  1689. * ```html
  1690. * <!doctype html>
  1691. * <html>
  1692. * <body>
  1693. * <div ng-controller="WelcomeController">
  1694. * {{greeting}}
  1695. * </div>
  1696. *
  1697. * <script src="angular.js"></script>
  1698. * <script>
  1699. * var app = angular.module('demo', [])
  1700. * .controller('WelcomeController', function($scope) {
  1701. * $scope.greeting = 'Welcome!';
  1702. * });
  1703. * angular.bootstrap(document, ['demo']);
  1704. * </script>
  1705. * </body>
  1706. * </html>
  1707. * ```
  1708. *
  1709. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1710. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1711. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1712. * function that will be invoked by the injector as a `config` block.
  1713. * See: {@link angular.module modules}
  1714. * @param {Object=} config an object for defining configuration options for the application. The
  1715. * following keys are supported:
  1716. *
  1717. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1718. * assist in finding bugs which break minified code. Defaults to `false`.
  1719. *
  1720. * @returns {auto.$injector} Returns the newly created injector for this app.
  1721. */
  1722. function bootstrap(element, modules, config) {
  1723. if (!isObject(config)) config = {};
  1724. var defaultConfig = {
  1725. strictDi: false
  1726. };
  1727. config = extend(defaultConfig, config);
  1728. var doBootstrap = function() {
  1729. element = jqLite(element);
  1730. if (element.injector()) {
  1731. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1732. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1733. throw ngMinErr(
  1734. 'btstrpd',
  1735. 'App already bootstrapped with this element \'{0}\'',
  1736. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1737. }
  1738. modules = modules || [];
  1739. modules.unshift(['$provide', function($provide) {
  1740. $provide.value('$rootElement', element);
  1741. }]);
  1742. if (config.debugInfoEnabled) {
  1743. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1744. modules.push(['$compileProvider', function($compileProvider) {
  1745. $compileProvider.debugInfoEnabled(true);
  1746. }]);
  1747. }
  1748. modules.unshift('ng');
  1749. var injector = createInjector(modules, config.strictDi);
  1750. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1751. function bootstrapApply(scope, element, compile, injector) {
  1752. scope.$apply(function() {
  1753. element.data('$injector', injector);
  1754. compile(element)(scope);
  1755. });
  1756. }]
  1757. );
  1758. return injector;
  1759. };
  1760. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1761. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1762. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1763. config.debugInfoEnabled = true;
  1764. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1765. }
  1766. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1767. return doBootstrap();
  1768. }
  1769. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1770. angular.resumeBootstrap = function(extraModules) {
  1771. forEach(extraModules, function(module) {
  1772. modules.push(module);
  1773. });
  1774. return doBootstrap();
  1775. };
  1776. if (isFunction(angular.resumeDeferredBootstrap)) {
  1777. angular.resumeDeferredBootstrap();
  1778. }
  1779. }
  1780. /**
  1781. * @ngdoc function
  1782. * @name angular.reloadWithDebugInfo
  1783. * @module ng
  1784. * @description
  1785. * Use this function to reload the current application with debug information turned on.
  1786. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1787. *
  1788. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1789. */
  1790. function reloadWithDebugInfo() {
  1791. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1792. window.location.reload();
  1793. }
  1794. /**
  1795. * @name angular.getTestability
  1796. * @module ng
  1797. * @description
  1798. * Get the testability service for the instance of AngularJS on the given
  1799. * element.
  1800. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1801. */
  1802. function getTestability(rootElement) {
  1803. var injector = angular.element(rootElement).injector();
  1804. if (!injector) {
  1805. throw ngMinErr('test',
  1806. 'no injector found for element argument to getTestability');
  1807. }
  1808. return injector.get('$$testability');
  1809. }
  1810. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1811. function snake_case(name, separator) {
  1812. separator = separator || '_';
  1813. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1814. return (pos ? separator : '') + letter.toLowerCase();
  1815. });
  1816. }
  1817. var bindJQueryFired = false;
  1818. function bindJQuery() {
  1819. var originalCleanData;
  1820. if (bindJQueryFired) {
  1821. return;
  1822. }
  1823. // bind to jQuery if present;
  1824. var jqName = jq();
  1825. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1826. !jqName ? undefined : // use jqLite
  1827. window[jqName]; // use jQuery specified by `ngJq`
  1828. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1829. // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.
  1830. // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1831. // versions. It will not work for sure with jQuery <1.7, though.
  1832. if (jQuery && jQuery.fn.on) {
  1833. jqLite = jQuery;
  1834. extend(jQuery.fn, {
  1835. scope: JQLitePrototype.scope,
  1836. isolateScope: JQLitePrototype.isolateScope,
  1837. controller: /** @type {?} */ (JQLitePrototype).controller,
  1838. injector: JQLitePrototype.injector,
  1839. inheritedData: JQLitePrototype.inheritedData
  1840. });
  1841. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1842. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1843. // the $destroy event on all removed nodes.
  1844. originalCleanData = jQuery.cleanData;
  1845. jQuery.cleanData = function(elems) {
  1846. var events;
  1847. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1848. events = jQuery._data(elem, 'events');
  1849. if (events && events.$destroy) {
  1850. jQuery(elem).triggerHandler('$destroy');
  1851. }
  1852. }
  1853. originalCleanData(elems);
  1854. };
  1855. } else {
  1856. jqLite = JQLite;
  1857. }
  1858. angular.element = jqLite;
  1859. // Prevent double-proxying.
  1860. bindJQueryFired = true;
  1861. }
  1862. /**
  1863. * throw error if the argument is falsy.
  1864. */
  1865. function assertArg(arg, name, reason) {
  1866. if (!arg) {
  1867. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1868. }
  1869. return arg;
  1870. }
  1871. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1872. if (acceptArrayAnnotation && isArray(arg)) {
  1873. arg = arg[arg.length - 1];
  1874. }
  1875. assertArg(isFunction(arg), name, 'not a function, got ' +
  1876. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1877. return arg;
  1878. }
  1879. /**
  1880. * throw error if the name given is hasOwnProperty
  1881. * @param {String} name the name to test
  1882. * @param {String} context the context in which the name is used, such as module or directive
  1883. */
  1884. function assertNotHasOwnProperty(name, context) {
  1885. if (name === 'hasOwnProperty') {
  1886. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1887. }
  1888. }
  1889. /**
  1890. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1891. * @param {Object} obj starting object
  1892. * @param {String} path path to traverse
  1893. * @param {boolean} [bindFnToScope=true]
  1894. * @returns {Object} value as accessible by path
  1895. */
  1896. //TODO(misko): this function needs to be removed
  1897. function getter(obj, path, bindFnToScope) {
  1898. if (!path) return obj;
  1899. var keys = path.split('.');
  1900. var key;
  1901. var lastInstance = obj;
  1902. var len = keys.length;
  1903. for (var i = 0; i < len; i++) {
  1904. key = keys[i];
  1905. if (obj) {
  1906. obj = (lastInstance = obj)[key];
  1907. }
  1908. }
  1909. if (!bindFnToScope && isFunction(obj)) {
  1910. return bind(lastInstance, obj);
  1911. }
  1912. return obj;
  1913. }
  1914. /**
  1915. * Return the DOM siblings between the first and last node in the given array.
  1916. * @param {Array} array like object
  1917. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1918. */
  1919. function getBlockNodes(nodes) {
  1920. // TODO(perf): update `nodes` instead of creating a new object?
  1921. var node = nodes[0];
  1922. var endNode = nodes[nodes.length - 1];
  1923. var blockNodes;
  1924. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1925. if (blockNodes || nodes[i] !== node) {
  1926. if (!blockNodes) {
  1927. blockNodes = jqLite(slice.call(nodes, 0, i));
  1928. }
  1929. blockNodes.push(node);
  1930. }
  1931. }
  1932. return blockNodes || nodes;
  1933. }
  1934. /**
  1935. * Creates a new object without a prototype. This object is useful for lookup without having to
  1936. * guard against prototypically inherited properties via hasOwnProperty.
  1937. *
  1938. * Related micro-benchmarks:
  1939. * - http://jsperf.com/object-create2
  1940. * - http://jsperf.com/proto-map-lookup/2
  1941. * - http://jsperf.com/for-in-vs-object-keys2
  1942. *
  1943. * @returns {Object}
  1944. */
  1945. function createMap() {
  1946. return Object.create(null);
  1947. }
  1948. function stringify(value) {
  1949. if (value == null) { // null || undefined
  1950. return '';
  1951. }
  1952. switch (typeof value) {
  1953. case 'string':
  1954. break;
  1955. case 'number':
  1956. value = '' + value;
  1957. break;
  1958. default:
  1959. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1960. value = value.toString();
  1961. } else {
  1962. value = toJson(value);
  1963. }
  1964. }
  1965. return value;
  1966. }
  1967. var NODE_TYPE_ELEMENT = 1;
  1968. var NODE_TYPE_ATTRIBUTE = 2;
  1969. var NODE_TYPE_TEXT = 3;
  1970. var NODE_TYPE_COMMENT = 8;
  1971. var NODE_TYPE_DOCUMENT = 9;
  1972. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1973. /**
  1974. * @ngdoc type
  1975. * @name angular.Module
  1976. * @module ng
  1977. * @description
  1978. *
  1979. * Interface for configuring AngularJS {@link angular.module modules}.
  1980. */
  1981. function setupModuleLoader(window) {
  1982. var $injectorMinErr = minErr('$injector');
  1983. var ngMinErr = minErr('ng');
  1984. function ensure(obj, name, factory) {
  1985. return obj[name] || (obj[name] = factory());
  1986. }
  1987. var angular = ensure(window, 'angular', Object);
  1988. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1989. angular.$$minErr = angular.$$minErr || minErr;
  1990. return ensure(angular, 'module', function() {
  1991. /** @type {Object.<string, angular.Module>} */
  1992. var modules = {};
  1993. /**
  1994. * @ngdoc function
  1995. * @name angular.module
  1996. * @module ng
  1997. * @description
  1998. *
  1999. * The `angular.module` is a global place for creating, registering and retrieving AngularJS
  2000. * modules.
  2001. * All modules (AngularJS core or 3rd party) that should be available to an application must be
  2002. * registered using this mechanism.
  2003. *
  2004. * Passing one argument retrieves an existing {@link angular.Module},
  2005. * whereas passing more than one argument creates a new {@link angular.Module}
  2006. *
  2007. *
  2008. * # Module
  2009. *
  2010. * A module is a collection of services, directives, controllers, filters, and configuration information.
  2011. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  2012. *
  2013. * ```js
  2014. * // Create a new module
  2015. * var myModule = angular.module('myModule', []);
  2016. *
  2017. * // register a new service
  2018. * myModule.value('appName', 'MyCoolApp');
  2019. *
  2020. * // configure existing services inside initialization blocks.
  2021. * myModule.config(['$locationProvider', function($locationProvider) {
  2022. * // Configure existing providers
  2023. * $locationProvider.hashPrefix('!');
  2024. * }]);
  2025. * ```
  2026. *
  2027. * Then you can create an injector and load your modules like this:
  2028. *
  2029. * ```js
  2030. * var injector = angular.injector(['ng', 'myModule'])
  2031. * ```
  2032. *
  2033. * However it's more likely that you'll just use
  2034. * {@link ng.directive:ngApp ngApp} or
  2035. * {@link angular.bootstrap} to simplify this process for you.
  2036. *
  2037. * @param {!string} name The name of the module to create or retrieve.
  2038. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2039. * unspecified then the module is being retrieved for further configuration.
  2040. * @param {Function=} configFn Optional configuration function for the module. Same as
  2041. * {@link angular.Module#config Module#config()}.
  2042. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2043. */
  2044. return function module(name, requires, configFn) {
  2045. var info = {};
  2046. var assertNotHasOwnProperty = function(name, context) {
  2047. if (name === 'hasOwnProperty') {
  2048. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2049. }
  2050. };
  2051. assertNotHasOwnProperty(name, 'module');
  2052. if (requires && modules.hasOwnProperty(name)) {
  2053. modules[name] = null;
  2054. }
  2055. return ensure(modules, name, function() {
  2056. if (!requires) {
  2057. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2058. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2059. 'specify the dependencies as the second argument.', name);
  2060. }
  2061. /** @type {!Array.<Array.<*>>} */
  2062. var invokeQueue = [];
  2063. /** @type {!Array.<Function>} */
  2064. var configBlocks = [];
  2065. /** @type {!Array.<Function>} */
  2066. var runBlocks = [];
  2067. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2068. /** @type {angular.Module} */
  2069. var moduleInstance = {
  2070. // Private state
  2071. _invokeQueue: invokeQueue,
  2072. _configBlocks: configBlocks,
  2073. _runBlocks: runBlocks,
  2074. /**
  2075. * @ngdoc method
  2076. * @name angular.Module#info
  2077. * @module ng
  2078. *
  2079. * @param {Object=} info Information about the module
  2080. * @returns {Object|Module} The current info object for this module if called as a getter,
  2081. * or `this` if called as a setter.
  2082. *
  2083. * @description
  2084. * Read and write custom information about this module.
  2085. * For example you could put the version of the module in here.
  2086. *
  2087. * ```js
  2088. * angular.module('myModule', []).info({ version: '1.0.0' });
  2089. * ```
  2090. *
  2091. * The version could then be read back out by accessing the module elsewhere:
  2092. *
  2093. * ```
  2094. * var version = angular.module('myModule').info().version;
  2095. * ```
  2096. *
  2097. * You can also retrieve this information during runtime via the
  2098. * {@link $injector#modules `$injector.modules`} property:
  2099. *
  2100. * ```js
  2101. * var version = $injector.modules['myModule'].info().version;
  2102. * ```
  2103. */
  2104. info: function(value) {
  2105. if (isDefined(value)) {
  2106. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2107. info = value;
  2108. return this;
  2109. }
  2110. return info;
  2111. },
  2112. /**
  2113. * @ngdoc property
  2114. * @name angular.Module#requires
  2115. * @module ng
  2116. *
  2117. * @description
  2118. * Holds the list of modules which the injector will load before the current module is
  2119. * loaded.
  2120. */
  2121. requires: requires,
  2122. /**
  2123. * @ngdoc property
  2124. * @name angular.Module#name
  2125. * @module ng
  2126. *
  2127. * @description
  2128. * Name of the module.
  2129. */
  2130. name: name,
  2131. /**
  2132. * @ngdoc method
  2133. * @name angular.Module#provider
  2134. * @module ng
  2135. * @param {string} name service name
  2136. * @param {Function} providerType Construction function for creating new instance of the
  2137. * service.
  2138. * @description
  2139. * See {@link auto.$provide#provider $provide.provider()}.
  2140. */
  2141. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2142. /**
  2143. * @ngdoc method
  2144. * @name angular.Module#factory
  2145. * @module ng
  2146. * @param {string} name service name
  2147. * @param {Function} providerFunction Function for creating new instance of the service.
  2148. * @description
  2149. * See {@link auto.$provide#factory $provide.factory()}.
  2150. */
  2151. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2152. /**
  2153. * @ngdoc method
  2154. * @name angular.Module#service
  2155. * @module ng
  2156. * @param {string} name service name
  2157. * @param {Function} constructor A constructor function that will be instantiated.
  2158. * @description
  2159. * See {@link auto.$provide#service $provide.service()}.
  2160. */
  2161. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2162. /**
  2163. * @ngdoc method
  2164. * @name angular.Module#value
  2165. * @module ng
  2166. * @param {string} name service name
  2167. * @param {*} object Service instance object.
  2168. * @description
  2169. * See {@link auto.$provide#value $provide.value()}.
  2170. */
  2171. value: invokeLater('$provide', 'value'),
  2172. /**
  2173. * @ngdoc method
  2174. * @name angular.Module#constant
  2175. * @module ng
  2176. * @param {string} name constant name
  2177. * @param {*} object Constant value.
  2178. * @description
  2179. * Because the constants are fixed, they get applied before other provide methods.
  2180. * See {@link auto.$provide#constant $provide.constant()}.
  2181. */
  2182. constant: invokeLater('$provide', 'constant', 'unshift'),
  2183. /**
  2184. * @ngdoc method
  2185. * @name angular.Module#decorator
  2186. * @module ng
  2187. * @param {string} name The name of the service to decorate.
  2188. * @param {Function} decorFn This function will be invoked when the service needs to be
  2189. * instantiated and should return the decorated service instance.
  2190. * @description
  2191. * See {@link auto.$provide#decorator $provide.decorator()}.
  2192. */
  2193. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2194. /**
  2195. * @ngdoc method
  2196. * @name angular.Module#animation
  2197. * @module ng
  2198. * @param {string} name animation name
  2199. * @param {Function} animationFactory Factory function for creating new instance of an
  2200. * animation.
  2201. * @description
  2202. *
  2203. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2204. *
  2205. *
  2206. * Defines an animation hook that can be later used with
  2207. * {@link $animate $animate} service and directives that use this service.
  2208. *
  2209. * ```js
  2210. * module.animation('.animation-name', function($inject1, $inject2) {
  2211. * return {
  2212. * eventName : function(element, done) {
  2213. * //code to run the animation
  2214. * //once complete, then run done()
  2215. * return function cancellationFunction(element) {
  2216. * //code to cancel the animation
  2217. * }
  2218. * }
  2219. * }
  2220. * })
  2221. * ```
  2222. *
  2223. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2224. * {@link ngAnimate ngAnimate module} for more information.
  2225. */
  2226. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2227. /**
  2228. * @ngdoc method
  2229. * @name angular.Module#filter
  2230. * @module ng
  2231. * @param {string} name Filter name - this must be a valid AngularJS expression identifier
  2232. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2233. * @description
  2234. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2235. *
  2236. * <div class="alert alert-warning">
  2237. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2238. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2239. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2240. * (`myapp_subsection_filterx`).
  2241. * </div>
  2242. */
  2243. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2244. /**
  2245. * @ngdoc method
  2246. * @name angular.Module#controller
  2247. * @module ng
  2248. * @param {string|Object} name Controller name, or an object map of controllers where the
  2249. * keys are the names and the values are the constructors.
  2250. * @param {Function} constructor Controller constructor function.
  2251. * @description
  2252. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2253. */
  2254. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2255. /**
  2256. * @ngdoc method
  2257. * @name angular.Module#directive
  2258. * @module ng
  2259. * @param {string|Object} name Directive name, or an object map of directives where the
  2260. * keys are the names and the values are the factories.
  2261. * @param {Function} directiveFactory Factory function for creating new instance of
  2262. * directives.
  2263. * @description
  2264. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2265. */
  2266. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2267. /**
  2268. * @ngdoc method
  2269. * @name angular.Module#component
  2270. * @module ng
  2271. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2272. * @param {Object} options Component definition object (a simplified
  2273. * {@link ng.$compile#directive-definition-object directive definition object})
  2274. *
  2275. * @description
  2276. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2277. */
  2278. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2279. /**
  2280. * @ngdoc method
  2281. * @name angular.Module#config
  2282. * @module ng
  2283. * @param {Function} configFn Execute this function on module load. Useful for service
  2284. * configuration.
  2285. * @description
  2286. * Use this method to configure services by injecting their
  2287. * {@link angular.Module#provider `providers`}, e.g. for adding routes to the
  2288. * {@link ngRoute.$routeProvider $routeProvider}.
  2289. *
  2290. * Note that you can only inject {@link angular.Module#provider `providers`} and
  2291. * {@link angular.Module#constant `constants`} into this function.
  2292. *
  2293. * For more about how to configure services, see
  2294. * {@link providers#provider-recipe Provider Recipe}.
  2295. */
  2296. config: config,
  2297. /**
  2298. * @ngdoc method
  2299. * @name angular.Module#run
  2300. * @module ng
  2301. * @param {Function} initializationFn Execute this function after injector creation.
  2302. * Useful for application initialization.
  2303. * @description
  2304. * Use this method to register work which should be performed when the injector is done
  2305. * loading all modules.
  2306. */
  2307. run: function(block) {
  2308. runBlocks.push(block);
  2309. return this;
  2310. }
  2311. };
  2312. if (configFn) {
  2313. config(configFn);
  2314. }
  2315. return moduleInstance;
  2316. /**
  2317. * @param {string} provider
  2318. * @param {string} method
  2319. * @param {String=} insertMethod
  2320. * @returns {angular.Module}
  2321. */
  2322. function invokeLater(provider, method, insertMethod, queue) {
  2323. if (!queue) queue = invokeQueue;
  2324. return function() {
  2325. queue[insertMethod || 'push']([provider, method, arguments]);
  2326. return moduleInstance;
  2327. };
  2328. }
  2329. /**
  2330. * @param {string} provider
  2331. * @param {string} method
  2332. * @returns {angular.Module}
  2333. */
  2334. function invokeLaterAndSetModuleName(provider, method, queue) {
  2335. if (!queue) queue = invokeQueue;
  2336. return function(recipeName, factoryFunction) {
  2337. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2338. queue.push([provider, method, arguments]);
  2339. return moduleInstance;
  2340. };
  2341. }
  2342. });
  2343. };
  2344. });
  2345. }
  2346. /* global shallowCopy: true */
  2347. /**
  2348. * Creates a shallow copy of an object, an array or a primitive.
  2349. *
  2350. * Assumes that there are no proto properties for objects.
  2351. */
  2352. function shallowCopy(src, dst) {
  2353. if (isArray(src)) {
  2354. dst = dst || [];
  2355. for (var i = 0, ii = src.length; i < ii; i++) {
  2356. dst[i] = src[i];
  2357. }
  2358. } else if (isObject(src)) {
  2359. dst = dst || {};
  2360. for (var key in src) {
  2361. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2362. dst[key] = src[key];
  2363. }
  2364. }
  2365. }
  2366. return dst || src;
  2367. }
  2368. /* exported toDebugString */
  2369. function serializeObject(obj, maxDepth) {
  2370. var seen = [];
  2371. // There is no direct way to stringify object until reaching a specific depth
  2372. // and a very deep object can cause a performance issue, so we copy the object
  2373. // based on this specific depth and then stringify it.
  2374. if (isValidObjectMaxDepth(maxDepth)) {
  2375. // This file is also included in `angular-loader`, so `copy()` might not always be available in
  2376. // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
  2377. obj = angular.copy(obj, null, maxDepth);
  2378. }
  2379. return JSON.stringify(obj, function(key, val) {
  2380. val = toJsonReplacer(key, val);
  2381. if (isObject(val)) {
  2382. if (seen.indexOf(val) >= 0) return '...';
  2383. seen.push(val);
  2384. }
  2385. return val;
  2386. });
  2387. }
  2388. function toDebugString(obj, maxDepth) {
  2389. if (typeof obj === 'function') {
  2390. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2391. } else if (isUndefined(obj)) {
  2392. return 'undefined';
  2393. } else if (typeof obj !== 'string') {
  2394. return serializeObject(obj, maxDepth);
  2395. }
  2396. return obj;
  2397. }
  2398. /* global angularModule: true,
  2399. version: true,
  2400. $CompileProvider,
  2401. htmlAnchorDirective,
  2402. inputDirective,
  2403. inputDirective,
  2404. formDirective,
  2405. scriptDirective,
  2406. selectDirective,
  2407. optionDirective,
  2408. ngBindDirective,
  2409. ngBindHtmlDirective,
  2410. ngBindTemplateDirective,
  2411. ngClassDirective,
  2412. ngClassEvenDirective,
  2413. ngClassOddDirective,
  2414. ngCloakDirective,
  2415. ngControllerDirective,
  2416. ngFormDirective,
  2417. ngHideDirective,
  2418. ngIfDirective,
  2419. ngIncludeDirective,
  2420. ngIncludeFillContentDirective,
  2421. ngInitDirective,
  2422. ngNonBindableDirective,
  2423. ngPluralizeDirective,
  2424. ngRepeatDirective,
  2425. ngShowDirective,
  2426. ngStyleDirective,
  2427. ngSwitchDirective,
  2428. ngSwitchWhenDirective,
  2429. ngSwitchDefaultDirective,
  2430. ngOptionsDirective,
  2431. ngTranscludeDirective,
  2432. ngModelDirective,
  2433. ngListDirective,
  2434. ngChangeDirective,
  2435. patternDirective,
  2436. patternDirective,
  2437. requiredDirective,
  2438. requiredDirective,
  2439. minlengthDirective,
  2440. minlengthDirective,
  2441. maxlengthDirective,
  2442. maxlengthDirective,
  2443. ngValueDirective,
  2444. ngModelOptionsDirective,
  2445. ngAttributeAliasDirectives,
  2446. ngEventDirectives,
  2447. $AnchorScrollProvider,
  2448. $AnimateProvider,
  2449. $CoreAnimateCssProvider,
  2450. $$CoreAnimateJsProvider,
  2451. $$CoreAnimateQueueProvider,
  2452. $$AnimateRunnerFactoryProvider,
  2453. $$AnimateAsyncRunFactoryProvider,
  2454. $BrowserProvider,
  2455. $CacheFactoryProvider,
  2456. $ControllerProvider,
  2457. $DateProvider,
  2458. $DocumentProvider,
  2459. $$IsDocumentHiddenProvider,
  2460. $ExceptionHandlerProvider,
  2461. $FilterProvider,
  2462. $$ForceReflowProvider,
  2463. $InterpolateProvider,
  2464. $IntervalProvider,
  2465. $HttpProvider,
  2466. $HttpParamSerializerProvider,
  2467. $HttpParamSerializerJQLikeProvider,
  2468. $HttpBackendProvider,
  2469. $xhrFactoryProvider,
  2470. $jsonpCallbacksProvider,
  2471. $LocationProvider,
  2472. $LogProvider,
  2473. $$MapProvider,
  2474. $ParseProvider,
  2475. $RootScopeProvider,
  2476. $QProvider,
  2477. $$QProvider,
  2478. $$SanitizeUriProvider,
  2479. $SceProvider,
  2480. $SceDelegateProvider,
  2481. $SnifferProvider,
  2482. $TemplateCacheProvider,
  2483. $TemplateRequestProvider,
  2484. $$TestabilityProvider,
  2485. $TimeoutProvider,
  2486. $$RAFProvider,
  2487. $WindowProvider,
  2488. $$jqLiteProvider,
  2489. $$CookieReaderProvider
  2490. */
  2491. /**
  2492. * @ngdoc object
  2493. * @name angular.version
  2494. * @module ng
  2495. * @description
  2496. * An object that contains information about the current AngularJS version.
  2497. *
  2498. * This object has the following properties:
  2499. *
  2500. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2501. * - `major` – `{number}` – Major version number, such as "0".
  2502. * - `minor` – `{number}` – Minor version number, such as "9".
  2503. * - `dot` – `{number}` – Dot version number, such as "18".
  2504. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2505. */
  2506. var version = {
  2507. // These placeholder strings will be replaced by grunt's `build` task.
  2508. // They need to be double- or single-quoted.
  2509. full: '1.6.9',
  2510. major: 1,
  2511. minor: 6,
  2512. dot: 9,
  2513. codeName: 'fiery-basilisk'
  2514. };
  2515. function publishExternalAPI(angular) {
  2516. extend(angular, {
  2517. 'errorHandlingConfig': errorHandlingConfig,
  2518. 'bootstrap': bootstrap,
  2519. 'copy': copy,
  2520. 'extend': extend,
  2521. 'merge': merge,
  2522. 'equals': equals,
  2523. 'element': jqLite,
  2524. 'forEach': forEach,
  2525. 'injector': createInjector,
  2526. 'noop': noop,
  2527. 'bind': bind,
  2528. 'toJson': toJson,
  2529. 'fromJson': fromJson,
  2530. 'identity': identity,
  2531. 'isUndefined': isUndefined,
  2532. 'isDefined': isDefined,
  2533. 'isString': isString,
  2534. 'isFunction': isFunction,
  2535. 'isObject': isObject,
  2536. 'isNumber': isNumber,
  2537. 'isElement': isElement,
  2538. 'isArray': isArray,
  2539. 'version': version,
  2540. 'isDate': isDate,
  2541. 'lowercase': lowercase,
  2542. 'uppercase': uppercase,
  2543. 'callbacks': {$$counter: 0},
  2544. 'getTestability': getTestability,
  2545. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2546. '$$minErr': minErr,
  2547. '$$csp': csp,
  2548. '$$encodeUriSegment': encodeUriSegment,
  2549. '$$encodeUriQuery': encodeUriQuery,
  2550. '$$stringify': stringify
  2551. });
  2552. angularModule = setupModuleLoader(window);
  2553. angularModule('ng', ['ngLocale'], ['$provide',
  2554. function ngModule($provide) {
  2555. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2556. $provide.provider({
  2557. $$sanitizeUri: $$SanitizeUriProvider
  2558. });
  2559. $provide.provider('$compile', $CompileProvider).
  2560. directive({
  2561. a: htmlAnchorDirective,
  2562. input: inputDirective,
  2563. textarea: inputDirective,
  2564. form: formDirective,
  2565. script: scriptDirective,
  2566. select: selectDirective,
  2567. option: optionDirective,
  2568. ngBind: ngBindDirective,
  2569. ngBindHtml: ngBindHtmlDirective,
  2570. ngBindTemplate: ngBindTemplateDirective,
  2571. ngClass: ngClassDirective,
  2572. ngClassEven: ngClassEvenDirective,
  2573. ngClassOdd: ngClassOddDirective,
  2574. ngCloak: ngCloakDirective,
  2575. ngController: ngControllerDirective,
  2576. ngForm: ngFormDirective,
  2577. ngHide: ngHideDirective,
  2578. ngIf: ngIfDirective,
  2579. ngInclude: ngIncludeDirective,
  2580. ngInit: ngInitDirective,
  2581. ngNonBindable: ngNonBindableDirective,
  2582. ngPluralize: ngPluralizeDirective,
  2583. ngRepeat: ngRepeatDirective,
  2584. ngShow: ngShowDirective,
  2585. ngStyle: ngStyleDirective,
  2586. ngSwitch: ngSwitchDirective,
  2587. ngSwitchWhen: ngSwitchWhenDirective,
  2588. ngSwitchDefault: ngSwitchDefaultDirective,
  2589. ngOptions: ngOptionsDirective,
  2590. ngTransclude: ngTranscludeDirective,
  2591. ngModel: ngModelDirective,
  2592. ngList: ngListDirective,
  2593. ngChange: ngChangeDirective,
  2594. pattern: patternDirective,
  2595. ngPattern: patternDirective,
  2596. required: requiredDirective,
  2597. ngRequired: requiredDirective,
  2598. minlength: minlengthDirective,
  2599. ngMinlength: minlengthDirective,
  2600. maxlength: maxlengthDirective,
  2601. ngMaxlength: maxlengthDirective,
  2602. ngValue: ngValueDirective,
  2603. ngModelOptions: ngModelOptionsDirective
  2604. }).
  2605. directive({
  2606. ngInclude: ngIncludeFillContentDirective
  2607. }).
  2608. directive(ngAttributeAliasDirectives).
  2609. directive(ngEventDirectives);
  2610. $provide.provider({
  2611. $anchorScroll: $AnchorScrollProvider,
  2612. $animate: $AnimateProvider,
  2613. $animateCss: $CoreAnimateCssProvider,
  2614. $$animateJs: $$CoreAnimateJsProvider,
  2615. $$animateQueue: $$CoreAnimateQueueProvider,
  2616. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2617. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2618. $browser: $BrowserProvider,
  2619. $cacheFactory: $CacheFactoryProvider,
  2620. $controller: $ControllerProvider,
  2621. $document: $DocumentProvider,
  2622. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2623. $exceptionHandler: $ExceptionHandlerProvider,
  2624. $filter: $FilterProvider,
  2625. $$forceReflow: $$ForceReflowProvider,
  2626. $interpolate: $InterpolateProvider,
  2627. $interval: $IntervalProvider,
  2628. $http: $HttpProvider,
  2629. $httpParamSerializer: $HttpParamSerializerProvider,
  2630. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2631. $httpBackend: $HttpBackendProvider,
  2632. $xhrFactory: $xhrFactoryProvider,
  2633. $jsonpCallbacks: $jsonpCallbacksProvider,
  2634. $location: $LocationProvider,
  2635. $log: $LogProvider,
  2636. $parse: $ParseProvider,
  2637. $rootScope: $RootScopeProvider,
  2638. $q: $QProvider,
  2639. $$q: $$QProvider,
  2640. $sce: $SceProvider,
  2641. $sceDelegate: $SceDelegateProvider,
  2642. $sniffer: $SnifferProvider,
  2643. $templateCache: $TemplateCacheProvider,
  2644. $templateRequest: $TemplateRequestProvider,
  2645. $$testability: $$TestabilityProvider,
  2646. $timeout: $TimeoutProvider,
  2647. $window: $WindowProvider,
  2648. $$rAF: $$RAFProvider,
  2649. $$jqLite: $$jqLiteProvider,
  2650. $$Map: $$MapProvider,
  2651. $$cookieReader: $$CookieReaderProvider
  2652. });
  2653. }
  2654. ])
  2655. .info({ angularVersion: '1.6.9' });
  2656. }
  2657. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2658. * Any commits to this file should be reviewed with security in mind. *
  2659. * Changes to this file can potentially create security vulnerabilities. *
  2660. * An approval from 2 Core members with history of modifying *
  2661. * this file is required. *
  2662. * *
  2663. * Does the change somehow allow for arbitrary javascript to be executed? *
  2664. * Or allows for someone to change the prototype of built-in objects? *
  2665. * Or gives undesired access to variables likes document or window? *
  2666. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2667. /* global
  2668. JQLitePrototype: true,
  2669. BOOLEAN_ATTR: true,
  2670. ALIASED_ATTR: true
  2671. */
  2672. //////////////////////////////////
  2673. //JQLite
  2674. //////////////////////////////////
  2675. /**
  2676. * @ngdoc function
  2677. * @name angular.element
  2678. * @module ng
  2679. * @kind function
  2680. *
  2681. * @description
  2682. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2683. *
  2684. * If jQuery is available, `angular.element` is an alias for the
  2685. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2686. * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2687. *
  2688. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2689. * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2690. * commonly needed functionality with the goal of having a very small footprint.
  2691. *
  2692. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2693. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2694. * specific version of jQuery if multiple versions exist on the page.
  2695. *
  2696. * <div class="alert alert-info">**Note:** All element references in AngularJS are always wrapped with jQuery or
  2697. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2698. *
  2699. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2700. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2701. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2702. *
  2703. * ## AngularJS's jqLite
  2704. * jqLite provides only the following jQuery methods:
  2705. *
  2706. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2707. * - [`after()`](http://api.jquery.com/after/)
  2708. * - [`append()`](http://api.jquery.com/append/)
  2709. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2710. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2711. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2712. * - [`clone()`](http://api.jquery.com/clone/)
  2713. * - [`contents()`](http://api.jquery.com/contents/)
  2714. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2715. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2716. * - [`data()`](http://api.jquery.com/data/)
  2717. * - [`detach()`](http://api.jquery.com/detach/)
  2718. * - [`empty()`](http://api.jquery.com/empty/)
  2719. * - [`eq()`](http://api.jquery.com/eq/)
  2720. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2721. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2722. * - [`html()`](http://api.jquery.com/html/)
  2723. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2724. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2725. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2726. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2727. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2728. * - [`prepend()`](http://api.jquery.com/prepend/)
  2729. * - [`prop()`](http://api.jquery.com/prop/)
  2730. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2731. * - [`remove()`](http://api.jquery.com/remove/)
  2732. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2733. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2734. * - [`removeData()`](http://api.jquery.com/removeData/)
  2735. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2736. * - [`text()`](http://api.jquery.com/text/)
  2737. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2738. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2739. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2740. * - [`val()`](http://api.jquery.com/val/)
  2741. * - [`wrap()`](http://api.jquery.com/wrap/)
  2742. *
  2743. * ## jQuery/jqLite Extras
  2744. * AngularJS also provides the following additional methods and events to both jQuery and jqLite:
  2745. *
  2746. * ### Events
  2747. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2748. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2749. * element before it is removed.
  2750. *
  2751. * ### Methods
  2752. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2753. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2754. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2755. * `'ngModel'`).
  2756. * - `injector()` - retrieves the injector of the current element or its parent.
  2757. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2758. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2759. * be enabled.
  2760. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2761. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2762. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2763. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2764. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2765. * parent element is reached.
  2766. *
  2767. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2768. * https://github.com/angular/angular.js/issues/14251 for more information.
  2769. *
  2770. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2771. * @returns {Object} jQuery object.
  2772. */
  2773. JQLite.expando = 'ng339';
  2774. var jqCache = JQLite.cache = {},
  2775. jqId = 1;
  2776. /*
  2777. * !!! This is an undocumented "private" function !!!
  2778. */
  2779. JQLite._data = function(node) {
  2780. //jQuery always returns an object on cache miss
  2781. return this.cache[node[this.expando]] || {};
  2782. };
  2783. function jqNextId() { return ++jqId; }
  2784. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2785. var MS_HACK_REGEXP = /^-ms-/;
  2786. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2787. var jqLiteMinErr = minErr('jqLite');
  2788. /**
  2789. * Converts kebab-case to camelCase.
  2790. * There is also a special case for the ms prefix starting with a lowercase letter.
  2791. * @param name Name to normalize
  2792. */
  2793. function cssKebabToCamel(name) {
  2794. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2795. }
  2796. function fnCamelCaseReplace(all, letter) {
  2797. return letter.toUpperCase();
  2798. }
  2799. /**
  2800. * Converts kebab-case to camelCase.
  2801. * @param name Name to normalize
  2802. */
  2803. function kebabToCamel(name) {
  2804. return name
  2805. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2806. }
  2807. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2808. var HTML_REGEXP = /<|&#?\w+;/;
  2809. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2810. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2811. var wrapMap = {
  2812. 'option': [1, '<select multiple="multiple">', '</select>'],
  2813. 'thead': [1, '<table>', '</table>'],
  2814. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2815. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2816. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2817. '_default': [0, '', '']
  2818. };
  2819. wrapMap.optgroup = wrapMap.option;
  2820. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2821. wrapMap.th = wrapMap.td;
  2822. function jqLiteIsTextNode(html) {
  2823. return !HTML_REGEXP.test(html);
  2824. }
  2825. function jqLiteAcceptsData(node) {
  2826. // The window object can accept data but has no nodeType
  2827. // Otherwise we are only interested in elements (1) and documents (9)
  2828. var nodeType = node.nodeType;
  2829. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2830. }
  2831. function jqLiteHasData(node) {
  2832. for (var key in jqCache[node.ng339]) {
  2833. return true;
  2834. }
  2835. return false;
  2836. }
  2837. function jqLiteBuildFragment(html, context) {
  2838. var tmp, tag, wrap,
  2839. fragment = context.createDocumentFragment(),
  2840. nodes = [], i;
  2841. if (jqLiteIsTextNode(html)) {
  2842. // Convert non-html into a text node
  2843. nodes.push(context.createTextNode(html));
  2844. } else {
  2845. // Convert html into DOM nodes
  2846. tmp = fragment.appendChild(context.createElement('div'));
  2847. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2848. wrap = wrapMap[tag] || wrapMap._default;
  2849. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2850. // Descend through wrappers to the right content
  2851. i = wrap[0];
  2852. while (i--) {
  2853. tmp = tmp.lastChild;
  2854. }
  2855. nodes = concat(nodes, tmp.childNodes);
  2856. tmp = fragment.firstChild;
  2857. tmp.textContent = '';
  2858. }
  2859. // Remove wrapper from fragment
  2860. fragment.textContent = '';
  2861. fragment.innerHTML = ''; // Clear inner HTML
  2862. forEach(nodes, function(node) {
  2863. fragment.appendChild(node);
  2864. });
  2865. return fragment;
  2866. }
  2867. function jqLiteParseHTML(html, context) {
  2868. context = context || window.document;
  2869. var parsed;
  2870. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2871. return [context.createElement(parsed[1])];
  2872. }
  2873. if ((parsed = jqLiteBuildFragment(html, context))) {
  2874. return parsed.childNodes;
  2875. }
  2876. return [];
  2877. }
  2878. function jqLiteWrapNode(node, wrapper) {
  2879. var parent = node.parentNode;
  2880. if (parent) {
  2881. parent.replaceChild(wrapper, node);
  2882. }
  2883. wrapper.appendChild(node);
  2884. }
  2885. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2886. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2887. // eslint-disable-next-line no-bitwise
  2888. return !!(this.compareDocumentPosition(arg) & 16);
  2889. };
  2890. /////////////////////////////////////////////
  2891. function JQLite(element) {
  2892. if (element instanceof JQLite) {
  2893. return element;
  2894. }
  2895. var argIsString;
  2896. if (isString(element)) {
  2897. element = trim(element);
  2898. argIsString = true;
  2899. }
  2900. if (!(this instanceof JQLite)) {
  2901. if (argIsString && element.charAt(0) !== '<') {
  2902. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2903. }
  2904. return new JQLite(element);
  2905. }
  2906. if (argIsString) {
  2907. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2908. } else if (isFunction(element)) {
  2909. jqLiteReady(element);
  2910. } else {
  2911. jqLiteAddNodes(this, element);
  2912. }
  2913. }
  2914. function jqLiteClone(element) {
  2915. return element.cloneNode(true);
  2916. }
  2917. function jqLiteDealoc(element, onlyDescendants) {
  2918. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2919. if (element.querySelectorAll) {
  2920. jqLite.cleanData(element.querySelectorAll('*'));
  2921. }
  2922. }
  2923. function jqLiteOff(element, type, fn, unsupported) {
  2924. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2925. var expandoStore = jqLiteExpandoStore(element);
  2926. var events = expandoStore && expandoStore.events;
  2927. var handle = expandoStore && expandoStore.handle;
  2928. if (!handle) return; //no listeners registered
  2929. if (!type) {
  2930. for (type in events) {
  2931. if (type !== '$destroy') {
  2932. element.removeEventListener(type, handle);
  2933. }
  2934. delete events[type];
  2935. }
  2936. } else {
  2937. var removeHandler = function(type) {
  2938. var listenerFns = events[type];
  2939. if (isDefined(fn)) {
  2940. arrayRemove(listenerFns || [], fn);
  2941. }
  2942. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2943. element.removeEventListener(type, handle);
  2944. delete events[type];
  2945. }
  2946. };
  2947. forEach(type.split(' '), function(type) {
  2948. removeHandler(type);
  2949. if (MOUSE_EVENT_MAP[type]) {
  2950. removeHandler(MOUSE_EVENT_MAP[type]);
  2951. }
  2952. });
  2953. }
  2954. }
  2955. function jqLiteRemoveData(element, name) {
  2956. var expandoId = element.ng339;
  2957. var expandoStore = expandoId && jqCache[expandoId];
  2958. if (expandoStore) {
  2959. if (name) {
  2960. delete expandoStore.data[name];
  2961. return;
  2962. }
  2963. if (expandoStore.handle) {
  2964. if (expandoStore.events.$destroy) {
  2965. expandoStore.handle({}, '$destroy');
  2966. }
  2967. jqLiteOff(element);
  2968. }
  2969. delete jqCache[expandoId];
  2970. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2971. }
  2972. }
  2973. function jqLiteExpandoStore(element, createIfNecessary) {
  2974. var expandoId = element.ng339,
  2975. expandoStore = expandoId && jqCache[expandoId];
  2976. if (createIfNecessary && !expandoStore) {
  2977. element.ng339 = expandoId = jqNextId();
  2978. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2979. }
  2980. return expandoStore;
  2981. }
  2982. function jqLiteData(element, key, value) {
  2983. if (jqLiteAcceptsData(element)) {
  2984. var prop;
  2985. var isSimpleSetter = isDefined(value);
  2986. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2987. var massGetter = !key;
  2988. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2989. var data = expandoStore && expandoStore.data;
  2990. if (isSimpleSetter) { // data('key', value)
  2991. data[kebabToCamel(key)] = value;
  2992. } else {
  2993. if (massGetter) { // data()
  2994. return data;
  2995. } else {
  2996. if (isSimpleGetter) { // data('key')
  2997. // don't force creation of expandoStore if it doesn't exist yet
  2998. return data && data[kebabToCamel(key)];
  2999. } else { // mass-setter: data({key1: val1, key2: val2})
  3000. for (prop in key) {
  3001. data[kebabToCamel(prop)] = key[prop];
  3002. }
  3003. }
  3004. }
  3005. }
  3006. }
  3007. }
  3008. function jqLiteHasClass(element, selector) {
  3009. if (!element.getAttribute) return false;
  3010. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  3011. indexOf(' ' + selector + ' ') > -1);
  3012. }
  3013. function jqLiteRemoveClass(element, cssClasses) {
  3014. if (cssClasses && element.setAttribute) {
  3015. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3016. .replace(/[\n\t]/g, ' ');
  3017. var newClasses = existingClasses;
  3018. forEach(cssClasses.split(' '), function(cssClass) {
  3019. cssClass = trim(cssClass);
  3020. newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
  3021. });
  3022. if (newClasses !== existingClasses) {
  3023. element.setAttribute('class', trim(newClasses));
  3024. }
  3025. }
  3026. }
  3027. function jqLiteAddClass(element, cssClasses) {
  3028. if (cssClasses && element.setAttribute) {
  3029. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3030. .replace(/[\n\t]/g, ' ');
  3031. var newClasses = existingClasses;
  3032. forEach(cssClasses.split(' '), function(cssClass) {
  3033. cssClass = trim(cssClass);
  3034. if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
  3035. newClasses += cssClass + ' ';
  3036. }
  3037. });
  3038. if (newClasses !== existingClasses) {
  3039. element.setAttribute('class', trim(newClasses));
  3040. }
  3041. }
  3042. }
  3043. function jqLiteAddNodes(root, elements) {
  3044. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  3045. if (elements) {
  3046. // if a Node (the most common case)
  3047. if (elements.nodeType) {
  3048. root[root.length++] = elements;
  3049. } else {
  3050. var length = elements.length;
  3051. // if an Array or NodeList and not a Window
  3052. if (typeof length === 'number' && elements.window !== elements) {
  3053. if (length) {
  3054. for (var i = 0; i < length; i++) {
  3055. root[root.length++] = elements[i];
  3056. }
  3057. }
  3058. } else {
  3059. root[root.length++] = elements;
  3060. }
  3061. }
  3062. }
  3063. }
  3064. function jqLiteController(element, name) {
  3065. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3066. }
  3067. function jqLiteInheritedData(element, name, value) {
  3068. // if element is the document object work with the html element instead
  3069. // this makes $(document).scope() possible
  3070. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3071. element = element.documentElement;
  3072. }
  3073. var names = isArray(name) ? name : [name];
  3074. while (element) {
  3075. for (var i = 0, ii = names.length; i < ii; i++) {
  3076. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3077. }
  3078. // If dealing with a document fragment node with a host element, and no parent, use the host
  3079. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3080. // to lookup parent controllers.
  3081. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3082. }
  3083. }
  3084. function jqLiteEmpty(element) {
  3085. jqLiteDealoc(element, true);
  3086. while (element.firstChild) {
  3087. element.removeChild(element.firstChild);
  3088. }
  3089. }
  3090. function jqLiteRemove(element, keepData) {
  3091. if (!keepData) jqLiteDealoc(element);
  3092. var parent = element.parentNode;
  3093. if (parent) parent.removeChild(element);
  3094. }
  3095. function jqLiteDocumentLoaded(action, win) {
  3096. win = win || window;
  3097. if (win.document.readyState === 'complete') {
  3098. // Force the action to be run async for consistent behavior
  3099. // from the action's point of view
  3100. // i.e. it will definitely not be in a $apply
  3101. win.setTimeout(action);
  3102. } else {
  3103. // No need to unbind this handler as load is only ever called once
  3104. jqLite(win).on('load', action);
  3105. }
  3106. }
  3107. function jqLiteReady(fn) {
  3108. function trigger() {
  3109. window.document.removeEventListener('DOMContentLoaded', trigger);
  3110. window.removeEventListener('load', trigger);
  3111. fn();
  3112. }
  3113. // check if document is already loaded
  3114. if (window.document.readyState === 'complete') {
  3115. window.setTimeout(fn);
  3116. } else {
  3117. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3118. // Works for modern browsers and IE9
  3119. window.document.addEventListener('DOMContentLoaded', trigger);
  3120. // Fallback to window.onload for others
  3121. window.addEventListener('load', trigger);
  3122. }
  3123. }
  3124. //////////////////////////////////////////
  3125. // Functions which are declared directly.
  3126. //////////////////////////////////////////
  3127. var JQLitePrototype = JQLite.prototype = {
  3128. ready: jqLiteReady,
  3129. toString: function() {
  3130. var value = [];
  3131. forEach(this, function(e) { value.push('' + e);});
  3132. return '[' + value.join(', ') + ']';
  3133. },
  3134. eq: function(index) {
  3135. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3136. },
  3137. length: 0,
  3138. push: push,
  3139. sort: [].sort,
  3140. splice: [].splice
  3141. };
  3142. //////////////////////////////////////////
  3143. // Functions iterating getter/setters.
  3144. // these functions return self on setter and
  3145. // value on get.
  3146. //////////////////////////////////////////
  3147. var BOOLEAN_ATTR = {};
  3148. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3149. BOOLEAN_ATTR[lowercase(value)] = value;
  3150. });
  3151. var BOOLEAN_ELEMENTS = {};
  3152. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3153. BOOLEAN_ELEMENTS[value] = true;
  3154. });
  3155. var ALIASED_ATTR = {
  3156. 'ngMinlength': 'minlength',
  3157. 'ngMaxlength': 'maxlength',
  3158. 'ngMin': 'min',
  3159. 'ngMax': 'max',
  3160. 'ngPattern': 'pattern',
  3161. 'ngStep': 'step'
  3162. };
  3163. function getBooleanAttrName(element, name) {
  3164. // check dom last since we will most likely fail on name
  3165. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3166. // booleanAttr is here twice to minimize DOM access
  3167. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3168. }
  3169. function getAliasedAttrName(name) {
  3170. return ALIASED_ATTR[name];
  3171. }
  3172. forEach({
  3173. data: jqLiteData,
  3174. removeData: jqLiteRemoveData,
  3175. hasData: jqLiteHasData,
  3176. cleanData: function jqLiteCleanData(nodes) {
  3177. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3178. jqLiteRemoveData(nodes[i]);
  3179. }
  3180. }
  3181. }, function(fn, name) {
  3182. JQLite[name] = fn;
  3183. });
  3184. forEach({
  3185. data: jqLiteData,
  3186. inheritedData: jqLiteInheritedData,
  3187. scope: function(element) {
  3188. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3189. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3190. },
  3191. isolateScope: function(element) {
  3192. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3193. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3194. },
  3195. controller: jqLiteController,
  3196. injector: function(element) {
  3197. return jqLiteInheritedData(element, '$injector');
  3198. },
  3199. removeAttr: function(element, name) {
  3200. element.removeAttribute(name);
  3201. },
  3202. hasClass: jqLiteHasClass,
  3203. css: function(element, name, value) {
  3204. name = cssKebabToCamel(name);
  3205. if (isDefined(value)) {
  3206. element.style[name] = value;
  3207. } else {
  3208. return element.style[name];
  3209. }
  3210. },
  3211. attr: function(element, name, value) {
  3212. var ret;
  3213. var nodeType = element.nodeType;
  3214. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3215. !element.getAttribute) {
  3216. return;
  3217. }
  3218. var lowercasedName = lowercase(name);
  3219. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3220. if (isDefined(value)) {
  3221. // setter
  3222. if (value === null || (value === false && isBooleanAttr)) {
  3223. element.removeAttribute(name);
  3224. } else {
  3225. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3226. }
  3227. } else {
  3228. // getter
  3229. ret = element.getAttribute(name);
  3230. if (isBooleanAttr && ret !== null) {
  3231. ret = lowercasedName;
  3232. }
  3233. // Normalize non-existing attributes to undefined (as jQuery).
  3234. return ret === null ? undefined : ret;
  3235. }
  3236. },
  3237. prop: function(element, name, value) {
  3238. if (isDefined(value)) {
  3239. element[name] = value;
  3240. } else {
  3241. return element[name];
  3242. }
  3243. },
  3244. text: (function() {
  3245. getText.$dv = '';
  3246. return getText;
  3247. function getText(element, value) {
  3248. if (isUndefined(value)) {
  3249. var nodeType = element.nodeType;
  3250. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3251. }
  3252. element.textContent = value;
  3253. }
  3254. })(),
  3255. val: function(element, value) {
  3256. if (isUndefined(value)) {
  3257. if (element.multiple && nodeName_(element) === 'select') {
  3258. var result = [];
  3259. forEach(element.options, function(option) {
  3260. if (option.selected) {
  3261. result.push(option.value || option.text);
  3262. }
  3263. });
  3264. return result;
  3265. }
  3266. return element.value;
  3267. }
  3268. element.value = value;
  3269. },
  3270. html: function(element, value) {
  3271. if (isUndefined(value)) {
  3272. return element.innerHTML;
  3273. }
  3274. jqLiteDealoc(element, true);
  3275. element.innerHTML = value;
  3276. },
  3277. empty: jqLiteEmpty
  3278. }, function(fn, name) {
  3279. /**
  3280. * Properties: writes return selection, reads return first value
  3281. */
  3282. JQLite.prototype[name] = function(arg1, arg2) {
  3283. var i, key;
  3284. var nodeCount = this.length;
  3285. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3286. // in a way that survives minification.
  3287. // jqLiteEmpty takes no arguments but is a setter.
  3288. if (fn !== jqLiteEmpty &&
  3289. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3290. if (isObject(arg1)) {
  3291. // we are a write, but the object properties are the key/values
  3292. for (i = 0; i < nodeCount; i++) {
  3293. if (fn === jqLiteData) {
  3294. // data() takes the whole object in jQuery
  3295. fn(this[i], arg1);
  3296. } else {
  3297. for (key in arg1) {
  3298. fn(this[i], key, arg1[key]);
  3299. }
  3300. }
  3301. }
  3302. // return self for chaining
  3303. return this;
  3304. } else {
  3305. // we are a read, so read the first child.
  3306. // TODO: do we still need this?
  3307. var value = fn.$dv;
  3308. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3309. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3310. for (var j = 0; j < jj; j++) {
  3311. var nodeValue = fn(this[j], arg1, arg2);
  3312. value = value ? value + nodeValue : nodeValue;
  3313. }
  3314. return value;
  3315. }
  3316. } else {
  3317. // we are a write, so apply to all children
  3318. for (i = 0; i < nodeCount; i++) {
  3319. fn(this[i], arg1, arg2);
  3320. }
  3321. // return self for chaining
  3322. return this;
  3323. }
  3324. };
  3325. });
  3326. function createEventHandler(element, events) {
  3327. var eventHandler = function(event, type) {
  3328. // jQuery specific api
  3329. event.isDefaultPrevented = function() {
  3330. return event.defaultPrevented;
  3331. };
  3332. var eventFns = events[type || event.type];
  3333. var eventFnsLength = eventFns ? eventFns.length : 0;
  3334. if (!eventFnsLength) return;
  3335. if (isUndefined(event.immediatePropagationStopped)) {
  3336. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3337. event.stopImmediatePropagation = function() {
  3338. event.immediatePropagationStopped = true;
  3339. if (event.stopPropagation) {
  3340. event.stopPropagation();
  3341. }
  3342. if (originalStopImmediatePropagation) {
  3343. originalStopImmediatePropagation.call(event);
  3344. }
  3345. };
  3346. }
  3347. event.isImmediatePropagationStopped = function() {
  3348. return event.immediatePropagationStopped === true;
  3349. };
  3350. // Some events have special handlers that wrap the real handler
  3351. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3352. // Copy event handlers in case event handlers array is modified during execution.
  3353. if ((eventFnsLength > 1)) {
  3354. eventFns = shallowCopy(eventFns);
  3355. }
  3356. for (var i = 0; i < eventFnsLength; i++) {
  3357. if (!event.isImmediatePropagationStopped()) {
  3358. handlerWrapper(element, event, eventFns[i]);
  3359. }
  3360. }
  3361. };
  3362. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3363. // events on `element`
  3364. eventHandler.elem = element;
  3365. return eventHandler;
  3366. }
  3367. function defaultHandlerWrapper(element, event, handler) {
  3368. handler.call(element, event);
  3369. }
  3370. function specialMouseHandlerWrapper(target, event, handler) {
  3371. // Refer to jQuery's implementation of mouseenter & mouseleave
  3372. // Read about mouseenter and mouseleave:
  3373. // http://www.quirksmode.org/js/events_mouse.html#link8
  3374. var related = event.relatedTarget;
  3375. // For mousenter/leave call the handler if related is outside the target.
  3376. // NB: No relatedTarget if the mouse left/entered the browser window
  3377. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3378. handler.call(target, event);
  3379. }
  3380. }
  3381. //////////////////////////////////////////
  3382. // Functions iterating traversal.
  3383. // These functions chain results into a single
  3384. // selector.
  3385. //////////////////////////////////////////
  3386. forEach({
  3387. removeData: jqLiteRemoveData,
  3388. on: function jqLiteOn(element, type, fn, unsupported) {
  3389. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3390. // Do not add event handlers to non-elements because they will not be cleaned up.
  3391. if (!jqLiteAcceptsData(element)) {
  3392. return;
  3393. }
  3394. var expandoStore = jqLiteExpandoStore(element, true);
  3395. var events = expandoStore.events;
  3396. var handle = expandoStore.handle;
  3397. if (!handle) {
  3398. handle = expandoStore.handle = createEventHandler(element, events);
  3399. }
  3400. // http://jsperf.com/string-indexof-vs-split
  3401. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3402. var i = types.length;
  3403. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3404. var eventFns = events[type];
  3405. if (!eventFns) {
  3406. eventFns = events[type] = [];
  3407. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3408. if (type !== '$destroy' && !noEventListener) {
  3409. element.addEventListener(type, handle);
  3410. }
  3411. }
  3412. eventFns.push(fn);
  3413. };
  3414. while (i--) {
  3415. type = types[i];
  3416. if (MOUSE_EVENT_MAP[type]) {
  3417. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3418. addHandler(type, undefined, true);
  3419. } else {
  3420. addHandler(type);
  3421. }
  3422. }
  3423. },
  3424. off: jqLiteOff,
  3425. one: function(element, type, fn) {
  3426. element = jqLite(element);
  3427. //add the listener twice so that when it is called
  3428. //you can remove the original function and still be
  3429. //able to call element.off(ev, fn) normally
  3430. element.on(type, function onFn() {
  3431. element.off(type, fn);
  3432. element.off(type, onFn);
  3433. });
  3434. element.on(type, fn);
  3435. },
  3436. replaceWith: function(element, replaceNode) {
  3437. var index, parent = element.parentNode;
  3438. jqLiteDealoc(element);
  3439. forEach(new JQLite(replaceNode), function(node) {
  3440. if (index) {
  3441. parent.insertBefore(node, index.nextSibling);
  3442. } else {
  3443. parent.replaceChild(node, element);
  3444. }
  3445. index = node;
  3446. });
  3447. },
  3448. children: function(element) {
  3449. var children = [];
  3450. forEach(element.childNodes, function(element) {
  3451. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3452. children.push(element);
  3453. }
  3454. });
  3455. return children;
  3456. },
  3457. contents: function(element) {
  3458. return element.contentDocument || element.childNodes || [];
  3459. },
  3460. append: function(element, node) {
  3461. var nodeType = element.nodeType;
  3462. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3463. node = new JQLite(node);
  3464. for (var i = 0, ii = node.length; i < ii; i++) {
  3465. var child = node[i];
  3466. element.appendChild(child);
  3467. }
  3468. },
  3469. prepend: function(element, node) {
  3470. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3471. var index = element.firstChild;
  3472. forEach(new JQLite(node), function(child) {
  3473. element.insertBefore(child, index);
  3474. });
  3475. }
  3476. },
  3477. wrap: function(element, wrapNode) {
  3478. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3479. },
  3480. remove: jqLiteRemove,
  3481. detach: function(element) {
  3482. jqLiteRemove(element, true);
  3483. },
  3484. after: function(element, newElement) {
  3485. var index = element, parent = element.parentNode;
  3486. if (parent) {
  3487. newElement = new JQLite(newElement);
  3488. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3489. var node = newElement[i];
  3490. parent.insertBefore(node, index.nextSibling);
  3491. index = node;
  3492. }
  3493. }
  3494. },
  3495. addClass: jqLiteAddClass,
  3496. removeClass: jqLiteRemoveClass,
  3497. toggleClass: function(element, selector, condition) {
  3498. if (selector) {
  3499. forEach(selector.split(' '), function(className) {
  3500. var classCondition = condition;
  3501. if (isUndefined(classCondition)) {
  3502. classCondition = !jqLiteHasClass(element, className);
  3503. }
  3504. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3505. });
  3506. }
  3507. },
  3508. parent: function(element) {
  3509. var parent = element.parentNode;
  3510. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3511. },
  3512. next: function(element) {
  3513. return element.nextElementSibling;
  3514. },
  3515. find: function(element, selector) {
  3516. if (element.getElementsByTagName) {
  3517. return element.getElementsByTagName(selector);
  3518. } else {
  3519. return [];
  3520. }
  3521. },
  3522. clone: jqLiteClone,
  3523. triggerHandler: function(element, event, extraParameters) {
  3524. var dummyEvent, eventFnsCopy, handlerArgs;
  3525. var eventName = event.type || event;
  3526. var expandoStore = jqLiteExpandoStore(element);
  3527. var events = expandoStore && expandoStore.events;
  3528. var eventFns = events && events[eventName];
  3529. if (eventFns) {
  3530. // Create a dummy event to pass to the handlers
  3531. dummyEvent = {
  3532. preventDefault: function() { this.defaultPrevented = true; },
  3533. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3534. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3535. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3536. stopPropagation: noop,
  3537. type: eventName,
  3538. target: element
  3539. };
  3540. // If a custom event was provided then extend our dummy event with it
  3541. if (event.type) {
  3542. dummyEvent = extend(dummyEvent, event);
  3543. }
  3544. // Copy event handlers in case event handlers array is modified during execution.
  3545. eventFnsCopy = shallowCopy(eventFns);
  3546. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3547. forEach(eventFnsCopy, function(fn) {
  3548. if (!dummyEvent.isImmediatePropagationStopped()) {
  3549. fn.apply(element, handlerArgs);
  3550. }
  3551. });
  3552. }
  3553. }
  3554. }, function(fn, name) {
  3555. /**
  3556. * chaining functions
  3557. */
  3558. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3559. var value;
  3560. for (var i = 0, ii = this.length; i < ii; i++) {
  3561. if (isUndefined(value)) {
  3562. value = fn(this[i], arg1, arg2, arg3);
  3563. if (isDefined(value)) {
  3564. // any function which returns a value needs to be wrapped
  3565. value = jqLite(value);
  3566. }
  3567. } else {
  3568. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3569. }
  3570. }
  3571. return isDefined(value) ? value : this;
  3572. };
  3573. });
  3574. // bind legacy bind/unbind to on/off
  3575. JQLite.prototype.bind = JQLite.prototype.on;
  3576. JQLite.prototype.unbind = JQLite.prototype.off;
  3577. // Provider for private $$jqLite service
  3578. /** @this */
  3579. function $$jqLiteProvider() {
  3580. this.$get = function $$jqLite() {
  3581. return extend(JQLite, {
  3582. hasClass: function(node, classes) {
  3583. if (node.attr) node = node[0];
  3584. return jqLiteHasClass(node, classes);
  3585. },
  3586. addClass: function(node, classes) {
  3587. if (node.attr) node = node[0];
  3588. return jqLiteAddClass(node, classes);
  3589. },
  3590. removeClass: function(node, classes) {
  3591. if (node.attr) node = node[0];
  3592. return jqLiteRemoveClass(node, classes);
  3593. }
  3594. });
  3595. };
  3596. }
  3597. /**
  3598. * Computes a hash of an 'obj'.
  3599. * Hash of a:
  3600. * string is string
  3601. * number is number as string
  3602. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3603. * that is also assigned to the $$hashKey property of the object.
  3604. *
  3605. * @param obj
  3606. * @returns {string} hash string such that the same input will have the same hash string.
  3607. * The resulting string key is in 'type:hashKey' format.
  3608. */
  3609. function hashKey(obj, nextUidFn) {
  3610. var key = obj && obj.$$hashKey;
  3611. if (key) {
  3612. if (typeof key === 'function') {
  3613. key = obj.$$hashKey();
  3614. }
  3615. return key;
  3616. }
  3617. var objType = typeof obj;
  3618. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3619. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3620. } else {
  3621. key = objType + ':' + obj;
  3622. }
  3623. return key;
  3624. }
  3625. // A minimal ES2015 Map implementation.
  3626. // Should be bug/feature equivalent to the native implementations of supported browsers
  3627. // (for the features required in Angular).
  3628. // See https://kangax.github.io/compat-table/es6/#test-Map
  3629. var nanKey = Object.create(null);
  3630. function NgMapShim() {
  3631. this._keys = [];
  3632. this._values = [];
  3633. this._lastKey = NaN;
  3634. this._lastIndex = -1;
  3635. }
  3636. NgMapShim.prototype = {
  3637. _idx: function(key) {
  3638. if (key === this._lastKey) {
  3639. return this._lastIndex;
  3640. }
  3641. this._lastKey = key;
  3642. this._lastIndex = this._keys.indexOf(key);
  3643. return this._lastIndex;
  3644. },
  3645. _transformKey: function(key) {
  3646. return isNumberNaN(key) ? nanKey : key;
  3647. },
  3648. get: function(key) {
  3649. key = this._transformKey(key);
  3650. var idx = this._idx(key);
  3651. if (idx !== -1) {
  3652. return this._values[idx];
  3653. }
  3654. },
  3655. set: function(key, value) {
  3656. key = this._transformKey(key);
  3657. var idx = this._idx(key);
  3658. if (idx === -1) {
  3659. idx = this._lastIndex = this._keys.length;
  3660. }
  3661. this._keys[idx] = key;
  3662. this._values[idx] = value;
  3663. // Support: IE11
  3664. // Do not `return this` to simulate the partial IE11 implementation
  3665. },
  3666. delete: function(key) {
  3667. key = this._transformKey(key);
  3668. var idx = this._idx(key);
  3669. if (idx === -1) {
  3670. return false;
  3671. }
  3672. this._keys.splice(idx, 1);
  3673. this._values.splice(idx, 1);
  3674. this._lastKey = NaN;
  3675. this._lastIndex = -1;
  3676. return true;
  3677. }
  3678. };
  3679. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3680. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3681. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3682. var NgMap = NgMapShim;
  3683. var $$MapProvider = [/** @this */function() {
  3684. this.$get = [function() {
  3685. return NgMap;
  3686. }];
  3687. }];
  3688. /**
  3689. * @ngdoc function
  3690. * @module ng
  3691. * @name angular.injector
  3692. * @kind function
  3693. *
  3694. * @description
  3695. * Creates an injector object that can be used for retrieving services as well as for
  3696. * dependency injection (see {@link guide/di dependency injection}).
  3697. *
  3698. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3699. * {@link angular.module}. The `ng` module must be explicitly added.
  3700. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3701. * disallows argument name annotation inference.
  3702. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3703. *
  3704. * @example
  3705. * Typical usage
  3706. * ```js
  3707. * // create an injector
  3708. * var $injector = angular.injector(['ng']);
  3709. *
  3710. * // use the injector to kick off your application
  3711. * // use the type inference to auto inject arguments, or use implicit injection
  3712. * $injector.invoke(function($rootScope, $compile, $document) {
  3713. * $compile($document)($rootScope);
  3714. * $rootScope.$digest();
  3715. * });
  3716. * ```
  3717. *
  3718. * Sometimes you want to get access to the injector of a currently running AngularJS app
  3719. * from outside AngularJS. Perhaps, you want to inject and compile some markup after the
  3720. * application has been bootstrapped. You can do this using the extra `injector()` added
  3721. * to JQuery/jqLite elements. See {@link angular.element}.
  3722. *
  3723. * *This is fairly rare but could be the case if a third party library is injecting the
  3724. * markup.*
  3725. *
  3726. * In the following example a new block of HTML containing a `ng-controller`
  3727. * directive is added to the end of the document body by JQuery. We then compile and link
  3728. * it into the current AngularJS scope.
  3729. *
  3730. * ```js
  3731. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3732. * $(document.body).append($div);
  3733. *
  3734. * angular.element(document).injector().invoke(function($compile) {
  3735. * var scope = angular.element($div).scope();
  3736. * $compile($div)(scope);
  3737. * });
  3738. * ```
  3739. */
  3740. /**
  3741. * @ngdoc module
  3742. * @name auto
  3743. * @installation
  3744. * @description
  3745. *
  3746. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3747. */
  3748. var ARROW_ARG = /^([^(]+?)=>/;
  3749. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3750. var FN_ARG_SPLIT = /,/;
  3751. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3752. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3753. var $injectorMinErr = minErr('$injector');
  3754. function stringifyFn(fn) {
  3755. return Function.prototype.toString.call(fn);
  3756. }
  3757. function extractArgs(fn) {
  3758. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3759. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3760. return args;
  3761. }
  3762. function anonFn(fn) {
  3763. // For anonymous functions, showing at the very least the function signature can help in
  3764. // debugging.
  3765. var args = extractArgs(fn);
  3766. if (args) {
  3767. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3768. }
  3769. return 'fn';
  3770. }
  3771. function annotate(fn, strictDi, name) {
  3772. var $inject,
  3773. argDecl,
  3774. last;
  3775. if (typeof fn === 'function') {
  3776. if (!($inject = fn.$inject)) {
  3777. $inject = [];
  3778. if (fn.length) {
  3779. if (strictDi) {
  3780. if (!isString(name) || !name) {
  3781. name = fn.name || anonFn(fn);
  3782. }
  3783. throw $injectorMinErr('strictdi',
  3784. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3785. }
  3786. argDecl = extractArgs(fn);
  3787. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3788. arg.replace(FN_ARG, function(all, underscore, name) {
  3789. $inject.push(name);
  3790. });
  3791. });
  3792. }
  3793. fn.$inject = $inject;
  3794. }
  3795. } else if (isArray(fn)) {
  3796. last = fn.length - 1;
  3797. assertArgFn(fn[last], 'fn');
  3798. $inject = fn.slice(0, last);
  3799. } else {
  3800. assertArgFn(fn, 'fn', true);
  3801. }
  3802. return $inject;
  3803. }
  3804. ///////////////////////////////////////
  3805. /**
  3806. * @ngdoc service
  3807. * @name $injector
  3808. *
  3809. * @description
  3810. *
  3811. * `$injector` is used to retrieve object instances as defined by
  3812. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3813. * and load modules.
  3814. *
  3815. * The following always holds true:
  3816. *
  3817. * ```js
  3818. * var $injector = angular.injector();
  3819. * expect($injector.get('$injector')).toBe($injector);
  3820. * expect($injector.invoke(function($injector) {
  3821. * return $injector;
  3822. * })).toBe($injector);
  3823. * ```
  3824. *
  3825. * ## Injection Function Annotation
  3826. *
  3827. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3828. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3829. *
  3830. * ```js
  3831. * // inferred (only works if code not minified/obfuscated)
  3832. * $injector.invoke(function(serviceA){});
  3833. *
  3834. * // annotated
  3835. * function explicit(serviceA) {};
  3836. * explicit.$inject = ['serviceA'];
  3837. * $injector.invoke(explicit);
  3838. *
  3839. * // inline
  3840. * $injector.invoke(['serviceA', function(serviceA){}]);
  3841. * ```
  3842. *
  3843. * ### Inference
  3844. *
  3845. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3846. * can then be parsed and the function arguments can be extracted. This method of discovering
  3847. * annotations is disallowed when the injector is in strict mode.
  3848. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3849. * argument names.
  3850. *
  3851. * ### `$inject` Annotation
  3852. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3853. *
  3854. * ### Inline
  3855. * As an array of injection names, where the last item in the array is the function to call.
  3856. */
  3857. /**
  3858. * @ngdoc property
  3859. * @name $injector#modules
  3860. * @type {Object}
  3861. * @description
  3862. * A hash containing all the modules that have been loaded into the
  3863. * $injector.
  3864. *
  3865. * You can use this property to find out information about a module via the
  3866. * {@link angular.Module#info `myModule.info(...)`} method.
  3867. *
  3868. * For example:
  3869. *
  3870. * ```
  3871. * var info = $injector.modules['ngAnimate'].info();
  3872. * ```
  3873. *
  3874. * **Do not use this property to attempt to modify the modules after the application
  3875. * has been bootstrapped.**
  3876. */
  3877. /**
  3878. * @ngdoc method
  3879. * @name $injector#get
  3880. *
  3881. * @description
  3882. * Return an instance of the service.
  3883. *
  3884. * @param {string} name The name of the instance to retrieve.
  3885. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3886. * @return {*} The instance.
  3887. */
  3888. /**
  3889. * @ngdoc method
  3890. * @name $injector#invoke
  3891. *
  3892. * @description
  3893. * Invoke the method and supply the method arguments from the `$injector`.
  3894. *
  3895. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3896. * injected according to the {@link guide/di $inject Annotation} rules.
  3897. * @param {Object=} self The `this` for the invoked method.
  3898. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3899. * object first, before the `$injector` is consulted.
  3900. * @returns {*} the value returned by the invoked `fn` function.
  3901. */
  3902. /**
  3903. * @ngdoc method
  3904. * @name $injector#has
  3905. *
  3906. * @description
  3907. * Allows the user to query if the particular service exists.
  3908. *
  3909. * @param {string} name Name of the service to query.
  3910. * @returns {boolean} `true` if injector has given service.
  3911. */
  3912. /**
  3913. * @ngdoc method
  3914. * @name $injector#instantiate
  3915. * @description
  3916. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3917. * operator, and supplies all of the arguments to the constructor function as specified by the
  3918. * constructor annotation.
  3919. *
  3920. * @param {Function} Type Annotated constructor function.
  3921. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3922. * object first, before the `$injector` is consulted.
  3923. * @returns {Object} new instance of `Type`.
  3924. */
  3925. /**
  3926. * @ngdoc method
  3927. * @name $injector#annotate
  3928. *
  3929. * @description
  3930. * Returns an array of service names which the function is requesting for injection. This API is
  3931. * used by the injector to determine which services need to be injected into the function when the
  3932. * function is invoked. There are three ways in which the function can be annotated with the needed
  3933. * dependencies.
  3934. *
  3935. * #### Argument names
  3936. *
  3937. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3938. * by converting the function into a string using `toString()` method and extracting the argument
  3939. * names.
  3940. * ```js
  3941. * // Given
  3942. * function MyController($scope, $route) {
  3943. * // ...
  3944. * }
  3945. *
  3946. * // Then
  3947. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3948. * ```
  3949. *
  3950. * You can disallow this method by using strict injection mode.
  3951. *
  3952. * This method does not work with code minification / obfuscation. For this reason the following
  3953. * annotation strategies are supported.
  3954. *
  3955. * #### The `$inject` property
  3956. *
  3957. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3958. * represent names of services to be injected into the function.
  3959. * ```js
  3960. * // Given
  3961. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3962. * // ...
  3963. * }
  3964. * // Define function dependencies
  3965. * MyController['$inject'] = ['$scope', '$route'];
  3966. *
  3967. * // Then
  3968. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3969. * ```
  3970. *
  3971. * #### The array notation
  3972. *
  3973. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3974. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3975. * a way that survives minification is a better choice:
  3976. *
  3977. * ```js
  3978. * // We wish to write this (not minification / obfuscation safe)
  3979. * injector.invoke(function($compile, $rootScope) {
  3980. * // ...
  3981. * });
  3982. *
  3983. * // We are forced to write break inlining
  3984. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3985. * // ...
  3986. * };
  3987. * tmpFn.$inject = ['$compile', '$rootScope'];
  3988. * injector.invoke(tmpFn);
  3989. *
  3990. * // To better support inline function the inline annotation is supported
  3991. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3992. * // ...
  3993. * }]);
  3994. *
  3995. * // Therefore
  3996. * expect(injector.annotate(
  3997. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3998. * ).toEqual(['$compile', '$rootScope']);
  3999. * ```
  4000. *
  4001. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  4002. * be retrieved as described above.
  4003. *
  4004. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  4005. *
  4006. * @returns {Array.<string>} The names of the services which the function requires.
  4007. */
  4008. /**
  4009. * @ngdoc method
  4010. * @name $injector#loadNewModules
  4011. *
  4012. * @description
  4013. *
  4014. * **This is a dangerous API, which you use at your own risk!**
  4015. *
  4016. * Add the specified modules to the current injector.
  4017. *
  4018. * This method will add each of the injectables to the injector and execute all of the config and run
  4019. * blocks for each module passed to the method.
  4020. *
  4021. * If a module has already been loaded into the injector then it will not be loaded again.
  4022. *
  4023. * * The application developer is responsible for loading the code containing the modules; and for
  4024. * ensuring that lazy scripts are not downloaded and executed more often that desired.
  4025. * * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
  4026. * * Modules cannot be unloaded.
  4027. *
  4028. * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
  4029. * into the injector, which may indicate whether the script has been executed already.
  4030. *
  4031. * @example
  4032. * Here is an example of loading a bundle of modules, with a utility method called `getScript`:
  4033. *
  4034. * ```javascript
  4035. * app.factory('loadModule', function($injector) {
  4036. * return function loadModule(moduleName, bundleUrl) {
  4037. * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
  4038. * };
  4039. * })
  4040. * ```
  4041. *
  4042. * @param {Array<String|Function|Array>=} mods an array of modules to load into the application.
  4043. * Each item in the array should be the name of a predefined module or a (DI annotated)
  4044. * function that will be invoked by the injector as a `config` block.
  4045. * See: {@link angular.module modules}
  4046. */
  4047. /**
  4048. * @ngdoc service
  4049. * @name $provide
  4050. *
  4051. * @description
  4052. *
  4053. * The {@link auto.$provide $provide} service has a number of methods for registering components
  4054. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  4055. * {@link angular.Module}.
  4056. *
  4057. * An AngularJS **service** is a singleton object created by a **service factory**. These **service
  4058. * factories** are functions which, in turn, are created by a **service provider**.
  4059. * The **service providers** are constructor functions. When instantiated they must contain a
  4060. * property called `$get`, which holds the **service factory** function.
  4061. *
  4062. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  4063. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  4064. * function to get the instance of the **service**.
  4065. *
  4066. * Often services have no configuration options and there is no need to add methods to the service
  4067. * provider. The provider will be no more than a constructor function with a `$get` property. For
  4068. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  4069. * services without specifying a provider.
  4070. *
  4071. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  4072. * {@link auto.$injector $injector}
  4073. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  4074. * providers and services.
  4075. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  4076. * services, not providers.
  4077. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  4078. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  4079. * given factory function.
  4080. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  4081. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  4082. * a new object using the given constructor function.
  4083. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  4084. * will be able to modify or replace the implementation of another service.
  4085. *
  4086. * See the individual methods for more information and examples.
  4087. */
  4088. /**
  4089. * @ngdoc method
  4090. * @name $provide#provider
  4091. * @description
  4092. *
  4093. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4094. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4095. * service.
  4096. *
  4097. * Service provider names start with the name of the service they provide followed by `Provider`.
  4098. * For example, the {@link ng.$log $log} service has a provider called
  4099. * {@link ng.$logProvider $logProvider}.
  4100. *
  4101. * Service provider objects can have additional methods which allow configuration of the provider
  4102. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4103. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4104. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4105. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4106. * console or not.
  4107. *
  4108. * It is possible to inject other providers into the provider function,
  4109. * but the injected provider must have been defined before the one that requires it.
  4110. *
  4111. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4112. 'Provider'` key.
  4113. * @param {(Object|function())} provider If the provider is:
  4114. *
  4115. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4116. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4117. * - `Constructor`: a new instance of the provider will be created using
  4118. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4119. *
  4120. * @returns {Object} registered provider instance
  4121. * @example
  4122. *
  4123. * The following example shows how to create a simple event tracking service and register it using
  4124. * {@link auto.$provide#provider $provide.provider()}.
  4125. *
  4126. * ```js
  4127. * // Define the eventTracker provider
  4128. * function EventTrackerProvider() {
  4129. * var trackingUrl = '/track';
  4130. *
  4131. * // A provider method for configuring where the tracked events should been saved
  4132. * this.setTrackingUrl = function(url) {
  4133. * trackingUrl = url;
  4134. * };
  4135. *
  4136. * // The service factory function
  4137. * this.$get = ['$http', function($http) {
  4138. * var trackedEvents = {};
  4139. * return {
  4140. * // Call this to track an event
  4141. * event: function(event) {
  4142. * var count = trackedEvents[event] || 0;
  4143. * count += 1;
  4144. * trackedEvents[event] = count;
  4145. * return count;
  4146. * },
  4147. * // Call this to save the tracked events to the trackingUrl
  4148. * save: function() {
  4149. * $http.post(trackingUrl, trackedEvents);
  4150. * }
  4151. * };
  4152. * }];
  4153. * }
  4154. *
  4155. * describe('eventTracker', function() {
  4156. * var postSpy;
  4157. *
  4158. * beforeEach(module(function($provide) {
  4159. * // Register the eventTracker provider
  4160. * $provide.provider('eventTracker', EventTrackerProvider);
  4161. * }));
  4162. *
  4163. * beforeEach(module(function(eventTrackerProvider) {
  4164. * // Configure eventTracker provider
  4165. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4166. * }));
  4167. *
  4168. * it('tracks events', inject(function(eventTracker) {
  4169. * expect(eventTracker.event('login')).toEqual(1);
  4170. * expect(eventTracker.event('login')).toEqual(2);
  4171. * }));
  4172. *
  4173. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4174. * postSpy = spyOn($http, 'post');
  4175. * eventTracker.event('login');
  4176. * eventTracker.save();
  4177. * expect(postSpy).toHaveBeenCalled();
  4178. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4179. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4180. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4181. * }));
  4182. * });
  4183. * ```
  4184. */
  4185. /**
  4186. * @ngdoc method
  4187. * @name $provide#factory
  4188. * @description
  4189. *
  4190. * Register a **service factory**, which will be called to return the service instance.
  4191. * This is short for registering a service where its provider consists of only a `$get` property,
  4192. * which is the given service factory function.
  4193. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4194. * configure your service in a provider.
  4195. *
  4196. * @param {string} name The name of the instance.
  4197. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4198. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4199. * @returns {Object} registered provider instance
  4200. *
  4201. * @example
  4202. * Here is an example of registering a service
  4203. * ```js
  4204. * $provide.factory('ping', ['$http', function($http) {
  4205. * return function ping() {
  4206. * return $http.send('/ping');
  4207. * };
  4208. * }]);
  4209. * ```
  4210. * You would then inject and use this service like this:
  4211. * ```js
  4212. * someModule.controller('Ctrl', ['ping', function(ping) {
  4213. * ping();
  4214. * }]);
  4215. * ```
  4216. */
  4217. /**
  4218. * @ngdoc method
  4219. * @name $provide#service
  4220. * @description
  4221. *
  4222. * Register a **service constructor**, which will be invoked with `new` to create the service
  4223. * instance.
  4224. * This is short for registering a service where its provider's `$get` property is a factory
  4225. * function that returns an instance instantiated by the injector from the service constructor
  4226. * function.
  4227. *
  4228. * Internally it looks a bit like this:
  4229. *
  4230. * ```
  4231. * {
  4232. * $get: function() {
  4233. * return $injector.instantiate(constructor);
  4234. * }
  4235. * }
  4236. * ```
  4237. *
  4238. *
  4239. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4240. * as a type/class.
  4241. *
  4242. * @param {string} name The name of the instance.
  4243. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4244. * that will be instantiated.
  4245. * @returns {Object} registered provider instance
  4246. *
  4247. * @example
  4248. * Here is an example of registering a service using
  4249. * {@link auto.$provide#service $provide.service(class)}.
  4250. * ```js
  4251. * var Ping = function($http) {
  4252. * this.$http = $http;
  4253. * };
  4254. *
  4255. * Ping.$inject = ['$http'];
  4256. *
  4257. * Ping.prototype.send = function() {
  4258. * return this.$http.get('/ping');
  4259. * };
  4260. * $provide.service('ping', Ping);
  4261. * ```
  4262. * You would then inject and use this service like this:
  4263. * ```js
  4264. * someModule.controller('Ctrl', ['ping', function(ping) {
  4265. * ping.send();
  4266. * }]);
  4267. * ```
  4268. */
  4269. /**
  4270. * @ngdoc method
  4271. * @name $provide#value
  4272. * @description
  4273. *
  4274. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4275. * number, an array, an object or a function. This is short for registering a service where its
  4276. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4277. * service**. That also means it is not possible to inject other services into a value service.
  4278. *
  4279. * Value services are similar to constant services, except that they cannot be injected into a
  4280. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4281. * an AngularJS {@link auto.$provide#decorator decorator}.
  4282. *
  4283. * @param {string} name The name of the instance.
  4284. * @param {*} value The value.
  4285. * @returns {Object} registered provider instance
  4286. *
  4287. * @example
  4288. * Here are some examples of creating value services.
  4289. * ```js
  4290. * $provide.value('ADMIN_USER', 'admin');
  4291. *
  4292. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4293. *
  4294. * $provide.value('halfOf', function(value) {
  4295. * return value / 2;
  4296. * });
  4297. * ```
  4298. */
  4299. /**
  4300. * @ngdoc method
  4301. * @name $provide#constant
  4302. * @description
  4303. *
  4304. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4305. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4306. * possible to inject other services into a constant.
  4307. *
  4308. * But unlike {@link auto.$provide#value value}, a constant can be
  4309. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4310. * be overridden by an AngularJS {@link auto.$provide#decorator decorator}.
  4311. *
  4312. * @param {string} name The name of the constant.
  4313. * @param {*} value The constant value.
  4314. * @returns {Object} registered instance
  4315. *
  4316. * @example
  4317. * Here a some examples of creating constants:
  4318. * ```js
  4319. * $provide.constant('SHARD_HEIGHT', 306);
  4320. *
  4321. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4322. *
  4323. * $provide.constant('double', function(value) {
  4324. * return value * 2;
  4325. * });
  4326. * ```
  4327. */
  4328. /**
  4329. * @ngdoc method
  4330. * @name $provide#decorator
  4331. * @description
  4332. *
  4333. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4334. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4335. * service. The return value of the decorator function may be the original service, or a new service
  4336. * that replaces (or wraps and delegates to) the original service.
  4337. *
  4338. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4339. *
  4340. * @param {string} name The name of the service to decorate.
  4341. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4342. * provided and should return the decorated service instance. The function is called using
  4343. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4344. * Local injection arguments:
  4345. *
  4346. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4347. * decorated or delegated to.
  4348. *
  4349. * @example
  4350. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4351. * calls to {@link ng.$log#error $log.warn()}.
  4352. * ```js
  4353. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4354. * $delegate.warn = $delegate.error;
  4355. * return $delegate;
  4356. * }]);
  4357. * ```
  4358. */
  4359. function createInjector(modulesToLoad, strictDi) {
  4360. strictDi = (strictDi === true);
  4361. var INSTANTIATING = {},
  4362. providerSuffix = 'Provider',
  4363. path = [],
  4364. loadedModules = new NgMap(),
  4365. providerCache = {
  4366. $provide: {
  4367. provider: supportObject(provider),
  4368. factory: supportObject(factory),
  4369. service: supportObject(service),
  4370. value: supportObject(value),
  4371. constant: supportObject(constant),
  4372. decorator: decorator
  4373. }
  4374. },
  4375. providerInjector = (providerCache.$injector =
  4376. createInternalInjector(providerCache, function(serviceName, caller) {
  4377. if (angular.isString(caller)) {
  4378. path.push(caller);
  4379. }
  4380. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4381. })),
  4382. instanceCache = {},
  4383. protoInstanceInjector =
  4384. createInternalInjector(instanceCache, function(serviceName, caller) {
  4385. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4386. return instanceInjector.invoke(
  4387. provider.$get, provider, undefined, serviceName);
  4388. }),
  4389. instanceInjector = protoInstanceInjector;
  4390. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4391. instanceInjector.modules = providerInjector.modules = createMap();
  4392. var runBlocks = loadModules(modulesToLoad);
  4393. instanceInjector = protoInstanceInjector.get('$injector');
  4394. instanceInjector.strictDi = strictDi;
  4395. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4396. instanceInjector.loadNewModules = function(mods) {
  4397. forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
  4398. };
  4399. return instanceInjector;
  4400. ////////////////////////////////////
  4401. // $provider
  4402. ////////////////////////////////////
  4403. function supportObject(delegate) {
  4404. return function(key, value) {
  4405. if (isObject(key)) {
  4406. forEach(key, reverseParams(delegate));
  4407. } else {
  4408. return delegate(key, value);
  4409. }
  4410. };
  4411. }
  4412. function provider(name, provider_) {
  4413. assertNotHasOwnProperty(name, 'service');
  4414. if (isFunction(provider_) || isArray(provider_)) {
  4415. provider_ = providerInjector.instantiate(provider_);
  4416. }
  4417. if (!provider_.$get) {
  4418. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4419. }
  4420. return (providerCache[name + providerSuffix] = provider_);
  4421. }
  4422. function enforceReturnValue(name, factory) {
  4423. return /** @this */ function enforcedReturnValue() {
  4424. var result = instanceInjector.invoke(factory, this);
  4425. if (isUndefined(result)) {
  4426. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4427. }
  4428. return result;
  4429. };
  4430. }
  4431. function factory(name, factoryFn, enforce) {
  4432. return provider(name, {
  4433. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4434. });
  4435. }
  4436. function service(name, constructor) {
  4437. return factory(name, ['$injector', function($injector) {
  4438. return $injector.instantiate(constructor);
  4439. }]);
  4440. }
  4441. function value(name, val) { return factory(name, valueFn(val), false); }
  4442. function constant(name, value) {
  4443. assertNotHasOwnProperty(name, 'constant');
  4444. providerCache[name] = value;
  4445. instanceCache[name] = value;
  4446. }
  4447. function decorator(serviceName, decorFn) {
  4448. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4449. orig$get = origProvider.$get;
  4450. origProvider.$get = function() {
  4451. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4452. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4453. };
  4454. }
  4455. ////////////////////////////////////
  4456. // Module Loading
  4457. ////////////////////////////////////
  4458. function loadModules(modulesToLoad) {
  4459. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4460. var runBlocks = [], moduleFn;
  4461. forEach(modulesToLoad, function(module) {
  4462. if (loadedModules.get(module)) return;
  4463. loadedModules.set(module, true);
  4464. function runInvokeQueue(queue) {
  4465. var i, ii;
  4466. for (i = 0, ii = queue.length; i < ii; i++) {
  4467. var invokeArgs = queue[i],
  4468. provider = providerInjector.get(invokeArgs[0]);
  4469. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4470. }
  4471. }
  4472. try {
  4473. if (isString(module)) {
  4474. moduleFn = angularModule(module);
  4475. instanceInjector.modules[module] = moduleFn;
  4476. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4477. runInvokeQueue(moduleFn._invokeQueue);
  4478. runInvokeQueue(moduleFn._configBlocks);
  4479. } else if (isFunction(module)) {
  4480. runBlocks.push(providerInjector.invoke(module));
  4481. } else if (isArray(module)) {
  4482. runBlocks.push(providerInjector.invoke(module));
  4483. } else {
  4484. assertArgFn(module, 'module');
  4485. }
  4486. } catch (e) {
  4487. if (isArray(module)) {
  4488. module = module[module.length - 1];
  4489. }
  4490. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4491. // Safari & FF's stack traces don't contain error.message content
  4492. // unlike those of Chrome and IE
  4493. // So if stack doesn't contain message, we create a new string that contains both.
  4494. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4495. // eslint-disable-next-line no-ex-assign
  4496. e = e.message + '\n' + e.stack;
  4497. }
  4498. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4499. module, e.stack || e.message || e);
  4500. }
  4501. });
  4502. return runBlocks;
  4503. }
  4504. ////////////////////////////////////
  4505. // internal Injector
  4506. ////////////////////////////////////
  4507. function createInternalInjector(cache, factory) {
  4508. function getService(serviceName, caller) {
  4509. if (cache.hasOwnProperty(serviceName)) {
  4510. if (cache[serviceName] === INSTANTIATING) {
  4511. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4512. serviceName + ' <- ' + path.join(' <- '));
  4513. }
  4514. return cache[serviceName];
  4515. } else {
  4516. try {
  4517. path.unshift(serviceName);
  4518. cache[serviceName] = INSTANTIATING;
  4519. cache[serviceName] = factory(serviceName, caller);
  4520. return cache[serviceName];
  4521. } catch (err) {
  4522. if (cache[serviceName] === INSTANTIATING) {
  4523. delete cache[serviceName];
  4524. }
  4525. throw err;
  4526. } finally {
  4527. path.shift();
  4528. }
  4529. }
  4530. }
  4531. function injectionArgs(fn, locals, serviceName) {
  4532. var args = [],
  4533. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4534. for (var i = 0, length = $inject.length; i < length; i++) {
  4535. var key = $inject[i];
  4536. if (typeof key !== 'string') {
  4537. throw $injectorMinErr('itkn',
  4538. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4539. }
  4540. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4541. getService(key, serviceName));
  4542. }
  4543. return args;
  4544. }
  4545. function isClass(func) {
  4546. // Support: IE 9-11 only
  4547. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4548. if (msie || typeof func !== 'function') {
  4549. return false;
  4550. }
  4551. var result = func.$$ngIsClass;
  4552. if (!isBoolean(result)) {
  4553. // Support: Edge 12-13 only
  4554. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4555. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4556. }
  4557. return result;
  4558. }
  4559. function invoke(fn, self, locals, serviceName) {
  4560. if (typeof locals === 'string') {
  4561. serviceName = locals;
  4562. locals = null;
  4563. }
  4564. var args = injectionArgs(fn, locals, serviceName);
  4565. if (isArray(fn)) {
  4566. fn = fn[fn.length - 1];
  4567. }
  4568. if (!isClass(fn)) {
  4569. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4570. // #5388
  4571. return fn.apply(self, args);
  4572. } else {
  4573. args.unshift(null);
  4574. return new (Function.prototype.bind.apply(fn, args))();
  4575. }
  4576. }
  4577. function instantiate(Type, locals, serviceName) {
  4578. // Check if Type is annotated and use just the given function at n-1 as parameter
  4579. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4580. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4581. var args = injectionArgs(Type, locals, serviceName);
  4582. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4583. args.unshift(null);
  4584. return new (Function.prototype.bind.apply(ctor, args))();
  4585. }
  4586. return {
  4587. invoke: invoke,
  4588. instantiate: instantiate,
  4589. get: getService,
  4590. annotate: createInjector.$$annotate,
  4591. has: function(name) {
  4592. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4593. }
  4594. };
  4595. }
  4596. }
  4597. createInjector.$$annotate = annotate;
  4598. /**
  4599. * @ngdoc provider
  4600. * @name $anchorScrollProvider
  4601. * @this
  4602. *
  4603. * @description
  4604. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4605. * {@link ng.$location#hash $location.hash()} changes.
  4606. */
  4607. function $AnchorScrollProvider() {
  4608. var autoScrollingEnabled = true;
  4609. /**
  4610. * @ngdoc method
  4611. * @name $anchorScrollProvider#disableAutoScrolling
  4612. *
  4613. * @description
  4614. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4615. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4616. * Use this method to disable automatic scrolling.
  4617. *
  4618. * If automatic scrolling is disabled, one must explicitly call
  4619. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4620. * current hash.
  4621. */
  4622. this.disableAutoScrolling = function() {
  4623. autoScrollingEnabled = false;
  4624. };
  4625. /**
  4626. * @ngdoc service
  4627. * @name $anchorScroll
  4628. * @kind function
  4629. * @requires $window
  4630. * @requires $location
  4631. * @requires $rootScope
  4632. *
  4633. * @description
  4634. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4635. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4636. * in the
  4637. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4638. *
  4639. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4640. * match any anchor whenever it changes. This can be disabled by calling
  4641. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4642. *
  4643. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4644. * vertical scroll-offset (either fixed or dynamic).
  4645. *
  4646. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4647. * {@link ng.$location#hash $location.hash()} will be used.
  4648. *
  4649. * @property {(number|function|jqLite)} yOffset
  4650. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4651. * positioned elements at the top of the page, such as navbars, headers etc.
  4652. *
  4653. * `yOffset` can be specified in various ways:
  4654. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4655. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4656. * a number representing the offset (in pixels).<br /><br />
  4657. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4658. * the top of the page to the element's bottom will be used as offset.<br />
  4659. * **Note**: The element will be taken into account only as long as its `position` is set to
  4660. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4661. * their height and/or positioning according to the viewport's size.
  4662. *
  4663. * <br />
  4664. * <div class="alert alert-warning">
  4665. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4666. * not some child element.
  4667. * </div>
  4668. *
  4669. * @example
  4670. <example module="anchorScrollExample" name="anchor-scroll">
  4671. <file name="index.html">
  4672. <div id="scrollArea" ng-controller="ScrollController">
  4673. <a ng-click="gotoBottom()">Go to bottom</a>
  4674. <a id="bottom"></a> You're at the bottom!
  4675. </div>
  4676. </file>
  4677. <file name="script.js">
  4678. angular.module('anchorScrollExample', [])
  4679. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4680. function($scope, $location, $anchorScroll) {
  4681. $scope.gotoBottom = function() {
  4682. // set the location.hash to the id of
  4683. // the element you wish to scroll to.
  4684. $location.hash('bottom');
  4685. // call $anchorScroll()
  4686. $anchorScroll();
  4687. };
  4688. }]);
  4689. </file>
  4690. <file name="style.css">
  4691. #scrollArea {
  4692. height: 280px;
  4693. overflow: auto;
  4694. }
  4695. #bottom {
  4696. display: block;
  4697. margin-top: 2000px;
  4698. }
  4699. </file>
  4700. </example>
  4701. *
  4702. * <hr />
  4703. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4704. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4705. *
  4706. * @example
  4707. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4708. <file name="index.html">
  4709. <div class="fixed-header" ng-controller="headerCtrl">
  4710. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4711. Go to anchor {{x}}
  4712. </a>
  4713. </div>
  4714. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4715. Anchor {{x}} of 5
  4716. </div>
  4717. </file>
  4718. <file name="script.js">
  4719. angular.module('anchorScrollOffsetExample', [])
  4720. .run(['$anchorScroll', function($anchorScroll) {
  4721. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4722. }])
  4723. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4724. function($anchorScroll, $location, $scope) {
  4725. $scope.gotoAnchor = function(x) {
  4726. var newHash = 'anchor' + x;
  4727. if ($location.hash() !== newHash) {
  4728. // set the $location.hash to `newHash` and
  4729. // $anchorScroll will automatically scroll to it
  4730. $location.hash('anchor' + x);
  4731. } else {
  4732. // call $anchorScroll() explicitly,
  4733. // since $location.hash hasn't changed
  4734. $anchorScroll();
  4735. }
  4736. };
  4737. }
  4738. ]);
  4739. </file>
  4740. <file name="style.css">
  4741. body {
  4742. padding-top: 50px;
  4743. }
  4744. .anchor {
  4745. border: 2px dashed DarkOrchid;
  4746. padding: 10px 10px 200px 10px;
  4747. }
  4748. .fixed-header {
  4749. background-color: rgba(0, 0, 0, 0.2);
  4750. height: 50px;
  4751. position: fixed;
  4752. top: 0; left: 0; right: 0;
  4753. }
  4754. .fixed-header > a {
  4755. display: inline-block;
  4756. margin: 5px 15px;
  4757. }
  4758. </file>
  4759. </example>
  4760. */
  4761. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4762. var document = $window.document;
  4763. // Helper function to get first anchor from a NodeList
  4764. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4765. // and working in all supported browsers.)
  4766. function getFirstAnchor(list) {
  4767. var result = null;
  4768. Array.prototype.some.call(list, function(element) {
  4769. if (nodeName_(element) === 'a') {
  4770. result = element;
  4771. return true;
  4772. }
  4773. });
  4774. return result;
  4775. }
  4776. function getYOffset() {
  4777. var offset = scroll.yOffset;
  4778. if (isFunction(offset)) {
  4779. offset = offset();
  4780. } else if (isElement(offset)) {
  4781. var elem = offset[0];
  4782. var style = $window.getComputedStyle(elem);
  4783. if (style.position !== 'fixed') {
  4784. offset = 0;
  4785. } else {
  4786. offset = elem.getBoundingClientRect().bottom;
  4787. }
  4788. } else if (!isNumber(offset)) {
  4789. offset = 0;
  4790. }
  4791. return offset;
  4792. }
  4793. function scrollTo(elem) {
  4794. if (elem) {
  4795. elem.scrollIntoView();
  4796. var offset = getYOffset();
  4797. if (offset) {
  4798. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4799. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4800. // top of the viewport.
  4801. //
  4802. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4803. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4804. // way down the page.
  4805. //
  4806. // This is often the case for elements near the bottom of the page.
  4807. //
  4808. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4809. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4810. // desired position.
  4811. var elemTop = elem.getBoundingClientRect().top;
  4812. $window.scrollBy(0, elemTop - offset);
  4813. }
  4814. } else {
  4815. $window.scrollTo(0, 0);
  4816. }
  4817. }
  4818. function scroll(hash) {
  4819. // Allow numeric hashes
  4820. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4821. var elm;
  4822. // empty hash, scroll to the top of the page
  4823. if (!hash) scrollTo(null);
  4824. // element with given id
  4825. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4826. // first anchor with given name :-D
  4827. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4828. // no element and hash === 'top', scroll to the top of the page
  4829. else if (hash === 'top') scrollTo(null);
  4830. }
  4831. // does not scroll when user clicks on anchor link that is currently on
  4832. // (no url change, no $location.hash() change), browser native does scroll
  4833. if (autoScrollingEnabled) {
  4834. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4835. function autoScrollWatchAction(newVal, oldVal) {
  4836. // skip the initial scroll if $location.hash is empty
  4837. if (newVal === oldVal && newVal === '') return;
  4838. jqLiteDocumentLoaded(function() {
  4839. $rootScope.$evalAsync(scroll);
  4840. });
  4841. });
  4842. }
  4843. return scroll;
  4844. }];
  4845. }
  4846. var $animateMinErr = minErr('$animate');
  4847. var ELEMENT_NODE = 1;
  4848. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4849. function mergeClasses(a,b) {
  4850. if (!a && !b) return '';
  4851. if (!a) return b;
  4852. if (!b) return a;
  4853. if (isArray(a)) a = a.join(' ');
  4854. if (isArray(b)) b = b.join(' ');
  4855. return a + ' ' + b;
  4856. }
  4857. function extractElementNode(element) {
  4858. for (var i = 0; i < element.length; i++) {
  4859. var elm = element[i];
  4860. if (elm.nodeType === ELEMENT_NODE) {
  4861. return elm;
  4862. }
  4863. }
  4864. }
  4865. function splitClasses(classes) {
  4866. if (isString(classes)) {
  4867. classes = classes.split(' ');
  4868. }
  4869. // Use createMap() to prevent class assumptions involving property names in
  4870. // Object.prototype
  4871. var obj = createMap();
  4872. forEach(classes, function(klass) {
  4873. // sometimes the split leaves empty string values
  4874. // incase extra spaces were applied to the options
  4875. if (klass.length) {
  4876. obj[klass] = true;
  4877. }
  4878. });
  4879. return obj;
  4880. }
  4881. // if any other type of options value besides an Object value is
  4882. // passed into the $animate.method() animation then this helper code
  4883. // will be run which will ignore it. While this patch is not the
  4884. // greatest solution to this, a lot of existing plugins depend on
  4885. // $animate to either call the callback (< 1.2) or return a promise
  4886. // that can be changed. This helper function ensures that the options
  4887. // are wiped clean incase a callback function is provided.
  4888. function prepareAnimateOptions(options) {
  4889. return isObject(options)
  4890. ? options
  4891. : {};
  4892. }
  4893. var $$CoreAnimateJsProvider = /** @this */ function() {
  4894. this.$get = noop;
  4895. };
  4896. // this is prefixed with Core since it conflicts with
  4897. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4898. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4899. var postDigestQueue = new NgMap();
  4900. var postDigestElements = [];
  4901. this.$get = ['$$AnimateRunner', '$rootScope',
  4902. function($$AnimateRunner, $rootScope) {
  4903. return {
  4904. enabled: noop,
  4905. on: noop,
  4906. off: noop,
  4907. pin: noop,
  4908. push: function(element, event, options, domOperation) {
  4909. if (domOperation) {
  4910. domOperation();
  4911. }
  4912. options = options || {};
  4913. if (options.from) {
  4914. element.css(options.from);
  4915. }
  4916. if (options.to) {
  4917. element.css(options.to);
  4918. }
  4919. if (options.addClass || options.removeClass) {
  4920. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4921. }
  4922. var runner = new $$AnimateRunner();
  4923. // since there are no animations to run the runner needs to be
  4924. // notified that the animation call is complete.
  4925. runner.complete();
  4926. return runner;
  4927. }
  4928. };
  4929. function updateData(data, classes, value) {
  4930. var changed = false;
  4931. if (classes) {
  4932. classes = isString(classes) ? classes.split(' ') :
  4933. isArray(classes) ? classes : [];
  4934. forEach(classes, function(className) {
  4935. if (className) {
  4936. changed = true;
  4937. data[className] = value;
  4938. }
  4939. });
  4940. }
  4941. return changed;
  4942. }
  4943. function handleCSSClassChanges() {
  4944. forEach(postDigestElements, function(element) {
  4945. var data = postDigestQueue.get(element);
  4946. if (data) {
  4947. var existing = splitClasses(element.attr('class'));
  4948. var toAdd = '';
  4949. var toRemove = '';
  4950. forEach(data, function(status, className) {
  4951. var hasClass = !!existing[className];
  4952. if (status !== hasClass) {
  4953. if (status) {
  4954. toAdd += (toAdd.length ? ' ' : '') + className;
  4955. } else {
  4956. toRemove += (toRemove.length ? ' ' : '') + className;
  4957. }
  4958. }
  4959. });
  4960. forEach(element, function(elm) {
  4961. if (toAdd) {
  4962. jqLiteAddClass(elm, toAdd);
  4963. }
  4964. if (toRemove) {
  4965. jqLiteRemoveClass(elm, toRemove);
  4966. }
  4967. });
  4968. postDigestQueue.delete(element);
  4969. }
  4970. });
  4971. postDigestElements.length = 0;
  4972. }
  4973. function addRemoveClassesPostDigest(element, add, remove) {
  4974. var data = postDigestQueue.get(element) || {};
  4975. var classesAdded = updateData(data, add, true);
  4976. var classesRemoved = updateData(data, remove, false);
  4977. if (classesAdded || classesRemoved) {
  4978. postDigestQueue.set(element, data);
  4979. postDigestElements.push(element);
  4980. if (postDigestElements.length === 1) {
  4981. $rootScope.$$postDigest(handleCSSClassChanges);
  4982. }
  4983. }
  4984. }
  4985. }];
  4986. };
  4987. /**
  4988. * @ngdoc provider
  4989. * @name $animateProvider
  4990. *
  4991. * @description
  4992. * Default implementation of $animate that doesn't perform any animations, instead just
  4993. * synchronously performs DOM updates and resolves the returned runner promise.
  4994. *
  4995. * In order to enable animations the `ngAnimate` module has to be loaded.
  4996. *
  4997. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4998. */
  4999. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  5000. var provider = this;
  5001. var classNameFilter = null;
  5002. var customFilter = null;
  5003. this.$$registeredAnimations = Object.create(null);
  5004. /**
  5005. * @ngdoc method
  5006. * @name $animateProvider#register
  5007. *
  5008. * @description
  5009. * Registers a new injectable animation factory function. The factory function produces the
  5010. * animation object which contains callback functions for each event that is expected to be
  5011. * animated.
  5012. *
  5013. * * `eventFn`: `function(element, ... , doneFunction, options)`
  5014. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  5015. * on the type of animation additional arguments will be injected into the animation function. The
  5016. * list below explains the function signatures for the different animation methods:
  5017. *
  5018. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  5019. * - addClass: function(element, addedClasses, doneFunction, options)
  5020. * - removeClass: function(element, removedClasses, doneFunction, options)
  5021. * - enter, leave, move: function(element, doneFunction, options)
  5022. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  5023. *
  5024. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  5025. *
  5026. * ```js
  5027. * return {
  5028. * //enter, leave, move signature
  5029. * eventFn : function(element, done, options) {
  5030. * //code to run the animation
  5031. * //once complete, then run done()
  5032. * return function endFunction(wasCancelled) {
  5033. * //code to cancel the animation
  5034. * }
  5035. * }
  5036. * }
  5037. * ```
  5038. *
  5039. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  5040. * @param {Function} factory The factory function that will be executed to return the animation
  5041. * object.
  5042. */
  5043. this.register = function(name, factory) {
  5044. if (name && name.charAt(0) !== '.') {
  5045. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  5046. }
  5047. var key = name + '-animation';
  5048. provider.$$registeredAnimations[name.substr(1)] = key;
  5049. $provide.factory(key, factory);
  5050. };
  5051. /**
  5052. * @ngdoc method
  5053. * @name $animateProvider#customFilter
  5054. *
  5055. * @description
  5056. * Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
  5057. * determine if an animation is allowed or not. When no filter is specified (the default), no
  5058. * animation will be blocked. Setting the `customFilter` value will only allow animations for
  5059. * which the filter function's return value is truthy.
  5060. *
  5061. * This allows to easily create arbitrarily complex rules for filtering animations, such as
  5062. * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
  5063. * Filtering animations can also boost performance for low-powered devices, as well as
  5064. * applications containing a lot of structural operations.
  5065. *
  5066. * <div class="alert alert-success">
  5067. * **Best Practice:**
  5068. * Keep the filtering function as lean as possible, because it will be called for each DOM
  5069. * action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
  5070. * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
  5071. * directives that support animations.
  5072. * Performing computationally expensive or time-consuming operations on each call of the
  5073. * filtering function can make your animations sluggish.
  5074. * </div>
  5075. *
  5076. * **Note:** If present, `customFilter` will be checked before
  5077. * {@link $animateProvider#classNameFilter classNameFilter}.
  5078. *
  5079. * @param {Function=} filterFn - The filter function which will be used to filter all animations.
  5080. * If a falsy value is returned, no animation will be performed. The function will be called
  5081. * with the following arguments:
  5082. * - **node** `{DOMElement}` - The DOM element to be animated.
  5083. * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
  5084. * etc).
  5085. * - **options** `{Object}` - A collection of options/styles used for the animation.
  5086. * @return {Function} The current filter function or `null` if there is none set.
  5087. */
  5088. this.customFilter = function(filterFn) {
  5089. if (arguments.length === 1) {
  5090. customFilter = isFunction(filterFn) ? filterFn : null;
  5091. }
  5092. return customFilter;
  5093. };
  5094. /**
  5095. * @ngdoc method
  5096. * @name $animateProvider#classNameFilter
  5097. *
  5098. * @description
  5099. * Sets and/or returns the CSS class regular expression that is checked when performing
  5100. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  5101. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  5102. * When setting the `classNameFilter` value, animations will only be performed on elements
  5103. * that successfully match the filter expression. This in turn can boost performance
  5104. * for low-powered devices as well as applications containing a lot of structural operations.
  5105. *
  5106. * **Note:** If present, `classNameFilter` will be checked after
  5107. * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
  5108. * false, `classNameFilter` will not be checked.
  5109. *
  5110. * @param {RegExp=} expression The className expression which will be checked against all animations
  5111. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  5112. */
  5113. this.classNameFilter = function(expression) {
  5114. if (arguments.length === 1) {
  5115. classNameFilter = (expression instanceof RegExp) ? expression : null;
  5116. if (classNameFilter) {
  5117. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  5118. if (reservedRegex.test(classNameFilter.toString())) {
  5119. classNameFilter = null;
  5120. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  5121. }
  5122. }
  5123. }
  5124. return classNameFilter;
  5125. };
  5126. this.$get = ['$$animateQueue', function($$animateQueue) {
  5127. function domInsert(element, parentElement, afterElement) {
  5128. // if for some reason the previous element was removed
  5129. // from the dom sometime before this code runs then let's
  5130. // just stick to using the parent element as the anchor
  5131. if (afterElement) {
  5132. var afterNode = extractElementNode(afterElement);
  5133. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  5134. afterElement = null;
  5135. }
  5136. }
  5137. if (afterElement) {
  5138. afterElement.after(element);
  5139. } else {
  5140. parentElement.prepend(element);
  5141. }
  5142. }
  5143. /**
  5144. * @ngdoc service
  5145. * @name $animate
  5146. * @description The $animate service exposes a series of DOM utility methods that provide support
  5147. * for animation hooks. The default behavior is the application of DOM operations, however,
  5148. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5149. * to ensure that animation runs with the triggered DOM operation.
  5150. *
  5151. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5152. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5153. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5154. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5155. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5156. *
  5157. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5158. *
  5159. * To learn more about enabling animation support, click here to visit the
  5160. * {@link ngAnimate ngAnimate module page}.
  5161. */
  5162. return {
  5163. // we don't call it directly since non-existant arguments may
  5164. // be interpreted as null within the sub enabled function
  5165. /**
  5166. *
  5167. * @ngdoc method
  5168. * @name $animate#on
  5169. * @kind function
  5170. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5171. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5172. * is fired with the following params:
  5173. *
  5174. * ```js
  5175. * $animate.on('enter', container,
  5176. * function callback(element, phase) {
  5177. * // cool we detected an enter animation within the container
  5178. * }
  5179. * );
  5180. * ```
  5181. *
  5182. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5183. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5184. * as well as among its children
  5185. * @param {Function} callback the callback function that will be fired when the listener is triggered
  5186. *
  5187. * The arguments present in the callback function are:
  5188. * * `element` - The captured DOM element that the animation was fired on.
  5189. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5190. */
  5191. on: $$animateQueue.on,
  5192. /**
  5193. *
  5194. * @ngdoc method
  5195. * @name $animate#off
  5196. * @kind function
  5197. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5198. * can be used in three different ways depending on the arguments:
  5199. *
  5200. * ```js
  5201. * // remove all the animation event listeners listening for `enter`
  5202. * $animate.off('enter');
  5203. *
  5204. * // remove listeners for all animation events from the container element
  5205. * $animate.off(container);
  5206. *
  5207. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5208. * $animate.off('enter', container);
  5209. *
  5210. * // remove the event listener function provided by `callback` that is set
  5211. * // to listen for `enter` on the given `container` as well as its children
  5212. * $animate.off('enter', container, callback);
  5213. * ```
  5214. *
  5215. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5216. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5217. * arguments are ignored.
  5218. * @param {DOMElement=} container the container element the event listener was placed on
  5219. * @param {Function=} callback the callback function that was registered as the listener
  5220. */
  5221. off: $$animateQueue.off,
  5222. /**
  5223. * @ngdoc method
  5224. * @name $animate#pin
  5225. * @kind function
  5226. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5227. * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the
  5228. * element despite being outside the realm of the application or within another application. Say for example if the application
  5229. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5230. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5231. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5232. *
  5233. * Note that this feature is only active when the `ngAnimate` module is used.
  5234. *
  5235. * @param {DOMElement} element the external element that will be pinned
  5236. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5237. */
  5238. pin: $$animateQueue.pin,
  5239. /**
  5240. *
  5241. * @ngdoc method
  5242. * @name $animate#enabled
  5243. * @kind function
  5244. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5245. * function can be called in four ways:
  5246. *
  5247. * ```js
  5248. * // returns true or false
  5249. * $animate.enabled();
  5250. *
  5251. * // changes the enabled state for all animations
  5252. * $animate.enabled(false);
  5253. * $animate.enabled(true);
  5254. *
  5255. * // returns true or false if animations are enabled for an element
  5256. * $animate.enabled(element);
  5257. *
  5258. * // changes the enabled state for an element and its children
  5259. * $animate.enabled(element, true);
  5260. * $animate.enabled(element, false);
  5261. * ```
  5262. *
  5263. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5264. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5265. *
  5266. * @return {boolean} whether or not animations are enabled
  5267. */
  5268. enabled: $$animateQueue.enabled,
  5269. /**
  5270. * @ngdoc method
  5271. * @name $animate#cancel
  5272. * @kind function
  5273. * @description Cancels the provided animation.
  5274. *
  5275. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  5276. */
  5277. cancel: function(runner) {
  5278. if (runner.end) {
  5279. runner.end();
  5280. }
  5281. },
  5282. /**
  5283. *
  5284. * @ngdoc method
  5285. * @name $animate#enter
  5286. * @kind function
  5287. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5288. * as the first child within the `parent` element and then triggers an animation.
  5289. * A promise is returned that will be resolved during the next digest once the animation
  5290. * has completed.
  5291. *
  5292. * @param {DOMElement} element the element which will be inserted into the DOM
  5293. * @param {DOMElement} parent the parent element which will append the element as
  5294. * a child (so long as the after element is not present)
  5295. * @param {DOMElement=} after the sibling element after which the element will be appended
  5296. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5297. * The object can have the following properties:
  5298. *
  5299. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5300. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5301. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5302. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5303. *
  5304. * @return {Promise} the animation callback promise
  5305. */
  5306. enter: function(element, parent, after, options) {
  5307. parent = parent && jqLite(parent);
  5308. after = after && jqLite(after);
  5309. parent = parent || after.parent();
  5310. domInsert(element, parent, after);
  5311. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5312. },
  5313. /**
  5314. *
  5315. * @ngdoc method
  5316. * @name $animate#move
  5317. * @kind function
  5318. * @description Inserts (moves) the element into its new position in the DOM either after
  5319. * the `after` element (if provided) or as the first child within the `parent` element
  5320. * and then triggers an animation. A promise is returned that will be resolved
  5321. * during the next digest once the animation has completed.
  5322. *
  5323. * @param {DOMElement} element the element which will be moved into the new DOM position
  5324. * @param {DOMElement} parent the parent element which will append the element as
  5325. * a child (so long as the after element is not present)
  5326. * @param {DOMElement=} after the sibling element after which the element will be appended
  5327. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5328. * The object can have the following properties:
  5329. *
  5330. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5331. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5332. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5333. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5334. *
  5335. * @return {Promise} the animation callback promise
  5336. */
  5337. move: function(element, parent, after, options) {
  5338. parent = parent && jqLite(parent);
  5339. after = after && jqLite(after);
  5340. parent = parent || after.parent();
  5341. domInsert(element, parent, after);
  5342. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5343. },
  5344. /**
  5345. * @ngdoc method
  5346. * @name $animate#leave
  5347. * @kind function
  5348. * @description Triggers an animation and then removes the element from the DOM.
  5349. * When the function is called a promise is returned that will be resolved during the next
  5350. * digest once the animation has completed.
  5351. *
  5352. * @param {DOMElement} element the element which will be removed from the DOM
  5353. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5354. * The object can have the following properties:
  5355. *
  5356. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5357. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5358. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5359. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5360. *
  5361. * @return {Promise} the animation callback promise
  5362. */
  5363. leave: function(element, options) {
  5364. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5365. element.remove();
  5366. });
  5367. },
  5368. /**
  5369. * @ngdoc method
  5370. * @name $animate#addClass
  5371. * @kind function
  5372. *
  5373. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5374. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5375. * animation if element already contains the CSS class or if the class is removed at a later step.
  5376. * Note that class-based animations are treated differently compared to structural animations
  5377. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5378. * depending if CSS or JavaScript animations are used.
  5379. *
  5380. * @param {DOMElement} element the element which the CSS classes will be applied to
  5381. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5382. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5383. * The object can have the following properties:
  5384. *
  5385. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5386. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5387. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5388. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5389. *
  5390. * @return {Promise} the animation callback promise
  5391. */
  5392. addClass: function(element, className, options) {
  5393. options = prepareAnimateOptions(options);
  5394. options.addClass = mergeClasses(options.addclass, className);
  5395. return $$animateQueue.push(element, 'addClass', options);
  5396. },
  5397. /**
  5398. * @ngdoc method
  5399. * @name $animate#removeClass
  5400. * @kind function
  5401. *
  5402. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5403. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5404. * animation if element does not contain the CSS class or if the class is added at a later step.
  5405. * Note that class-based animations are treated differently compared to structural animations
  5406. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5407. * depending if CSS or JavaScript animations are used.
  5408. *
  5409. * @param {DOMElement} element the element which the CSS classes will be applied to
  5410. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5411. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5412. * The object can have the following properties:
  5413. *
  5414. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5415. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5416. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5417. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5418. *
  5419. * @return {Promise} the animation callback promise
  5420. */
  5421. removeClass: function(element, className, options) {
  5422. options = prepareAnimateOptions(options);
  5423. options.removeClass = mergeClasses(options.removeClass, className);
  5424. return $$animateQueue.push(element, 'removeClass', options);
  5425. },
  5426. /**
  5427. * @ngdoc method
  5428. * @name $animate#setClass
  5429. * @kind function
  5430. *
  5431. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5432. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5433. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5434. * passed. Note that class-based animations are treated differently compared to structural animations
  5435. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5436. * depending if CSS or JavaScript animations are used.
  5437. *
  5438. * @param {DOMElement} element the element which the CSS classes will be applied to
  5439. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5440. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5441. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5442. * The object can have the following properties:
  5443. *
  5444. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5445. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5446. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5447. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5448. *
  5449. * @return {Promise} the animation callback promise
  5450. */
  5451. setClass: function(element, add, remove, options) {
  5452. options = prepareAnimateOptions(options);
  5453. options.addClass = mergeClasses(options.addClass, add);
  5454. options.removeClass = mergeClasses(options.removeClass, remove);
  5455. return $$animateQueue.push(element, 'setClass', options);
  5456. },
  5457. /**
  5458. * @ngdoc method
  5459. * @name $animate#animate
  5460. * @kind function
  5461. *
  5462. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5463. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5464. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5465. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5466. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5467. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5468. * method (or as part of the `options` parameter):
  5469. *
  5470. * ```js
  5471. * ngModule.animation('.my-inline-animation', function() {
  5472. * return {
  5473. * animate : function(element, from, to, done, options) {
  5474. * //animation
  5475. * done();
  5476. * }
  5477. * }
  5478. * });
  5479. * ```
  5480. *
  5481. * @param {DOMElement} element the element which the CSS styles will be applied to
  5482. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5483. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5484. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5485. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5486. * (Note that if no animation is detected then this value will not be applied to the element.)
  5487. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5488. * The object can have the following properties:
  5489. *
  5490. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5491. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5492. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5493. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5494. *
  5495. * @return {Promise} the animation callback promise
  5496. */
  5497. animate: function(element, from, to, className, options) {
  5498. options = prepareAnimateOptions(options);
  5499. options.from = options.from ? extend(options.from, from) : from;
  5500. options.to = options.to ? extend(options.to, to) : to;
  5501. className = className || 'ng-inline-animate';
  5502. options.tempClasses = mergeClasses(options.tempClasses, className);
  5503. return $$animateQueue.push(element, 'animate', options);
  5504. }
  5505. };
  5506. }];
  5507. }];
  5508. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5509. this.$get = ['$$rAF', function($$rAF) {
  5510. var waitQueue = [];
  5511. function waitForTick(fn) {
  5512. waitQueue.push(fn);
  5513. if (waitQueue.length > 1) return;
  5514. $$rAF(function() {
  5515. for (var i = 0; i < waitQueue.length; i++) {
  5516. waitQueue[i]();
  5517. }
  5518. waitQueue = [];
  5519. });
  5520. }
  5521. return function() {
  5522. var passed = false;
  5523. waitForTick(function() {
  5524. passed = true;
  5525. });
  5526. return function(callback) {
  5527. if (passed) {
  5528. callback();
  5529. } else {
  5530. waitForTick(callback);
  5531. }
  5532. };
  5533. };
  5534. }];
  5535. };
  5536. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5537. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5538. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5539. var INITIAL_STATE = 0;
  5540. var DONE_PENDING_STATE = 1;
  5541. var DONE_COMPLETE_STATE = 2;
  5542. AnimateRunner.chain = function(chain, callback) {
  5543. var index = 0;
  5544. next();
  5545. function next() {
  5546. if (index === chain.length) {
  5547. callback(true);
  5548. return;
  5549. }
  5550. chain[index](function(response) {
  5551. if (response === false) {
  5552. callback(false);
  5553. return;
  5554. }
  5555. index++;
  5556. next();
  5557. });
  5558. }
  5559. };
  5560. AnimateRunner.all = function(runners, callback) {
  5561. var count = 0;
  5562. var status = true;
  5563. forEach(runners, function(runner) {
  5564. runner.done(onProgress);
  5565. });
  5566. function onProgress(response) {
  5567. status = status && response;
  5568. if (++count === runners.length) {
  5569. callback(status);
  5570. }
  5571. }
  5572. };
  5573. function AnimateRunner(host) {
  5574. this.setHost(host);
  5575. var rafTick = $$animateAsyncRun();
  5576. var timeoutTick = function(fn) {
  5577. $timeout(fn, 0, false);
  5578. };
  5579. this._doneCallbacks = [];
  5580. this._tick = function(fn) {
  5581. if ($$isDocumentHidden()) {
  5582. timeoutTick(fn);
  5583. } else {
  5584. rafTick(fn);
  5585. }
  5586. };
  5587. this._state = 0;
  5588. }
  5589. AnimateRunner.prototype = {
  5590. setHost: function(host) {
  5591. this.host = host || {};
  5592. },
  5593. done: function(fn) {
  5594. if (this._state === DONE_COMPLETE_STATE) {
  5595. fn();
  5596. } else {
  5597. this._doneCallbacks.push(fn);
  5598. }
  5599. },
  5600. progress: noop,
  5601. getPromise: function() {
  5602. if (!this.promise) {
  5603. var self = this;
  5604. this.promise = $q(function(resolve, reject) {
  5605. self.done(function(status) {
  5606. if (status === false) {
  5607. reject();
  5608. } else {
  5609. resolve();
  5610. }
  5611. });
  5612. });
  5613. }
  5614. return this.promise;
  5615. },
  5616. then: function(resolveHandler, rejectHandler) {
  5617. return this.getPromise().then(resolveHandler, rejectHandler);
  5618. },
  5619. 'catch': function(handler) {
  5620. return this.getPromise()['catch'](handler);
  5621. },
  5622. 'finally': function(handler) {
  5623. return this.getPromise()['finally'](handler);
  5624. },
  5625. pause: function() {
  5626. if (this.host.pause) {
  5627. this.host.pause();
  5628. }
  5629. },
  5630. resume: function() {
  5631. if (this.host.resume) {
  5632. this.host.resume();
  5633. }
  5634. },
  5635. end: function() {
  5636. if (this.host.end) {
  5637. this.host.end();
  5638. }
  5639. this._resolve(true);
  5640. },
  5641. cancel: function() {
  5642. if (this.host.cancel) {
  5643. this.host.cancel();
  5644. }
  5645. this._resolve(false);
  5646. },
  5647. complete: function(response) {
  5648. var self = this;
  5649. if (self._state === INITIAL_STATE) {
  5650. self._state = DONE_PENDING_STATE;
  5651. self._tick(function() {
  5652. self._resolve(response);
  5653. });
  5654. }
  5655. },
  5656. _resolve: function(response) {
  5657. if (this._state !== DONE_COMPLETE_STATE) {
  5658. forEach(this._doneCallbacks, function(fn) {
  5659. fn(response);
  5660. });
  5661. this._doneCallbacks.length = 0;
  5662. this._state = DONE_COMPLETE_STATE;
  5663. }
  5664. }
  5665. };
  5666. return AnimateRunner;
  5667. }];
  5668. };
  5669. /* exported $CoreAnimateCssProvider */
  5670. /**
  5671. * @ngdoc service
  5672. * @name $animateCss
  5673. * @kind object
  5674. * @this
  5675. *
  5676. * @description
  5677. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5678. * then the `$animateCss` service will actually perform animations.
  5679. *
  5680. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5681. */
  5682. var $CoreAnimateCssProvider = function() {
  5683. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5684. return function(element, initialOptions) {
  5685. // all of the animation functions should create
  5686. // a copy of the options data, however, if a
  5687. // parent service has already created a copy then
  5688. // we should stick to using that
  5689. var options = initialOptions || {};
  5690. if (!options.$$prepared) {
  5691. options = copy(options);
  5692. }
  5693. // there is no point in applying the styles since
  5694. // there is no animation that goes on at all in
  5695. // this version of $animateCss.
  5696. if (options.cleanupStyles) {
  5697. options.from = options.to = null;
  5698. }
  5699. if (options.from) {
  5700. element.css(options.from);
  5701. options.from = null;
  5702. }
  5703. var closed, runner = new $$AnimateRunner();
  5704. return {
  5705. start: run,
  5706. end: run
  5707. };
  5708. function run() {
  5709. $$rAF(function() {
  5710. applyAnimationContents();
  5711. if (!closed) {
  5712. runner.complete();
  5713. }
  5714. closed = true;
  5715. });
  5716. return runner;
  5717. }
  5718. function applyAnimationContents() {
  5719. if (options.addClass) {
  5720. element.addClass(options.addClass);
  5721. options.addClass = null;
  5722. }
  5723. if (options.removeClass) {
  5724. element.removeClass(options.removeClass);
  5725. options.removeClass = null;
  5726. }
  5727. if (options.to) {
  5728. element.css(options.to);
  5729. options.to = null;
  5730. }
  5731. }
  5732. };
  5733. }];
  5734. };
  5735. /* global stripHash: true */
  5736. /**
  5737. * ! This is a private undocumented service !
  5738. *
  5739. * @name $browser
  5740. * @requires $log
  5741. * @description
  5742. * This object has two goals:
  5743. *
  5744. * - hide all the global state in the browser caused by the window object
  5745. * - abstract away all the browser specific features and inconsistencies
  5746. *
  5747. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5748. * service, which can be used for convenient testing of the application without the interaction with
  5749. * the real browser apis.
  5750. */
  5751. /**
  5752. * @param {object} window The global window object.
  5753. * @param {object} document jQuery wrapped document.
  5754. * @param {object} $log window.console or an object with the same interface.
  5755. * @param {object} $sniffer $sniffer service
  5756. */
  5757. function Browser(window, document, $log, $sniffer) {
  5758. var self = this,
  5759. location = window.location,
  5760. history = window.history,
  5761. setTimeout = window.setTimeout,
  5762. clearTimeout = window.clearTimeout,
  5763. pendingDeferIds = {};
  5764. self.isMock = false;
  5765. var outstandingRequestCount = 0;
  5766. var outstandingRequestCallbacks = [];
  5767. // TODO(vojta): remove this temporary api
  5768. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5769. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5770. /**
  5771. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5772. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5773. */
  5774. function completeOutstandingRequest(fn) {
  5775. try {
  5776. fn.apply(null, sliceArgs(arguments, 1));
  5777. } finally {
  5778. outstandingRequestCount--;
  5779. if (outstandingRequestCount === 0) {
  5780. while (outstandingRequestCallbacks.length) {
  5781. try {
  5782. outstandingRequestCallbacks.pop()();
  5783. } catch (e) {
  5784. $log.error(e);
  5785. }
  5786. }
  5787. }
  5788. }
  5789. }
  5790. function getHash(url) {
  5791. var index = url.indexOf('#');
  5792. return index === -1 ? '' : url.substr(index);
  5793. }
  5794. /**
  5795. * @private
  5796. * TODO(vojta): prefix this method with $$ ?
  5797. * @param {function()} callback Function that will be called when no outstanding request
  5798. */
  5799. self.notifyWhenNoOutstandingRequests = function(callback) {
  5800. if (outstandingRequestCount === 0) {
  5801. callback();
  5802. } else {
  5803. outstandingRequestCallbacks.push(callback);
  5804. }
  5805. };
  5806. //////////////////////////////////////////////////////////////
  5807. // URL API
  5808. //////////////////////////////////////////////////////////////
  5809. var cachedState, lastHistoryState,
  5810. lastBrowserUrl = location.href,
  5811. baseElement = document.find('base'),
  5812. pendingLocation = null,
  5813. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5814. try {
  5815. return history.state;
  5816. } catch (e) {
  5817. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5818. }
  5819. };
  5820. cacheState();
  5821. /**
  5822. * @name $browser#url
  5823. *
  5824. * @description
  5825. * GETTER:
  5826. * Without any argument, this method just returns current value of location.href.
  5827. *
  5828. * SETTER:
  5829. * With at least one argument, this method sets url to new value.
  5830. * If html5 history api supported, pushState/replaceState is used, otherwise
  5831. * location.href/location.replace is used.
  5832. * Returns its own instance to allow chaining
  5833. *
  5834. * NOTE: this api is intended for use only by the $location service. Please use the
  5835. * {@link ng.$location $location service} to change url.
  5836. *
  5837. * @param {string} url New url (when used as setter)
  5838. * @param {boolean=} replace Should new url replace current history record?
  5839. * @param {object=} state object to use with pushState/replaceState
  5840. */
  5841. self.url = function(url, replace, state) {
  5842. // In modern browsers `history.state` is `null` by default; treating it separately
  5843. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5844. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5845. if (isUndefined(state)) {
  5846. state = null;
  5847. }
  5848. // Android Browser BFCache causes location, history reference to become stale.
  5849. if (location !== window.location) location = window.location;
  5850. if (history !== window.history) history = window.history;
  5851. // setter
  5852. if (url) {
  5853. var sameState = lastHistoryState === state;
  5854. // Don't change anything if previous and current URLs and states match. This also prevents
  5855. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5856. // See https://github.com/angular/angular.js/commit/ffb2701
  5857. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5858. return self;
  5859. }
  5860. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5861. lastBrowserUrl = url;
  5862. lastHistoryState = state;
  5863. // Don't use history API if only the hash changed
  5864. // due to a bug in IE10/IE11 which leads
  5865. // to not firing a `hashchange` nor `popstate` event
  5866. // in some cases (see #9143).
  5867. if ($sniffer.history && (!sameBase || !sameState)) {
  5868. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5869. cacheState();
  5870. } else {
  5871. if (!sameBase) {
  5872. pendingLocation = url;
  5873. }
  5874. if (replace) {
  5875. location.replace(url);
  5876. } else if (!sameBase) {
  5877. location.href = url;
  5878. } else {
  5879. location.hash = getHash(url);
  5880. }
  5881. if (location.href !== url) {
  5882. pendingLocation = url;
  5883. }
  5884. }
  5885. if (pendingLocation) {
  5886. pendingLocation = url;
  5887. }
  5888. return self;
  5889. // getter
  5890. } else {
  5891. // - pendingLocation is needed as browsers don't allow to read out
  5892. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5893. // https://openradar.appspot.com/22186109).
  5894. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5895. return pendingLocation || location.href.replace(/%27/g,'\'');
  5896. }
  5897. };
  5898. /**
  5899. * @name $browser#state
  5900. *
  5901. * @description
  5902. * This method is a getter.
  5903. *
  5904. * Return history.state or null if history.state is undefined.
  5905. *
  5906. * @returns {object} state
  5907. */
  5908. self.state = function() {
  5909. return cachedState;
  5910. };
  5911. var urlChangeListeners = [],
  5912. urlChangeInit = false;
  5913. function cacheStateAndFireUrlChange() {
  5914. pendingLocation = null;
  5915. fireStateOrUrlChange();
  5916. }
  5917. // This variable should be used *only* inside the cacheState function.
  5918. var lastCachedState = null;
  5919. function cacheState() {
  5920. // This should be the only place in $browser where `history.state` is read.
  5921. cachedState = getCurrentState();
  5922. cachedState = isUndefined(cachedState) ? null : cachedState;
  5923. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5924. if (equals(cachedState, lastCachedState)) {
  5925. cachedState = lastCachedState;
  5926. }
  5927. lastCachedState = cachedState;
  5928. lastHistoryState = cachedState;
  5929. }
  5930. function fireStateOrUrlChange() {
  5931. var prevLastHistoryState = lastHistoryState;
  5932. cacheState();
  5933. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5934. return;
  5935. }
  5936. lastBrowserUrl = self.url();
  5937. lastHistoryState = cachedState;
  5938. forEach(urlChangeListeners, function(listener) {
  5939. listener(self.url(), cachedState);
  5940. });
  5941. }
  5942. /**
  5943. * @name $browser#onUrlChange
  5944. *
  5945. * @description
  5946. * Register callback function that will be called, when url changes.
  5947. *
  5948. * It's only called when the url is changed from outside of AngularJS:
  5949. * - user types different url into address bar
  5950. * - user clicks on history (forward/back) button
  5951. * - user clicks on a link
  5952. *
  5953. * It's not called when url is changed by $browser.url() method
  5954. *
  5955. * The listener gets called with new url as parameter.
  5956. *
  5957. * NOTE: this api is intended for use only by the $location service. Please use the
  5958. * {@link ng.$location $location service} to monitor url changes in AngularJS apps.
  5959. *
  5960. * @param {function(string)} listener Listener function to be called when url changes.
  5961. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5962. */
  5963. self.onUrlChange = function(callback) {
  5964. // TODO(vojta): refactor to use node's syntax for events
  5965. if (!urlChangeInit) {
  5966. // We listen on both (hashchange/popstate) when available, as some browsers don't
  5967. // fire popstate when user changes the address bar and don't fire hashchange when url
  5968. // changed by push/replaceState
  5969. // html5 history api - popstate event
  5970. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5971. // hashchange event
  5972. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5973. urlChangeInit = true;
  5974. }
  5975. urlChangeListeners.push(callback);
  5976. return callback;
  5977. };
  5978. /**
  5979. * @private
  5980. * Remove popstate and hashchange handler from window.
  5981. *
  5982. * NOTE: this api is intended for use only by $rootScope.
  5983. */
  5984. self.$$applicationDestroyed = function() {
  5985. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5986. };
  5987. /**
  5988. * Checks whether the url has changed outside of AngularJS.
  5989. * Needs to be exported to be able to check for changes that have been done in sync,
  5990. * as hashchange/popstate events fire in async.
  5991. */
  5992. self.$$checkUrlChange = fireStateOrUrlChange;
  5993. //////////////////////////////////////////////////////////////
  5994. // Misc API
  5995. //////////////////////////////////////////////////////////////
  5996. /**
  5997. * @name $browser#baseHref
  5998. *
  5999. * @description
  6000. * Returns current <base href>
  6001. * (always relative - without domain)
  6002. *
  6003. * @returns {string} The current base href
  6004. */
  6005. self.baseHref = function() {
  6006. var href = baseElement.attr('href');
  6007. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  6008. };
  6009. /**
  6010. * @name $browser#defer
  6011. * @param {function()} fn A function, who's execution should be deferred.
  6012. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  6013. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  6014. *
  6015. * @description
  6016. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  6017. *
  6018. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  6019. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  6020. * via `$browser.defer.flush()`.
  6021. *
  6022. */
  6023. self.defer = function(fn, delay) {
  6024. var timeoutId;
  6025. outstandingRequestCount++;
  6026. timeoutId = setTimeout(function() {
  6027. delete pendingDeferIds[timeoutId];
  6028. completeOutstandingRequest(fn);
  6029. }, delay || 0);
  6030. pendingDeferIds[timeoutId] = true;
  6031. return timeoutId;
  6032. };
  6033. /**
  6034. * @name $browser#defer.cancel
  6035. *
  6036. * @description
  6037. * Cancels a deferred task identified with `deferId`.
  6038. *
  6039. * @param {*} deferId Token returned by the `$browser.defer` function.
  6040. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  6041. * canceled.
  6042. */
  6043. self.defer.cancel = function(deferId) {
  6044. if (pendingDeferIds[deferId]) {
  6045. delete pendingDeferIds[deferId];
  6046. clearTimeout(deferId);
  6047. completeOutstandingRequest(noop);
  6048. return true;
  6049. }
  6050. return false;
  6051. };
  6052. }
  6053. /** @this */
  6054. function $BrowserProvider() {
  6055. this.$get = ['$window', '$log', '$sniffer', '$document',
  6056. function($window, $log, $sniffer, $document) {
  6057. return new Browser($window, $document, $log, $sniffer);
  6058. }];
  6059. }
  6060. /**
  6061. * @ngdoc service
  6062. * @name $cacheFactory
  6063. * @this
  6064. *
  6065. * @description
  6066. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  6067. * them.
  6068. *
  6069. * ```js
  6070. *
  6071. * var cache = $cacheFactory('cacheId');
  6072. * expect($cacheFactory.get('cacheId')).toBe(cache);
  6073. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  6074. *
  6075. * cache.put("key", "value");
  6076. * cache.put("another key", "another value");
  6077. *
  6078. * // We've specified no options on creation
  6079. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  6080. *
  6081. * ```
  6082. *
  6083. *
  6084. * @param {string} cacheId Name or id of the newly created cache.
  6085. * @param {object=} options Options object that specifies the cache behavior. Properties:
  6086. *
  6087. * - `{number=}` `capacity` — turns the cache into LRU cache.
  6088. *
  6089. * @returns {object} Newly created cache object with the following set of methods:
  6090. *
  6091. * - `{object}` `info()` — Returns id, size, and options of cache.
  6092. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  6093. * it.
  6094. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  6095. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  6096. * - `{void}` `removeAll()` — Removes all cached values.
  6097. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  6098. *
  6099. * @example
  6100. <example module="cacheExampleApp" name="cache-factory">
  6101. <file name="index.html">
  6102. <div ng-controller="CacheController">
  6103. <input ng-model="newCacheKey" placeholder="Key">
  6104. <input ng-model="newCacheValue" placeholder="Value">
  6105. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  6106. <p ng-if="keys.length">Cached Values</p>
  6107. <div ng-repeat="key in keys">
  6108. <span ng-bind="key"></span>
  6109. <span>: </span>
  6110. <b ng-bind="cache.get(key)"></b>
  6111. </div>
  6112. <p>Cache Info</p>
  6113. <div ng-repeat="(key, value) in cache.info()">
  6114. <span ng-bind="key"></span>
  6115. <span>: </span>
  6116. <b ng-bind="value"></b>
  6117. </div>
  6118. </div>
  6119. </file>
  6120. <file name="script.js">
  6121. angular.module('cacheExampleApp', []).
  6122. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  6123. $scope.keys = [];
  6124. $scope.cache = $cacheFactory('cacheId');
  6125. $scope.put = function(key, value) {
  6126. if (angular.isUndefined($scope.cache.get(key))) {
  6127. $scope.keys.push(key);
  6128. }
  6129. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  6130. };
  6131. }]);
  6132. </file>
  6133. <file name="style.css">
  6134. p {
  6135. margin: 10px 0 3px;
  6136. }
  6137. </file>
  6138. </example>
  6139. */
  6140. function $CacheFactoryProvider() {
  6141. this.$get = function() {
  6142. var caches = {};
  6143. function cacheFactory(cacheId, options) {
  6144. if (cacheId in caches) {
  6145. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6146. }
  6147. var size = 0,
  6148. stats = extend({}, options, {id: cacheId}),
  6149. data = createMap(),
  6150. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6151. lruHash = createMap(),
  6152. freshEnd = null,
  6153. staleEnd = null;
  6154. /**
  6155. * @ngdoc type
  6156. * @name $cacheFactory.Cache
  6157. *
  6158. * @description
  6159. * A cache object used to store and retrieve data, primarily used by
  6160. * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
  6161. * directive to cache templates and other data.
  6162. *
  6163. * ```js
  6164. * angular.module('superCache')
  6165. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6166. * return $cacheFactory('super-cache');
  6167. * }]);
  6168. * ```
  6169. *
  6170. * Example test:
  6171. *
  6172. * ```js
  6173. * it('should behave like a cache', inject(function(superCache) {
  6174. * superCache.put('key', 'value');
  6175. * superCache.put('another key', 'another value');
  6176. *
  6177. * expect(superCache.info()).toEqual({
  6178. * id: 'super-cache',
  6179. * size: 2
  6180. * });
  6181. *
  6182. * superCache.remove('another key');
  6183. * expect(superCache.get('another key')).toBeUndefined();
  6184. *
  6185. * superCache.removeAll();
  6186. * expect(superCache.info()).toEqual({
  6187. * id: 'super-cache',
  6188. * size: 0
  6189. * });
  6190. * }));
  6191. * ```
  6192. */
  6193. return (caches[cacheId] = {
  6194. /**
  6195. * @ngdoc method
  6196. * @name $cacheFactory.Cache#put
  6197. * @kind function
  6198. *
  6199. * @description
  6200. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6201. * retrieved later, and incrementing the size of the cache if the key was not already
  6202. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6203. * entries from the set.
  6204. *
  6205. * It will not insert undefined values into the cache.
  6206. *
  6207. * @param {string} key the key under which the cached data is stored.
  6208. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6209. * will not be stored.
  6210. * @returns {*} the value stored.
  6211. */
  6212. put: function(key, value) {
  6213. if (isUndefined(value)) return;
  6214. if (capacity < Number.MAX_VALUE) {
  6215. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6216. refresh(lruEntry);
  6217. }
  6218. if (!(key in data)) size++;
  6219. data[key] = value;
  6220. if (size > capacity) {
  6221. this.remove(staleEnd.key);
  6222. }
  6223. return value;
  6224. },
  6225. /**
  6226. * @ngdoc method
  6227. * @name $cacheFactory.Cache#get
  6228. * @kind function
  6229. *
  6230. * @description
  6231. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6232. *
  6233. * @param {string} key the key of the data to be retrieved
  6234. * @returns {*} the value stored.
  6235. */
  6236. get: function(key) {
  6237. if (capacity < Number.MAX_VALUE) {
  6238. var lruEntry = lruHash[key];
  6239. if (!lruEntry) return;
  6240. refresh(lruEntry);
  6241. }
  6242. return data[key];
  6243. },
  6244. /**
  6245. * @ngdoc method
  6246. * @name $cacheFactory.Cache#remove
  6247. * @kind function
  6248. *
  6249. * @description
  6250. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6251. *
  6252. * @param {string} key the key of the entry to be removed
  6253. */
  6254. remove: function(key) {
  6255. if (capacity < Number.MAX_VALUE) {
  6256. var lruEntry = lruHash[key];
  6257. if (!lruEntry) return;
  6258. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6259. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6260. link(lruEntry.n,lruEntry.p);
  6261. delete lruHash[key];
  6262. }
  6263. if (!(key in data)) return;
  6264. delete data[key];
  6265. size--;
  6266. },
  6267. /**
  6268. * @ngdoc method
  6269. * @name $cacheFactory.Cache#removeAll
  6270. * @kind function
  6271. *
  6272. * @description
  6273. * Clears the cache object of any entries.
  6274. */
  6275. removeAll: function() {
  6276. data = createMap();
  6277. size = 0;
  6278. lruHash = createMap();
  6279. freshEnd = staleEnd = null;
  6280. },
  6281. /**
  6282. * @ngdoc method
  6283. * @name $cacheFactory.Cache#destroy
  6284. * @kind function
  6285. *
  6286. * @description
  6287. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6288. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6289. */
  6290. destroy: function() {
  6291. data = null;
  6292. stats = null;
  6293. lruHash = null;
  6294. delete caches[cacheId];
  6295. },
  6296. /**
  6297. * @ngdoc method
  6298. * @name $cacheFactory.Cache#info
  6299. * @kind function
  6300. *
  6301. * @description
  6302. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6303. *
  6304. * @returns {object} an object with the following properties:
  6305. * <ul>
  6306. * <li>**id**: the id of the cache instance</li>
  6307. * <li>**size**: the number of entries kept in the cache instance</li>
  6308. * <li>**...**: any additional properties from the options object when creating the
  6309. * cache.</li>
  6310. * </ul>
  6311. */
  6312. info: function() {
  6313. return extend({}, stats, {size: size});
  6314. }
  6315. });
  6316. /**
  6317. * makes the `entry` the freshEnd of the LRU linked list
  6318. */
  6319. function refresh(entry) {
  6320. if (entry !== freshEnd) {
  6321. if (!staleEnd) {
  6322. staleEnd = entry;
  6323. } else if (staleEnd === entry) {
  6324. staleEnd = entry.n;
  6325. }
  6326. link(entry.n, entry.p);
  6327. link(entry, freshEnd);
  6328. freshEnd = entry;
  6329. freshEnd.n = null;
  6330. }
  6331. }
  6332. /**
  6333. * bidirectionally links two entries of the LRU linked list
  6334. */
  6335. function link(nextEntry, prevEntry) {
  6336. if (nextEntry !== prevEntry) {
  6337. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6338. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6339. }
  6340. }
  6341. }
  6342. /**
  6343. * @ngdoc method
  6344. * @name $cacheFactory#info
  6345. *
  6346. * @description
  6347. * Get information about all the caches that have been created
  6348. *
  6349. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6350. */
  6351. cacheFactory.info = function() {
  6352. var info = {};
  6353. forEach(caches, function(cache, cacheId) {
  6354. info[cacheId] = cache.info();
  6355. });
  6356. return info;
  6357. };
  6358. /**
  6359. * @ngdoc method
  6360. * @name $cacheFactory#get
  6361. *
  6362. * @description
  6363. * Get access to a cache object by the `cacheId` used when it was created.
  6364. *
  6365. * @param {string} cacheId Name or id of a cache to access.
  6366. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6367. */
  6368. cacheFactory.get = function(cacheId) {
  6369. return caches[cacheId];
  6370. };
  6371. return cacheFactory;
  6372. };
  6373. }
  6374. /**
  6375. * @ngdoc service
  6376. * @name $templateCache
  6377. * @this
  6378. *
  6379. * @description
  6380. * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
  6381. * {@link ng.$cacheFactory $cacheFactory}.
  6382. *
  6383. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6384. * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
  6385. * or by consuming the `$templateCache` service directly.
  6386. *
  6387. * Adding via the `script` tag:
  6388. *
  6389. * ```html
  6390. * <script type="text/ng-template" id="templateId.html">
  6391. * <p>This is the content of the template</p>
  6392. * </script>
  6393. * ```
  6394. *
  6395. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6396. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
  6397. * element with {@link ngApp} attribute), otherwise the template will be ignored.
  6398. *
  6399. * Adding via the `$templateCache` service:
  6400. *
  6401. * ```js
  6402. * var myApp = angular.module('myApp', []);
  6403. * myApp.run(function($templateCache) {
  6404. * $templateCache.put('templateId.html', 'This is the content of the template');
  6405. * });
  6406. * ```
  6407. *
  6408. * To retrieve the template later, simply use it in your component:
  6409. * ```js
  6410. * myApp.component('myComponent', {
  6411. * templateUrl: 'templateId.html'
  6412. * });
  6413. * ```
  6414. *
  6415. * or get it via the `$templateCache` service:
  6416. * ```js
  6417. * $templateCache.get('templateId.html')
  6418. * ```
  6419. *
  6420. */
  6421. function $TemplateCacheProvider() {
  6422. this.$get = ['$cacheFactory', function($cacheFactory) {
  6423. return $cacheFactory('templates');
  6424. }];
  6425. }
  6426. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6427. * Any commits to this file should be reviewed with security in mind. *
  6428. * Changes to this file can potentially create security vulnerabilities. *
  6429. * An approval from 2 Core members with history of modifying *
  6430. * this file is required. *
  6431. * *
  6432. * Does the change somehow allow for arbitrary javascript to be executed? *
  6433. * Or allows for someone to change the prototype of built-in objects? *
  6434. * Or gives undesired access to variables like document or window? *
  6435. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6436. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6437. *
  6438. * DOM-related variables:
  6439. *
  6440. * - "node" - DOM Node
  6441. * - "element" - DOM Element or Node
  6442. * - "$node" or "$element" - jqLite-wrapped node or element
  6443. *
  6444. *
  6445. * Compiler related stuff:
  6446. *
  6447. * - "linkFn" - linking fn of a single directive
  6448. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6449. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6450. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6451. */
  6452. /**
  6453. * @ngdoc service
  6454. * @name $compile
  6455. * @kind function
  6456. *
  6457. * @description
  6458. * Compiles an HTML string or DOM into a template and produces a template function, which
  6459. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6460. *
  6461. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6462. * {@link ng.$compileProvider#directive directives}.
  6463. *
  6464. * <div class="alert alert-warning">
  6465. * **Note:** This document is an in-depth reference of all directive options.
  6466. * For a gentle introduction to directives with examples of common use cases,
  6467. * see the {@link guide/directive directive guide}.
  6468. * </div>
  6469. *
  6470. * ## Comprehensive Directive API
  6471. *
  6472. * There are many different options for a directive.
  6473. *
  6474. * The difference resides in the return value of the factory function.
  6475. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6476. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6477. * the default values).
  6478. *
  6479. * <div class="alert alert-success">
  6480. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6481. * </div>
  6482. *
  6483. * Here's an example directive declared with a Directive Definition Object:
  6484. *
  6485. * ```js
  6486. * var myModule = angular.module(...);
  6487. *
  6488. * myModule.directive('directiveName', function factory(injectables) {
  6489. * var directiveDefinitionObject = {
  6490. * {@link $compile#-priority- priority}: 0,
  6491. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6492. * // or
  6493. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6494. * {@link $compile#-transclude- transclude}: false,
  6495. * {@link $compile#-restrict- restrict}: 'A',
  6496. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6497. * {@link $compile#-scope- scope}: false,
  6498. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6499. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6500. * {@link $compile#-bindtocontroller- bindToController}: false,
  6501. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6502. * {@link $compile#-multielement- multiElement}: false,
  6503. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6504. * return {
  6505. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6506. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6507. * }
  6508. * // or
  6509. * // return function postLink( ... ) { ... }
  6510. * },
  6511. * // or
  6512. * // {@link $compile#-link- link}: {
  6513. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6514. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6515. * // }
  6516. * // or
  6517. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6518. * };
  6519. * return directiveDefinitionObject;
  6520. * });
  6521. * ```
  6522. *
  6523. * <div class="alert alert-warning">
  6524. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6525. * </div>
  6526. *
  6527. * Therefore the above can be simplified as:
  6528. *
  6529. * ```js
  6530. * var myModule = angular.module(...);
  6531. *
  6532. * myModule.directive('directiveName', function factory(injectables) {
  6533. * var directiveDefinitionObject = {
  6534. * link: function postLink(scope, iElement, iAttrs) { ... }
  6535. * };
  6536. * return directiveDefinitionObject;
  6537. * // or
  6538. * // return function postLink(scope, iElement, iAttrs) { ... }
  6539. * });
  6540. * ```
  6541. *
  6542. * ### Life-cycle hooks
  6543. * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the
  6544. * directive:
  6545. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6546. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6547. * this element). This is a good place to put initialization code for your controller.
  6548. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6549. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6550. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6551. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6552. * also be called when your bindings are initialized.
  6553. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6554. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6555. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6556. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6557. * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6558. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6559. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6560. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6561. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6562. * components will have their `$onDestroy()` hook called before child components.
  6563. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6564. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6565. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6566. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6567. * suspended until that occurs.
  6568. *
  6569. * #### Comparison with life-cycle hooks in the new Angular
  6570. * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are
  6571. * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:
  6572. *
  6573. * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.
  6574. * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6575. * In Angular you can only define hooks on the prototype of the Component class.
  6576. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to
  6577. * `ngDoCheck` in Angular.
  6578. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6579. * propagated throughout the application.
  6580. * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6581. * error or do nothing depending upon the state of `enableProdMode()`.
  6582. *
  6583. * #### Life-cycle hook examples
  6584. *
  6585. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6586. * has not changed.
  6587. *
  6588. * <example name="doCheckDateExample" module="do-check-module">
  6589. * <file name="app.js">
  6590. * angular.module('do-check-module', [])
  6591. * .component('app', {
  6592. * template:
  6593. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6594. * 'Date: {{ $ctrl.date }}' +
  6595. * '<test date="$ctrl.date"></test>',
  6596. * controller: function() {
  6597. * this.date = new Date();
  6598. * this.month = this.date.getMonth();
  6599. * this.updateDate = function() {
  6600. * this.date.setMonth(this.month);
  6601. * };
  6602. * }
  6603. * })
  6604. * .component('test', {
  6605. * bindings: { date: '<' },
  6606. * template:
  6607. * '<pre>{{ $ctrl.log | json }}</pre>',
  6608. * controller: function() {
  6609. * var previousValue;
  6610. * this.log = [];
  6611. * this.$doCheck = function() {
  6612. * var currentValue = this.date && this.date.valueOf();
  6613. * if (previousValue !== currentValue) {
  6614. * this.log.push('doCheck: date mutated: ' + this.date);
  6615. * previousValue = currentValue;
  6616. * }
  6617. * };
  6618. * }
  6619. * });
  6620. * </file>
  6621. * <file name="index.html">
  6622. * <app></app>
  6623. * </file>
  6624. * </example>
  6625. *
  6626. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6627. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6628. * arrays or objects can have a negative impact on your application performance)
  6629. *
  6630. * <example name="doCheckArrayExample" module="do-check-module">
  6631. * <file name="index.html">
  6632. * <div ng-init="items = []">
  6633. * <button ng-click="items.push(items.length)">Add Item</button>
  6634. * <button ng-click="items = []">Reset Items</button>
  6635. * <pre>{{ items }}</pre>
  6636. * <test items="items"></test>
  6637. * </div>
  6638. * </file>
  6639. * <file name="app.js">
  6640. * angular.module('do-check-module', [])
  6641. * .component('test', {
  6642. * bindings: { items: '<' },
  6643. * template:
  6644. * '<pre>{{ $ctrl.log | json }}</pre>',
  6645. * controller: function() {
  6646. * this.log = [];
  6647. *
  6648. * this.$doCheck = function() {
  6649. * if (this.items_ref !== this.items) {
  6650. * this.log.push('doCheck: items changed');
  6651. * this.items_ref = this.items;
  6652. * }
  6653. * if (!angular.equals(this.items_clone, this.items)) {
  6654. * this.log.push('doCheck: items mutated');
  6655. * this.items_clone = angular.copy(this.items);
  6656. * }
  6657. * };
  6658. * }
  6659. * });
  6660. * </file>
  6661. * </example>
  6662. *
  6663. *
  6664. * ### Directive Definition Object
  6665. *
  6666. * The directive definition object provides instructions to the {@link ng.$compile
  6667. * compiler}. The attributes are:
  6668. *
  6669. * #### `multiElement`
  6670. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6671. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6672. * together as the directive elements. It is recommended that this feature be used on directives
  6673. * which are not strictly behavioral (such as {@link ngClick}), and which
  6674. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6675. *
  6676. * #### `priority`
  6677. * When there are multiple directives defined on a single DOM element, sometimes it
  6678. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6679. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6680. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6681. * are also run in priority order, but post-link functions are run in reverse order. The order
  6682. * of directives with the same priority is undefined. The default priority is `0`.
  6683. *
  6684. * #### `terminal`
  6685. * If set to true then the current `priority` will be the last set of directives
  6686. * which will execute (any directives at the current priority will still execute
  6687. * as the order of execution on same `priority` is undefined). Note that expressions
  6688. * and other directives used in the directive's template will also be excluded from execution.
  6689. *
  6690. * #### `scope`
  6691. * The scope property can be `false`, `true`, or an object:
  6692. *
  6693. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6694. * parent's scope.
  6695. *
  6696. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6697. * the directive's element. If multiple directives on the same element request a new scope,
  6698. * only one new scope is created.
  6699. *
  6700. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6701. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6702. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6703. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6704. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6705. * to its children elements.
  6706. *
  6707. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6708. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6709. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6710. * is bound to the parent scope, via matching attributes on the directive's element:
  6711. *
  6712. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6713. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6714. * attribute name is assumed to be the same as the local name. Given `<my-component
  6715. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6716. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6717. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6718. * scope. The `name` is read from the parent scope (not the directive's scope).
  6719. *
  6720. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6721. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6722. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6723. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6724. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6725. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6726. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6727. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6728. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6729. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6730. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6731. * method is used for tracking changes, and the equality check is based on object identity.
  6732. * However, if an object literal or an array literal is passed as the binding expression, the
  6733. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6734. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6735. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6736. *
  6737. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6738. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6739. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6740. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6741. *
  6742. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6743. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6744. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6745. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6746. * two caveats:
  6747. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6748. * sets the same value. That means if your bound value is an object, changes to its properties
  6749. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6750. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6751. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6752. * to the value has changed. In most cases, this should not be of concern, but can be important
  6753. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6754. * If you now change a property of the object in your parent scope, the change will not be
  6755. * propagated to the isolated scope, because the identity of the object on the parent scope
  6756. * has not changed. Instead you must assign a new object.
  6757. *
  6758. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6759. * back to the parent. However, it does not make this completely impossible.
  6760. *
  6761. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6762. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6763. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6764. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6765. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6766. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6767. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6768. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6769. *
  6770. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6771. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6772. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6773. *
  6774. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6775. * * **child scope** + **no scope** => Both directives will share one single child scope
  6776. * * **child scope** + **child scope** => Both directives will share one single child scope
  6777. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6778. * its parent's scope
  6779. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6780. * be applied to the same element.
  6781. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6782. * cannot be applied to the same element.
  6783. *
  6784. *
  6785. * #### `bindToController`
  6786. * This property is used to bind scope properties directly to the controller. It can be either
  6787. * `true` or an object hash with the same format as the `scope` property.
  6788. *
  6789. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6790. * allow a component to have its properties bound to the controller, rather than to scope.
  6791. *
  6792. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6793. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6794. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6795. * initialized.
  6796. *
  6797. * <div class="alert alert-warning">
  6798. * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class
  6799. * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please
  6800. * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6801. * </div>
  6802. *
  6803. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6804. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6805. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6806. * scope (useful for component directives).
  6807. *
  6808. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6809. *
  6810. *
  6811. * #### `controller`
  6812. * Controller constructor function. The controller is instantiated before the
  6813. * pre-linking phase and can be accessed by other directives (see
  6814. * `require` attribute). This allows the directives to communicate with each other and augment
  6815. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6816. *
  6817. * * `$scope` - Current scope associated with the element
  6818. * * `$element` - Current element
  6819. * * `$attrs` - Current attributes object for the element
  6820. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6821. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6822. * * `scope`: (optional) override the scope.
  6823. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6824. * * `futureParentElement` (optional):
  6825. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6826. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6827. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6828. * and when the `cloneLinkingFn` is passed,
  6829. * as those elements need to created and cloned in a special way when they are defined outside their
  6830. * usual containers (e.g. like `<svg>`).
  6831. * * See also the `directive.templateNamespace` property.
  6832. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6833. * then the default transclusion is provided.
  6834. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6835. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6836. *
  6837. * #### `require`
  6838. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6839. * `require` property can be a string, an array or an object:
  6840. * * a **string** containing the name of the directive to pass to the linking function
  6841. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6842. * linking function will be an array of controllers in the same order as the names in the `require` property
  6843. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6844. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6845. * controllers.
  6846. *
  6847. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6848. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6849. * have been constructed but before `$onInit` is called.
  6850. * If the name of the required controller is the same as the local name (the key), the name can be
  6851. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6852. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6853. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6854. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6855. * controller, in which case error checking is skipped). The name can be prefixed with:
  6856. *
  6857. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6858. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6859. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6860. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6861. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6862. * `null` to the `link` fn if not found.
  6863. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6864. * `null` to the `link` fn if not found.
  6865. *
  6866. *
  6867. * #### `controllerAs`
  6868. * Identifier name for a reference to the controller in the directive's scope.
  6869. * This allows the controller to be referenced from the directive template. This is especially
  6870. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6871. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6872. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6873. *
  6874. *
  6875. * #### `restrict`
  6876. * String of subset of `EACM` which restricts the directive to a specific directive
  6877. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6878. *
  6879. * * `E` - Element name (default): `<my-directive></my-directive>`
  6880. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6881. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6882. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6883. *
  6884. *
  6885. * #### `templateNamespace`
  6886. * String representing the document type used by the markup in the template.
  6887. * AngularJS needs this information as those elements need to be created and cloned
  6888. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6889. *
  6890. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6891. * top-level elements such as `<svg>` or `<math>`.
  6892. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6893. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6894. *
  6895. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6896. *
  6897. * #### `template`
  6898. * HTML markup that may:
  6899. * * Replace the contents of the directive's element (default).
  6900. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6901. * * Wrap the contents of the directive's element (if `transclude` is true).
  6902. *
  6903. * Value may be:
  6904. *
  6905. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6906. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6907. * function api below) and returns a string value.
  6908. *
  6909. *
  6910. * #### `templateUrl`
  6911. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6912. *
  6913. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6914. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6915. * sibling and parent elements as though this element had not contained any directives.
  6916. *
  6917. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6918. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6919. * case when only one deeply nested directive has `templateUrl`.
  6920. *
  6921. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6922. *
  6923. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6924. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6925. * a string value representing the url. In either case, the template URL is passed through {@link
  6926. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6927. *
  6928. *
  6929. * #### `replace` (*DEPRECATED*)
  6930. *
  6931. * `replace` will be removed in next major release - i.e. v2.0).
  6932. *
  6933. * Specifies what the template should replace. Defaults to `false`.
  6934. *
  6935. * * `true` - the template will replace the directive's element.
  6936. * * `false` - the template will replace the contents of the directive's element.
  6937. *
  6938. * The replacement process migrates all of the attributes / classes from the old element to the new
  6939. * one. See the {@link guide/directive#template-expanding-directive
  6940. * Directives Guide} for an example.
  6941. *
  6942. * There are very few scenarios where element replacement is required for the application function,
  6943. * the main one being reusable custom components that are used within SVG contexts
  6944. * (because SVG doesn't work with custom elements in the DOM tree).
  6945. *
  6946. * #### `transclude`
  6947. * Extract the contents of the element where the directive appears and make it available to the directive.
  6948. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6949. * {@link $compile#transclusion Transclusion} section below.
  6950. *
  6951. *
  6952. * #### `compile`
  6953. *
  6954. * ```js
  6955. * function compile(tElement, tAttrs, transclude) { ... }
  6956. * ```
  6957. *
  6958. * The compile function deals with transforming the template DOM. Since most directives do not do
  6959. * template transformation, it is not used often. The compile function takes the following arguments:
  6960. *
  6961. * * `tElement` - template element - The element where the directive has been declared. It is
  6962. * safe to do template transformation on the element and child elements only.
  6963. *
  6964. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6965. * between all directive compile functions.
  6966. *
  6967. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6968. *
  6969. * <div class="alert alert-warning">
  6970. * **Note:** The template instance and the link instance may be different objects if the template has
  6971. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6972. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6973. * should be done in a linking function rather than in a compile function.
  6974. * </div>
  6975. * <div class="alert alert-warning">
  6976. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6977. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6978. * stack overflow errors.
  6979. *
  6980. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6981. * a directive's template instead of relying on automatic template compilation via `template` or
  6982. * `templateUrl` declaration or manual compilation inside the compile function.
  6983. * </div>
  6984. *
  6985. * <div class="alert alert-danger">
  6986. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6987. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6988. * to the link function instead.
  6989. * </div>
  6990. * A compile function can have a return value which can be either a function or an object.
  6991. *
  6992. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6993. * `link` property of the config object when the compile function is empty.
  6994. *
  6995. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6996. * control when a linking function should be called during the linking phase. See info about
  6997. * pre-linking and post-linking functions below.
  6998. *
  6999. *
  7000. * #### `link`
  7001. * This property is used only if the `compile` property is not defined.
  7002. *
  7003. * ```js
  7004. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  7005. * ```
  7006. *
  7007. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  7008. * executed after the template has been cloned. This is where most of the directive logic will be
  7009. * put.
  7010. *
  7011. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  7012. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  7013. *
  7014. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  7015. * manipulate the children of the element only in `postLink` function since the children have
  7016. * already been linked.
  7017. *
  7018. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  7019. * between all directive linking functions.
  7020. *
  7021. * * `controller` - the directive's required controller instance(s) - Instances are shared
  7022. * among all directives, which allows the directives to use the controllers as a communication
  7023. * channel. The exact value depends on the directive's `require` property:
  7024. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  7025. * * `string`: the controller instance
  7026. * * `array`: array of controller instances
  7027. *
  7028. * If a required controller cannot be found, and it is optional, the instance is `null`,
  7029. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  7030. *
  7031. * Note that you can also require the directive's own controller - it will be made available like
  7032. * any other controller.
  7033. *
  7034. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  7035. * This is the same as the `$transclude` parameter of directive controllers,
  7036. * see {@link ng.$compile#-controller- the controller section for details}.
  7037. * `function([scope], cloneLinkingFn, futureParentElement)`.
  7038. *
  7039. * #### Pre-linking function
  7040. *
  7041. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  7042. * compiler linking function will fail to locate the correct elements for linking.
  7043. *
  7044. * #### Post-linking function
  7045. *
  7046. * Executed after the child elements are linked.
  7047. *
  7048. * Note that child elements that contain `templateUrl` directives will not have been compiled
  7049. * and linked since they are waiting for their template to load asynchronously and their own
  7050. * compilation and linking has been suspended until that occurs.
  7051. *
  7052. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  7053. * for their async templates to be resolved.
  7054. *
  7055. *
  7056. * ### Transclusion
  7057. *
  7058. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  7059. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  7060. * scope from where they were taken.
  7061. *
  7062. * Transclusion is used (often with {@link ngTransclude}) to insert the
  7063. * original contents of a directive's element into a specified place in the template of the directive.
  7064. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  7065. * content has access to the properties on the scope from which it was taken, even if the directive
  7066. * has isolated scope.
  7067. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  7068. *
  7069. * This makes it possible for the widget to have private state for its template, while the transcluded
  7070. * content has access to its originating scope.
  7071. *
  7072. * <div class="alert alert-warning">
  7073. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  7074. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  7075. * Testing Transclusion Directives}.
  7076. * </div>
  7077. *
  7078. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  7079. * directive's element, the entire element or multiple parts of the element contents:
  7080. *
  7081. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  7082. * * `'element'` - transclude the whole of the directive's element including any directives on this
  7083. * element that defined at a lower priority than this directive. When used, the `template`
  7084. * property is ignored.
  7085. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  7086. *
  7087. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  7088. *
  7089. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  7090. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  7091. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  7092. *
  7093. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7094. *
  7095. * If the element selector is prefixed with a `?` then that slot is optional.
  7096. *
  7097. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  7098. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  7099. *
  7100. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  7101. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  7102. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  7103. * injectable into the directive's controller.
  7104. *
  7105. *
  7106. * #### Transclusion Functions
  7107. *
  7108. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  7109. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  7110. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  7111. *
  7112. * <div class="alert alert-info">
  7113. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  7114. * ngTransclude will deal with it for us.
  7115. * </div>
  7116. *
  7117. * If you want to manually control the insertion and removal of the transcluded content in your directive
  7118. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  7119. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  7120. *
  7121. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  7122. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  7123. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  7124. *
  7125. * <div class="alert alert-info">
  7126. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  7127. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  7128. * </div>
  7129. *
  7130. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  7131. * attach function**:
  7132. *
  7133. * ```js
  7134. * var transcludedContent, transclusionScope;
  7135. *
  7136. * $transclude(function(clone, scope) {
  7137. * element.append(clone);
  7138. * transcludedContent = clone;
  7139. * transclusionScope = scope;
  7140. * });
  7141. * ```
  7142. *
  7143. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  7144. * associated transclusion scope:
  7145. *
  7146. * ```js
  7147. * transcludedContent.remove();
  7148. * transclusionScope.$destroy();
  7149. * ```
  7150. *
  7151. * <div class="alert alert-info">
  7152. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7153. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7154. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7155. * </div>
  7156. *
  7157. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7158. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7159. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7160. *
  7161. *
  7162. * #### Transclusion Scopes
  7163. *
  7164. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7165. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7166. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7167. * was taken.
  7168. *
  7169. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7170. * like this:
  7171. *
  7172. * ```html
  7173. * <div ng-app>
  7174. * <div isolate>
  7175. * <div transclusion>
  7176. * </div>
  7177. * </div>
  7178. * </div>
  7179. * ```
  7180. *
  7181. * The `$parent` scope hierarchy will look like this:
  7182. *
  7183. ```
  7184. - $rootScope
  7185. - isolate
  7186. - transclusion
  7187. ```
  7188. *
  7189. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7190. *
  7191. ```
  7192. - $rootScope
  7193. - transclusion
  7194. - isolate
  7195. ```
  7196. *
  7197. *
  7198. * ### Attributes
  7199. *
  7200. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7201. * `link()` or `compile()` functions. It has a variety of uses.
  7202. *
  7203. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7204. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7205. * to the attributes.
  7206. *
  7207. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7208. * object which allows the directives to use the attributes object as inter directive
  7209. * communication.
  7210. *
  7211. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7212. * allowing other directives to read the interpolated value.
  7213. *
  7214. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7215. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7216. * the only way to easily get the actual value because during the linking phase the interpolation
  7217. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7218. *
  7219. * ```js
  7220. * function linkingFn(scope, elm, attrs, ctrl) {
  7221. * // get the attribute value
  7222. * console.log(attrs.ngModel);
  7223. *
  7224. * // change the attribute
  7225. * attrs.$set('ngModel', 'new value');
  7226. *
  7227. * // observe changes to interpolated attribute
  7228. * attrs.$observe('ngModel', function(value) {
  7229. * console.log('ngModel has changed value to ' + value);
  7230. * });
  7231. * }
  7232. * ```
  7233. *
  7234. * ## Example
  7235. *
  7236. * <div class="alert alert-warning">
  7237. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7238. * to illustrate how `$compile` works.
  7239. * </div>
  7240. *
  7241. <example module="compileExample" name="compile">
  7242. <file name="index.html">
  7243. <script>
  7244. angular.module('compileExample', [], function($compileProvider) {
  7245. // configure new 'compile' directive by passing a directive
  7246. // factory function. The factory function injects the '$compile'
  7247. $compileProvider.directive('compile', function($compile) {
  7248. // directive factory creates a link function
  7249. return function(scope, element, attrs) {
  7250. scope.$watch(
  7251. function(scope) {
  7252. // watch the 'compile' expression for changes
  7253. return scope.$eval(attrs.compile);
  7254. },
  7255. function(value) {
  7256. // when the 'compile' expression changes
  7257. // assign it into the current DOM
  7258. element.html(value);
  7259. // compile the new DOM and link it to the current
  7260. // scope.
  7261. // NOTE: we only compile .childNodes so that
  7262. // we don't get into infinite loop compiling ourselves
  7263. $compile(element.contents())(scope);
  7264. }
  7265. );
  7266. };
  7267. });
  7268. })
  7269. .controller('GreeterController', ['$scope', function($scope) {
  7270. $scope.name = 'AngularJS';
  7271. $scope.html = 'Hello {{name}}';
  7272. }]);
  7273. </script>
  7274. <div ng-controller="GreeterController">
  7275. <input ng-model="name"> <br/>
  7276. <textarea ng-model="html"></textarea> <br/>
  7277. <div compile="html"></div>
  7278. </div>
  7279. </file>
  7280. <file name="protractor.js" type="protractor">
  7281. it('should auto compile', function() {
  7282. var textarea = $('textarea');
  7283. var output = $('div[compile]');
  7284. // The initial state reads 'Hello AngularJS'.
  7285. expect(output.getText()).toBe('Hello AngularJS');
  7286. textarea.clear();
  7287. textarea.sendKeys('{{name}}!');
  7288. expect(output.getText()).toBe('AngularJS!');
  7289. });
  7290. </file>
  7291. </example>
  7292. *
  7293. *
  7294. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7295. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7296. *
  7297. * <div class="alert alert-danger">
  7298. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7299. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7300. * `parentBoundTranscludeFn` to the link function instead.
  7301. * </div>
  7302. *
  7303. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7304. * root element(s), not their children)
  7305. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7306. * (a DOM element/tree) to a scope. Where:
  7307. *
  7308. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7309. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7310. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7311. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7312. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7313. *
  7314. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7315. * * `scope` - is the current scope with which the linking function is working with.
  7316. *
  7317. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7318. * keys may be used to control linking behavior:
  7319. *
  7320. * * `parentBoundTranscludeFn` - the transclude function made available to
  7321. * directives; if given, it will be passed through to the link functions of
  7322. * directives found in `element` during compilation.
  7323. * * `transcludeControllers` - an object hash with keys that map controller names
  7324. * to a hash with the key `instance`, which maps to the controller instance;
  7325. * if given, it will make the controllers available to directives on the compileNode:
  7326. * ```
  7327. * {
  7328. * parent: {
  7329. * instance: parentControllerInstance
  7330. * }
  7331. * }
  7332. * ```
  7333. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7334. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7335. * elements (e.g. SVG elements). See also the directive.controller property.
  7336. *
  7337. * Calling the linking function returns the element of the template. It is either the original
  7338. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7339. *
  7340. * After linking the view is not updated until after a call to $digest which typically is done by
  7341. * AngularJS automatically.
  7342. *
  7343. * If you need access to the bound view, there are two ways to do it:
  7344. *
  7345. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7346. * before you send them to the compiler and keep this reference around.
  7347. * ```js
  7348. * var element = $compile('<p>{{total}}</p>')(scope);
  7349. * ```
  7350. *
  7351. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7352. * example would not point to the clone, but rather to the original template that was cloned. In
  7353. * this case, you can access the clone via the cloneAttachFn:
  7354. * ```js
  7355. * var templateElement = angular.element('<p>{{total}}</p>'),
  7356. * scope = ....;
  7357. *
  7358. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7359. * //attach the clone to DOM document at the right place
  7360. * });
  7361. *
  7362. * //now we have reference to the cloned DOM via `clonedElement`
  7363. * ```
  7364. *
  7365. *
  7366. * For information on how the compiler works, see the
  7367. * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide.
  7368. *
  7369. * @knownIssue
  7370. *
  7371. * ### Double Compilation
  7372. *
  7373. Double compilation occurs when an already compiled part of the DOM gets
  7374. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7375. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7376. section on double compilation} for an in-depth explanation and ways to avoid it.
  7377. *
  7378. */
  7379. var $compileMinErr = minErr('$compile');
  7380. function UNINITIALIZED_VALUE() {}
  7381. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7382. /**
  7383. * @ngdoc provider
  7384. * @name $compileProvider
  7385. *
  7386. * @description
  7387. */
  7388. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7389. /** @this */
  7390. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7391. var hasDirectives = {},
  7392. Suffix = 'Directive',
  7393. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7394. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7395. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7396. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7397. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7398. // The assumption is that future DOM event attribute names will begin with
  7399. // 'on' and be composed of only English letters.
  7400. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7401. var bindingCache = createMap();
  7402. function parseIsolateBindings(scope, directiveName, isController) {
  7403. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7404. var bindings = createMap();
  7405. forEach(scope, function(definition, scopeName) {
  7406. if (definition in bindingCache) {
  7407. bindings[scopeName] = bindingCache[definition];
  7408. return;
  7409. }
  7410. var match = definition.match(LOCAL_REGEXP);
  7411. if (!match) {
  7412. throw $compileMinErr('iscp',
  7413. 'Invalid {3} for directive \'{0}\'.' +
  7414. ' Definition: {... {1}: \'{2}\' ...}',
  7415. directiveName, scopeName, definition,
  7416. (isController ? 'controller bindings definition' :
  7417. 'isolate scope definition'));
  7418. }
  7419. bindings[scopeName] = {
  7420. mode: match[1][0],
  7421. collection: match[2] === '*',
  7422. optional: match[3] === '?',
  7423. attrName: match[4] || scopeName
  7424. };
  7425. if (match[4]) {
  7426. bindingCache[definition] = bindings[scopeName];
  7427. }
  7428. });
  7429. return bindings;
  7430. }
  7431. function parseDirectiveBindings(directive, directiveName) {
  7432. var bindings = {
  7433. isolateScope: null,
  7434. bindToController: null
  7435. };
  7436. if (isObject(directive.scope)) {
  7437. if (directive.bindToController === true) {
  7438. bindings.bindToController = parseIsolateBindings(directive.scope,
  7439. directiveName, true);
  7440. bindings.isolateScope = {};
  7441. } else {
  7442. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7443. directiveName, false);
  7444. }
  7445. }
  7446. if (isObject(directive.bindToController)) {
  7447. bindings.bindToController =
  7448. parseIsolateBindings(directive.bindToController, directiveName, true);
  7449. }
  7450. if (bindings.bindToController && !directive.controller) {
  7451. // There is no controller
  7452. throw $compileMinErr('noctrl',
  7453. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7454. directiveName);
  7455. }
  7456. return bindings;
  7457. }
  7458. function assertValidDirectiveName(name) {
  7459. var letter = name.charAt(0);
  7460. if (!letter || letter !== lowercase(letter)) {
  7461. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7462. }
  7463. if (name !== name.trim()) {
  7464. throw $compileMinErr('baddir',
  7465. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7466. name);
  7467. }
  7468. }
  7469. function getDirectiveRequire(directive) {
  7470. var require = directive.require || (directive.controller && directive.name);
  7471. if (!isArray(require) && isObject(require)) {
  7472. forEach(require, function(value, key) {
  7473. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7474. var name = value.substring(match[0].length);
  7475. if (!name) require[key] = match[0] + key;
  7476. });
  7477. }
  7478. return require;
  7479. }
  7480. function getDirectiveRestrict(restrict, name) {
  7481. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7482. throw $compileMinErr('badrestrict',
  7483. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7484. restrict,
  7485. name);
  7486. }
  7487. return restrict || 'EA';
  7488. }
  7489. /**
  7490. * @ngdoc method
  7491. * @name $compileProvider#directive
  7492. * @kind function
  7493. *
  7494. * @description
  7495. * Register a new directive with the compiler.
  7496. *
  7497. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7498. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7499. * names and the values are the factories.
  7500. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7501. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7502. * @returns {ng.$compileProvider} Self for chaining.
  7503. */
  7504. this.directive = function registerDirective(name, directiveFactory) {
  7505. assertArg(name, 'name');
  7506. assertNotHasOwnProperty(name, 'directive');
  7507. if (isString(name)) {
  7508. assertValidDirectiveName(name);
  7509. assertArg(directiveFactory, 'directiveFactory');
  7510. if (!hasDirectives.hasOwnProperty(name)) {
  7511. hasDirectives[name] = [];
  7512. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7513. function($injector, $exceptionHandler) {
  7514. var directives = [];
  7515. forEach(hasDirectives[name], function(directiveFactory, index) {
  7516. try {
  7517. var directive = $injector.invoke(directiveFactory);
  7518. if (isFunction(directive)) {
  7519. directive = { compile: valueFn(directive) };
  7520. } else if (!directive.compile && directive.link) {
  7521. directive.compile = valueFn(directive.link);
  7522. }
  7523. directive.priority = directive.priority || 0;
  7524. directive.index = index;
  7525. directive.name = directive.name || name;
  7526. directive.require = getDirectiveRequire(directive);
  7527. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7528. directive.$$moduleName = directiveFactory.$$moduleName;
  7529. directives.push(directive);
  7530. } catch (e) {
  7531. $exceptionHandler(e);
  7532. }
  7533. });
  7534. return directives;
  7535. }]);
  7536. }
  7537. hasDirectives[name].push(directiveFactory);
  7538. } else {
  7539. forEach(name, reverseParams(registerDirective));
  7540. }
  7541. return this;
  7542. };
  7543. /**
  7544. * @ngdoc method
  7545. * @name $compileProvider#component
  7546. * @module ng
  7547. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  7548. * or an object map of components where the keys are the names and the values are the component definition objects.
  7549. * @param {Object} options Component definition object (a simplified
  7550. * {@link ng.$compile#directive-definition-object directive definition object}),
  7551. * with the following properties (all optional):
  7552. *
  7553. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7554. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7555. * registered controller} if passed as a string. An empty `noop` function by default.
  7556. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7557. * If present, the controller will be published to scope under the `controllerAs` name.
  7558. * If not present, this will default to be `$ctrl`.
  7559. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7560. * returns an html template as a string which should be used as the contents of this component.
  7561. * Empty string by default.
  7562. *
  7563. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7564. * the following locals:
  7565. *
  7566. * - `$element` - Current element
  7567. * - `$attrs` - Current attributes object for the element
  7568. *
  7569. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7570. * template that should be used as the contents of this component.
  7571. *
  7572. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7573. * the following locals:
  7574. *
  7575. * - `$element` - Current element
  7576. * - `$attrs` - Current attributes object for the element
  7577. *
  7578. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7579. * Component properties are always bound to the component controller and not to the scope.
  7580. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7581. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7582. * Disabled by default.
  7583. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7584. * this component's controller. The object keys specify the property names under which the required
  7585. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7586. * - `$...` – additional properties to attach to the directive factory function and the controller
  7587. * constructor function. (This is used by the component router to annotate)
  7588. *
  7589. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7590. * @description
  7591. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7592. * type of directive, which represents a self-contained UI component in your application. Such components
  7593. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7594. *
  7595. * Component definitions are very simple and do not require as much configuration as defining general
  7596. * directives. Component definitions usually consist only of a template and a controller backing it.
  7597. *
  7598. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7599. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7600. *
  7601. * Here are a few examples of how you would usually define components:
  7602. *
  7603. * ```js
  7604. * var myMod = angular.module(...);
  7605. * myMod.component('myComp', {
  7606. * template: '<div>My name is {{$ctrl.name}}</div>',
  7607. * controller: function() {
  7608. * this.name = 'shahar';
  7609. * }
  7610. * });
  7611. *
  7612. * myMod.component('myComp', {
  7613. * template: '<div>My name is {{$ctrl.name}}</div>',
  7614. * bindings: {name: '@'}
  7615. * });
  7616. *
  7617. * myMod.component('myComp', {
  7618. * templateUrl: 'views/my-comp.html',
  7619. * controller: 'MyCtrl',
  7620. * controllerAs: 'ctrl',
  7621. * bindings: {name: '@'}
  7622. * });
  7623. *
  7624. * ```
  7625. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7626. *
  7627. * <br />
  7628. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7629. */
  7630. this.component = function registerComponent(name, options) {
  7631. if (!isString(name)) {
  7632. forEach(name, reverseParams(bind(this, registerComponent)));
  7633. return this;
  7634. }
  7635. var controller = options.controller || function() {};
  7636. function factory($injector) {
  7637. function makeInjectable(fn) {
  7638. if (isFunction(fn) || isArray(fn)) {
  7639. return /** @this */ function(tElement, tAttrs) {
  7640. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7641. };
  7642. } else {
  7643. return fn;
  7644. }
  7645. }
  7646. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7647. var ddo = {
  7648. controller: controller,
  7649. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7650. template: makeInjectable(template),
  7651. templateUrl: makeInjectable(options.templateUrl),
  7652. transclude: options.transclude,
  7653. scope: {},
  7654. bindToController: options.bindings || {},
  7655. restrict: 'E',
  7656. require: options.require
  7657. };
  7658. // Copy annotations (starting with $) over to the DDO
  7659. forEach(options, function(val, key) {
  7660. if (key.charAt(0) === '$') ddo[key] = val;
  7661. });
  7662. return ddo;
  7663. }
  7664. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7665. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7666. // Nothing in AngularJS looks for annotations on the factory function but we can't remove
  7667. // it from 1.5.x yet.
  7668. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7669. // These could be used by libraries such as the new component router
  7670. forEach(options, function(val, key) {
  7671. if (key.charAt(0) === '$') {
  7672. factory[key] = val;
  7673. // Don't try to copy over annotations to named controller
  7674. if (isFunction(controller)) controller[key] = val;
  7675. }
  7676. });
  7677. factory.$inject = ['$injector'];
  7678. return this.directive(name, factory);
  7679. };
  7680. /**
  7681. * @ngdoc method
  7682. * @name $compileProvider#aHrefSanitizationWhitelist
  7683. * @kind function
  7684. *
  7685. * @description
  7686. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7687. * urls during a[href] sanitization.
  7688. *
  7689. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7690. *
  7691. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7692. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7693. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7694. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7695. *
  7696. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7697. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7698. * chaining otherwise.
  7699. */
  7700. this.aHrefSanitizationWhitelist = function(regexp) {
  7701. if (isDefined(regexp)) {
  7702. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7703. return this;
  7704. } else {
  7705. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7706. }
  7707. };
  7708. /**
  7709. * @ngdoc method
  7710. * @name $compileProvider#imgSrcSanitizationWhitelist
  7711. * @kind function
  7712. *
  7713. * @description
  7714. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7715. * urls during img[src] sanitization.
  7716. *
  7717. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7718. *
  7719. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7720. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7721. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7722. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7723. *
  7724. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7725. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7726. * chaining otherwise.
  7727. */
  7728. this.imgSrcSanitizationWhitelist = function(regexp) {
  7729. if (isDefined(regexp)) {
  7730. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7731. return this;
  7732. } else {
  7733. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7734. }
  7735. };
  7736. /**
  7737. * @ngdoc method
  7738. * @name $compileProvider#debugInfoEnabled
  7739. *
  7740. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7741. * current debugInfoEnabled state
  7742. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7743. *
  7744. * @kind function
  7745. *
  7746. * @description
  7747. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7748. * binding information and a reference to the current scope on to DOM elements.
  7749. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7750. * * `ng-binding` CSS class
  7751. * * `ng-scope` and `ng-isolated-scope` CSS classes
  7752. * * `$binding` data property containing an array of the binding expressions
  7753. * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return
  7754. * the element's scope.
  7755. * * Placeholder comments will contain information about what directive and binding caused the placeholder.
  7756. * E.g. `<!-- ngIf: shouldShow() -->`.
  7757. *
  7758. * You may want to disable this in production for a significant performance boost. See
  7759. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7760. *
  7761. * The default value is true.
  7762. */
  7763. var debugInfoEnabled = true;
  7764. this.debugInfoEnabled = function(enabled) {
  7765. if (isDefined(enabled)) {
  7766. debugInfoEnabled = enabled;
  7767. return this;
  7768. }
  7769. return debugInfoEnabled;
  7770. };
  7771. /**
  7772. * @ngdoc method
  7773. * @name $compileProvider#preAssignBindingsEnabled
  7774. *
  7775. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7776. * current preAssignBindingsEnabled state
  7777. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7778. *
  7779. * @kind function
  7780. *
  7781. * @description
  7782. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7783. * calling the controller's constructor.
  7784. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7785. * properties of the controller object before the constructor of this object is called.
  7786. *
  7787. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7788. *
  7789. * The default value is false.
  7790. *
  7791. * @deprecated
  7792. * sinceVersion="1.6.0"
  7793. * removeVersion="1.7.0"
  7794. *
  7795. * This method and the option to assign the bindings before calling the controller's constructor
  7796. * will be removed in v1.7.0.
  7797. */
  7798. var preAssignBindingsEnabled = false;
  7799. this.preAssignBindingsEnabled = function(enabled) {
  7800. if (isDefined(enabled)) {
  7801. preAssignBindingsEnabled = enabled;
  7802. return this;
  7803. }
  7804. return preAssignBindingsEnabled;
  7805. };
  7806. /**
  7807. * @ngdoc method
  7808. * @name $compileProvider#strictComponentBindingsEnabled
  7809. *
  7810. * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, otherwise just return the
  7811. * current strictComponentBindingsEnabled state
  7812. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7813. *
  7814. * @kind function
  7815. *
  7816. * @description
  7817. * Call this method to enable/disable strict component bindings check. If enabled, the compiler will enforce that
  7818. * for all bindings of a component that are not set as optional with `?`, an attribute needs to be provided
  7819. * on the component's HTML tag.
  7820. *
  7821. * The default value is false.
  7822. */
  7823. var strictComponentBindingsEnabled = false;
  7824. this.strictComponentBindingsEnabled = function(enabled) {
  7825. if (isDefined(enabled)) {
  7826. strictComponentBindingsEnabled = enabled;
  7827. return this;
  7828. }
  7829. return strictComponentBindingsEnabled;
  7830. };
  7831. var TTL = 10;
  7832. /**
  7833. * @ngdoc method
  7834. * @name $compileProvider#onChangesTtl
  7835. * @description
  7836. *
  7837. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7838. * assuming that the model is unstable.
  7839. *
  7840. * The current default is 10 iterations.
  7841. *
  7842. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7843. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7844. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7845. * the `$onChanges` hook execution.
  7846. *
  7847. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7848. *
  7849. * @param {number} limit The number of `$onChanges` hook iterations.
  7850. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7851. */
  7852. this.onChangesTtl = function(value) {
  7853. if (arguments.length) {
  7854. TTL = value;
  7855. return this;
  7856. }
  7857. return TTL;
  7858. };
  7859. var commentDirectivesEnabledConfig = true;
  7860. /**
  7861. * @ngdoc method
  7862. * @name $compileProvider#commentDirectivesEnabled
  7863. * @description
  7864. *
  7865. * It indicates to the compiler
  7866. * whether or not directives on comments should be compiled.
  7867. * Defaults to `true`.
  7868. *
  7869. * Calling this function with false disables the compilation of directives
  7870. * on comments for the whole application.
  7871. * This results in a compilation performance gain,
  7872. * as the compiler doesn't have to check comments when looking for directives.
  7873. * This should however only be used if you are sure that no comment directives are used in
  7874. * the application (including any 3rd party directives).
  7875. *
  7876. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7877. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7878. */
  7879. this.commentDirectivesEnabled = function(value) {
  7880. if (arguments.length) {
  7881. commentDirectivesEnabledConfig = value;
  7882. return this;
  7883. }
  7884. return commentDirectivesEnabledConfig;
  7885. };
  7886. var cssClassDirectivesEnabledConfig = true;
  7887. /**
  7888. * @ngdoc method
  7889. * @name $compileProvider#cssClassDirectivesEnabled
  7890. * @description
  7891. *
  7892. * It indicates to the compiler
  7893. * whether or not directives on element classes should be compiled.
  7894. * Defaults to `true`.
  7895. *
  7896. * Calling this function with false disables the compilation of directives
  7897. * on element classes for the whole application.
  7898. * This results in a compilation performance gain,
  7899. * as the compiler doesn't have to check element classes when looking for directives.
  7900. * This should however only be used if you are sure that no class directives are used in
  7901. * the application (including any 3rd party directives).
  7902. *
  7903. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7904. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7905. */
  7906. this.cssClassDirectivesEnabled = function(value) {
  7907. if (arguments.length) {
  7908. cssClassDirectivesEnabledConfig = value;
  7909. return this;
  7910. }
  7911. return cssClassDirectivesEnabledConfig;
  7912. };
  7913. this.$get = [
  7914. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7915. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7916. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7917. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7918. var SIMPLE_ATTR_NAME = /^\w/;
  7919. var specialAttrHolder = window.document.createElement('div');
  7920. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7921. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7922. var onChangesTtl = TTL;
  7923. // The onChanges hooks should all be run together in a single digest
  7924. // When changes occur, the call to trigger their hooks will be added to this queue
  7925. var onChangesQueue;
  7926. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7927. function flushOnChangesQueue() {
  7928. try {
  7929. if (!(--onChangesTtl)) {
  7930. // We have hit the TTL limit so reset everything
  7931. onChangesQueue = undefined;
  7932. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7933. }
  7934. // We must run this hook in an apply since the $$postDigest runs outside apply
  7935. $rootScope.$apply(function() {
  7936. var errors = [];
  7937. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7938. try {
  7939. onChangesQueue[i]();
  7940. } catch (e) {
  7941. errors.push(e);
  7942. }
  7943. }
  7944. // Reset the queue to trigger a new schedule next time there is a change
  7945. onChangesQueue = undefined;
  7946. if (errors.length) {
  7947. throw errors;
  7948. }
  7949. });
  7950. } finally {
  7951. onChangesTtl++;
  7952. }
  7953. }
  7954. function Attributes(element, attributesToCopy) {
  7955. if (attributesToCopy) {
  7956. var keys = Object.keys(attributesToCopy);
  7957. var i, l, key;
  7958. for (i = 0, l = keys.length; i < l; i++) {
  7959. key = keys[i];
  7960. this[key] = attributesToCopy[key];
  7961. }
  7962. } else {
  7963. this.$attr = {};
  7964. }
  7965. this.$$element = element;
  7966. }
  7967. Attributes.prototype = {
  7968. /**
  7969. * @ngdoc method
  7970. * @name $compile.directive.Attributes#$normalize
  7971. * @kind function
  7972. *
  7973. * @description
  7974. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7975. * `data-`) to its normalized, camelCase form.
  7976. *
  7977. * Also there is special case for Moz prefix starting with upper case letter.
  7978. *
  7979. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7980. *
  7981. * @param {string} name Name to normalize
  7982. */
  7983. $normalize: directiveNormalize,
  7984. /**
  7985. * @ngdoc method
  7986. * @name $compile.directive.Attributes#$addClass
  7987. * @kind function
  7988. *
  7989. * @description
  7990. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7991. * are enabled then an animation will be triggered for the class addition.
  7992. *
  7993. * @param {string} classVal The className value that will be added to the element
  7994. */
  7995. $addClass: function(classVal) {
  7996. if (classVal && classVal.length > 0) {
  7997. $animate.addClass(this.$$element, classVal);
  7998. }
  7999. },
  8000. /**
  8001. * @ngdoc method
  8002. * @name $compile.directive.Attributes#$removeClass
  8003. * @kind function
  8004. *
  8005. * @description
  8006. * Removes the CSS class value specified by the classVal parameter from the element. If
  8007. * animations are enabled then an animation will be triggered for the class removal.
  8008. *
  8009. * @param {string} classVal The className value that will be removed from the element
  8010. */
  8011. $removeClass: function(classVal) {
  8012. if (classVal && classVal.length > 0) {
  8013. $animate.removeClass(this.$$element, classVal);
  8014. }
  8015. },
  8016. /**
  8017. * @ngdoc method
  8018. * @name $compile.directive.Attributes#$updateClass
  8019. * @kind function
  8020. *
  8021. * @description
  8022. * Adds and removes the appropriate CSS class values to the element based on the difference
  8023. * between the new and old CSS class values (specified as newClasses and oldClasses).
  8024. *
  8025. * @param {string} newClasses The current CSS className value
  8026. * @param {string} oldClasses The former CSS className value
  8027. */
  8028. $updateClass: function(newClasses, oldClasses) {
  8029. var toAdd = tokenDifference(newClasses, oldClasses);
  8030. if (toAdd && toAdd.length) {
  8031. $animate.addClass(this.$$element, toAdd);
  8032. }
  8033. var toRemove = tokenDifference(oldClasses, newClasses);
  8034. if (toRemove && toRemove.length) {
  8035. $animate.removeClass(this.$$element, toRemove);
  8036. }
  8037. },
  8038. /**
  8039. * Set a normalized attribute on the element in a way such that all directives
  8040. * can share the attribute. This function properly handles boolean attributes.
  8041. * @param {string} key Normalized key. (ie ngAttribute)
  8042. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  8043. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  8044. * Defaults to true.
  8045. * @param {string=} attrName Optional none normalized name. Defaults to key.
  8046. */
  8047. $set: function(key, value, writeAttr, attrName) {
  8048. // TODO: decide whether or not to throw an error if "class"
  8049. //is set through this function since it may cause $updateClass to
  8050. //become unstable.
  8051. var node = this.$$element[0],
  8052. booleanKey = getBooleanAttrName(node, key),
  8053. aliasedKey = getAliasedAttrName(key),
  8054. observer = key,
  8055. nodeName;
  8056. if (booleanKey) {
  8057. this.$$element.prop(key, value);
  8058. attrName = booleanKey;
  8059. } else if (aliasedKey) {
  8060. this[aliasedKey] = value;
  8061. observer = aliasedKey;
  8062. }
  8063. this[key] = value;
  8064. // translate normalized key to actual key
  8065. if (attrName) {
  8066. this.$attr[key] = attrName;
  8067. } else {
  8068. attrName = this.$attr[key];
  8069. if (!attrName) {
  8070. this.$attr[key] = attrName = snake_case(key, '-');
  8071. }
  8072. }
  8073. nodeName = nodeName_(this.$$element);
  8074. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  8075. (nodeName === 'img' && key === 'src')) {
  8076. // sanitize a[href] and img[src] values
  8077. this[key] = value = $$sanitizeUri(value, key === 'src');
  8078. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  8079. // sanitize img[srcset] values
  8080. var result = '';
  8081. // first check if there are spaces because it's not the same pattern
  8082. var trimmedSrcset = trim(value);
  8083. // ( 999x ,| 999w ,| ,|, )
  8084. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  8085. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  8086. // split srcset into tuple of uri and descriptor except for the last item
  8087. var rawUris = trimmedSrcset.split(pattern);
  8088. // for each tuples
  8089. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  8090. for (var i = 0; i < nbrUrisWith2parts; i++) {
  8091. var innerIdx = i * 2;
  8092. // sanitize the uri
  8093. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  8094. // add the descriptor
  8095. result += (' ' + trim(rawUris[innerIdx + 1]));
  8096. }
  8097. // split the last item into uri and descriptor
  8098. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  8099. // sanitize the last uri
  8100. result += $$sanitizeUri(trim(lastTuple[0]), true);
  8101. // and add the last descriptor if any
  8102. if (lastTuple.length === 2) {
  8103. result += (' ' + trim(lastTuple[1]));
  8104. }
  8105. this[key] = value = result;
  8106. }
  8107. if (writeAttr !== false) {
  8108. if (value === null || isUndefined(value)) {
  8109. this.$$element.removeAttr(attrName);
  8110. } else {
  8111. if (SIMPLE_ATTR_NAME.test(attrName)) {
  8112. this.$$element.attr(attrName, value);
  8113. } else {
  8114. setSpecialAttr(this.$$element[0], attrName, value);
  8115. }
  8116. }
  8117. }
  8118. // fire observers
  8119. var $$observers = this.$$observers;
  8120. if ($$observers) {
  8121. forEach($$observers[observer], function(fn) {
  8122. try {
  8123. fn(value);
  8124. } catch (e) {
  8125. $exceptionHandler(e);
  8126. }
  8127. });
  8128. }
  8129. },
  8130. /**
  8131. * @ngdoc method
  8132. * @name $compile.directive.Attributes#$observe
  8133. * @kind function
  8134. *
  8135. * @description
  8136. * Observes an interpolated attribute.
  8137. *
  8138. * The observer function will be invoked once during the next `$digest` following
  8139. * compilation. The observer is then invoked whenever the interpolated value
  8140. * changes.
  8141. *
  8142. * @param {string} key Normalized key. (ie ngAttribute) .
  8143. * @param {function(interpolatedValue)} fn Function that will be called whenever
  8144. the interpolated value of the attribute changes.
  8145. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  8146. * guide} for more info.
  8147. * @returns {function()} Returns a deregistration function for this observer.
  8148. */
  8149. $observe: function(key, fn) {
  8150. var attrs = this,
  8151. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  8152. listeners = ($$observers[key] || ($$observers[key] = []));
  8153. listeners.push(fn);
  8154. $rootScope.$evalAsync(function() {
  8155. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  8156. // no one registered attribute interpolation function, so lets call it manually
  8157. fn(attrs[key]);
  8158. }
  8159. });
  8160. return function() {
  8161. arrayRemove(listeners, fn);
  8162. };
  8163. }
  8164. };
  8165. function setSpecialAttr(element, attrName, value) {
  8166. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  8167. // so we have to jump through some hoops to get such an attribute
  8168. // https://github.com/angular/angular.js/pull/13318
  8169. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  8170. var attributes = specialAttrHolder.firstChild.attributes;
  8171. var attribute = attributes[0];
  8172. // We have to remove the attribute from its container element before we can add it to the destination element
  8173. attributes.removeNamedItem(attribute.name);
  8174. attribute.value = value;
  8175. element.attributes.setNamedItem(attribute);
  8176. }
  8177. function safeAddClass($element, className) {
  8178. try {
  8179. $element.addClass(className);
  8180. } catch (e) {
  8181. // ignore, since it means that we are trying to set class on
  8182. // SVG element, where class name is read-only.
  8183. }
  8184. }
  8185. var startSymbol = $interpolate.startSymbol(),
  8186. endSymbol = $interpolate.endSymbol(),
  8187. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8188. ? identity
  8189. : function denormalizeTemplate(template) {
  8190. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8191. },
  8192. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  8193. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8194. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8195. var bindings = $element.data('$binding') || [];
  8196. if (isArray(binding)) {
  8197. bindings = bindings.concat(binding);
  8198. } else {
  8199. bindings.push(binding);
  8200. }
  8201. $element.data('$binding', bindings);
  8202. } : noop;
  8203. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8204. safeAddClass($element, 'ng-binding');
  8205. } : noop;
  8206. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8207. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8208. $element.data(dataName, scope);
  8209. } : noop;
  8210. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8211. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8212. } : noop;
  8213. compile.$$createComment = function(directiveName, comment) {
  8214. var content = '';
  8215. if (debugInfoEnabled) {
  8216. content = ' ' + (directiveName || '') + ': ';
  8217. if (comment) content += comment + ' ';
  8218. }
  8219. return window.document.createComment(content);
  8220. };
  8221. return compile;
  8222. //================================
  8223. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8224. previousCompileContext) {
  8225. if (!($compileNodes instanceof jqLite)) {
  8226. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8227. // modify it.
  8228. $compileNodes = jqLite($compileNodes);
  8229. }
  8230. var compositeLinkFn =
  8231. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8232. maxPriority, ignoreDirective, previousCompileContext);
  8233. compile.$$addScopeClass($compileNodes);
  8234. var namespace = null;
  8235. return function publicLinkFn(scope, cloneConnectFn, options) {
  8236. if (!$compileNodes) {
  8237. throw $compileMinErr('multilink', 'This element has already been linked.');
  8238. }
  8239. assertArg(scope, 'scope');
  8240. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8241. // A parent directive did a replace and a directive on this element asked
  8242. // for transclusion, which caused us to lose a layer of element on which
  8243. // we could hold the new transclusion scope, so we will create it manually
  8244. // here.
  8245. scope = scope.$parent.$new();
  8246. }
  8247. options = options || {};
  8248. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8249. transcludeControllers = options.transcludeControllers,
  8250. futureParentElement = options.futureParentElement;
  8251. // When `parentBoundTranscludeFn` is passed, it is a
  8252. // `controllersBoundTransclude` function (it was previously passed
  8253. // as `transclude` to directive.link) so we must unwrap it to get
  8254. // its `boundTranscludeFn`
  8255. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8256. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8257. }
  8258. if (!namespace) {
  8259. namespace = detectNamespaceForChildElements(futureParentElement);
  8260. }
  8261. var $linkNode;
  8262. if (namespace !== 'html') {
  8263. // When using a directive with replace:true and templateUrl the $compileNodes
  8264. // (or a child element inside of them)
  8265. // might change, so we need to recreate the namespace adapted compileNodes
  8266. // for call to the link function.
  8267. // Note: This will already clone the nodes...
  8268. $linkNode = jqLite(
  8269. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  8270. );
  8271. } else if (cloneConnectFn) {
  8272. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8273. // and sometimes changes the structure of the DOM.
  8274. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8275. } else {
  8276. $linkNode = $compileNodes;
  8277. }
  8278. if (transcludeControllers) {
  8279. for (var controllerName in transcludeControllers) {
  8280. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8281. }
  8282. }
  8283. compile.$$addScopeInfo($linkNode, scope);
  8284. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8285. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8286. if (!cloneConnectFn) {
  8287. $compileNodes = compositeLinkFn = null;
  8288. }
  8289. return $linkNode;
  8290. };
  8291. }
  8292. function detectNamespaceForChildElements(parentElement) {
  8293. // TODO: Make this detect MathML as well...
  8294. var node = parentElement && parentElement[0];
  8295. if (!node) {
  8296. return 'html';
  8297. } else {
  8298. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8299. }
  8300. }
  8301. /**
  8302. * Compile function matches each node in nodeList against the directives. Once all directives
  8303. * for a particular node are collected their compile functions are executed. The compile
  8304. * functions return values - the linking functions - are combined into a composite linking
  8305. * function, which is the a linking function for the node.
  8306. *
  8307. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8308. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8309. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8310. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8311. * the rootElement must be set the jqLite collection of the compile root. This is
  8312. * needed so that the jqLite collection items can be replaced with widgets.
  8313. * @param {number=} maxPriority Max directive priority.
  8314. * @returns {Function} A composite linking function of all of the matched directives or null.
  8315. */
  8316. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8317. previousCompileContext) {
  8318. var linkFns = [],
  8319. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8320. // or a jqLite/jQuery collection or an array
  8321. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8322. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8323. for (var i = 0; i < nodeList.length; i++) {
  8324. attrs = new Attributes();
  8325. // Support: IE 11 only
  8326. // Workaround for #11781 and #14924
  8327. if (msie === 11) {
  8328. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8329. }
  8330. // We must always refer to `nodeList[i]` hereafter,
  8331. // since the nodes can be replaced underneath us.
  8332. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8333. ignoreDirective);
  8334. nodeLinkFn = (directives.length)
  8335. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8336. null, [], [], previousCompileContext)
  8337. : null;
  8338. if (nodeLinkFn && nodeLinkFn.scope) {
  8339. compile.$$addScopeClass(attrs.$$element);
  8340. }
  8341. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8342. !(childNodes = nodeList[i].childNodes) ||
  8343. !childNodes.length)
  8344. ? null
  8345. : compileNodes(childNodes,
  8346. nodeLinkFn ? (
  8347. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8348. && nodeLinkFn.transclude) : transcludeFn);
  8349. if (nodeLinkFn || childLinkFn) {
  8350. linkFns.push(i, nodeLinkFn, childLinkFn);
  8351. linkFnFound = true;
  8352. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8353. }
  8354. //use the previous context only for the first element in the virtual group
  8355. previousCompileContext = null;
  8356. }
  8357. // return a linking function if we have found anything, null otherwise
  8358. return linkFnFound ? compositeLinkFn : null;
  8359. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8360. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8361. var stableNodeList;
  8362. if (nodeLinkFnFound) {
  8363. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8364. // offsets don't get screwed up
  8365. var nodeListLength = nodeList.length;
  8366. stableNodeList = new Array(nodeListLength);
  8367. // create a sparse array by only copying the elements which have a linkFn
  8368. for (i = 0; i < linkFns.length; i += 3) {
  8369. idx = linkFns[i];
  8370. stableNodeList[idx] = nodeList[idx];
  8371. }
  8372. } else {
  8373. stableNodeList = nodeList;
  8374. }
  8375. for (i = 0, ii = linkFns.length; i < ii;) {
  8376. node = stableNodeList[linkFns[i++]];
  8377. nodeLinkFn = linkFns[i++];
  8378. childLinkFn = linkFns[i++];
  8379. if (nodeLinkFn) {
  8380. if (nodeLinkFn.scope) {
  8381. childScope = scope.$new();
  8382. compile.$$addScopeInfo(jqLite(node), childScope);
  8383. } else {
  8384. childScope = scope;
  8385. }
  8386. if (nodeLinkFn.transcludeOnThisElement) {
  8387. childBoundTranscludeFn = createBoundTranscludeFn(
  8388. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8389. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8390. childBoundTranscludeFn = parentBoundTranscludeFn;
  8391. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8392. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8393. } else {
  8394. childBoundTranscludeFn = null;
  8395. }
  8396. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8397. } else if (childLinkFn) {
  8398. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8399. }
  8400. }
  8401. }
  8402. }
  8403. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8404. var node = nodeList[idx];
  8405. var parent = node.parentNode;
  8406. var sibling;
  8407. if (node.nodeType !== NODE_TYPE_TEXT) {
  8408. return;
  8409. }
  8410. while (true) {
  8411. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8412. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8413. break;
  8414. }
  8415. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8416. if (sibling.parentNode) {
  8417. sibling.parentNode.removeChild(sibling);
  8418. }
  8419. if (notLiveList && sibling === nodeList[idx + 1]) {
  8420. nodeList.splice(idx + 1, 1);
  8421. }
  8422. }
  8423. }
  8424. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8425. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8426. if (!transcludedScope) {
  8427. transcludedScope = scope.$new(false, containingScope);
  8428. transcludedScope.$$transcluded = true;
  8429. }
  8430. return transcludeFn(transcludedScope, cloneFn, {
  8431. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8432. transcludeControllers: controllers,
  8433. futureParentElement: futureParentElement
  8434. });
  8435. }
  8436. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8437. // so that they are available inside the `controllersBoundTransclude` function
  8438. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8439. for (var slotName in transcludeFn.$$slots) {
  8440. if (transcludeFn.$$slots[slotName]) {
  8441. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8442. } else {
  8443. boundSlots[slotName] = null;
  8444. }
  8445. }
  8446. return boundTranscludeFn;
  8447. }
  8448. /**
  8449. * Looks for directives on the given node and adds them to the directive collection which is
  8450. * sorted.
  8451. *
  8452. * @param node Node to search.
  8453. * @param directives An array to which the directives are added to. This array is sorted before
  8454. * the function returns.
  8455. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8456. * @param {number=} maxPriority Max directive priority.
  8457. */
  8458. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8459. var nodeType = node.nodeType,
  8460. attrsMap = attrs.$attr,
  8461. match,
  8462. nodeName,
  8463. className;
  8464. switch (nodeType) {
  8465. case NODE_TYPE_ELEMENT: /* Element */
  8466. nodeName = nodeName_(node);
  8467. // use the node name: <directive>
  8468. addDirective(directives,
  8469. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8470. // iterate over the attributes
  8471. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8472. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8473. var attrStartName = false;
  8474. var attrEndName = false;
  8475. attr = nAttrs[j];
  8476. name = attr.name;
  8477. value = attr.value;
  8478. // support ngAttr attribute binding
  8479. ngAttrName = directiveNormalize(name);
  8480. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8481. if (isNgAttr) {
  8482. name = name.replace(PREFIX_REGEXP, '')
  8483. .substr(8).replace(/_(.)/g, function(match, letter) {
  8484. return letter.toUpperCase();
  8485. });
  8486. }
  8487. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8488. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8489. attrStartName = name;
  8490. attrEndName = name.substr(0, name.length - 5) + 'end';
  8491. name = name.substr(0, name.length - 6);
  8492. }
  8493. nName = directiveNormalize(name.toLowerCase());
  8494. attrsMap[nName] = name;
  8495. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8496. attrs[nName] = value;
  8497. if (getBooleanAttrName(node, nName)) {
  8498. attrs[nName] = true; // presence means true
  8499. }
  8500. }
  8501. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8502. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8503. attrEndName);
  8504. }
  8505. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8506. // Hidden input elements can have strange behaviour when navigating back to the page
  8507. // This tells the browser not to try to cache and reinstate previous values
  8508. node.setAttribute('autocomplete', 'off');
  8509. }
  8510. // use class as directive
  8511. if (!cssClassDirectivesEnabled) break;
  8512. className = node.className;
  8513. if (isObject(className)) {
  8514. // Maybe SVGAnimatedString
  8515. className = className.animVal;
  8516. }
  8517. if (isString(className) && className !== '') {
  8518. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8519. nName = directiveNormalize(match[2]);
  8520. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8521. attrs[nName] = trim(match[3]);
  8522. }
  8523. className = className.substr(match.index + match[0].length);
  8524. }
  8525. }
  8526. break;
  8527. case NODE_TYPE_TEXT: /* Text Node */
  8528. addTextInterpolateDirective(directives, node.nodeValue);
  8529. break;
  8530. case NODE_TYPE_COMMENT: /* Comment */
  8531. if (!commentDirectivesEnabled) break;
  8532. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8533. break;
  8534. }
  8535. directives.sort(byPriority);
  8536. return directives;
  8537. }
  8538. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8539. // function created because of performance, try/catch disables
  8540. // the optimization of the whole function #14848
  8541. try {
  8542. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8543. if (match) {
  8544. var nName = directiveNormalize(match[1]);
  8545. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8546. attrs[nName] = trim(match[2]);
  8547. }
  8548. }
  8549. } catch (e) {
  8550. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8551. // comment's node value.
  8552. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8553. }
  8554. }
  8555. /**
  8556. * Given a node with a directive-start it collects all of the siblings until it finds
  8557. * directive-end.
  8558. * @param node
  8559. * @param attrStart
  8560. * @param attrEnd
  8561. * @returns {*}
  8562. */
  8563. function groupScan(node, attrStart, attrEnd) {
  8564. var nodes = [];
  8565. var depth = 0;
  8566. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8567. do {
  8568. if (!node) {
  8569. throw $compileMinErr('uterdir',
  8570. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8571. attrStart, attrEnd);
  8572. }
  8573. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8574. if (node.hasAttribute(attrStart)) depth++;
  8575. if (node.hasAttribute(attrEnd)) depth--;
  8576. }
  8577. nodes.push(node);
  8578. node = node.nextSibling;
  8579. } while (depth > 0);
  8580. } else {
  8581. nodes.push(node);
  8582. }
  8583. return jqLite(nodes);
  8584. }
  8585. /**
  8586. * Wrapper for linking function which converts normal linking function into a grouped
  8587. * linking function.
  8588. * @param linkFn
  8589. * @param attrStart
  8590. * @param attrEnd
  8591. * @returns {Function}
  8592. */
  8593. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8594. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8595. element = groupScan(element[0], attrStart, attrEnd);
  8596. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8597. };
  8598. }
  8599. /**
  8600. * A function generator that is used to support both eager and lazy compilation
  8601. * linking function.
  8602. * @param eager
  8603. * @param $compileNodes
  8604. * @param transcludeFn
  8605. * @param maxPriority
  8606. * @param ignoreDirective
  8607. * @param previousCompileContext
  8608. * @returns {Function}
  8609. */
  8610. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8611. var compiled;
  8612. if (eager) {
  8613. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8614. }
  8615. return /** @this */ function lazyCompilation() {
  8616. if (!compiled) {
  8617. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8618. // Null out all of these references in order to make them eligible for garbage collection
  8619. // since this is a potentially long lived closure
  8620. $compileNodes = transcludeFn = previousCompileContext = null;
  8621. }
  8622. return compiled.apply(this, arguments);
  8623. };
  8624. }
  8625. /**
  8626. * Once the directives have been collected, their compile functions are executed. This method
  8627. * is responsible for inlining directive templates as well as terminating the application
  8628. * of the directives if the terminal directive has been reached.
  8629. *
  8630. * @param {Array} directives Array of collected directives to execute their compile function.
  8631. * this needs to be pre-sorted by priority order.
  8632. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8633. * @param {Object} templateAttrs The shared attribute function
  8634. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8635. * scope argument is auto-generated to the new
  8636. * child of the transcluded parent scope.
  8637. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8638. * argument has the root jqLite array so that we can replace nodes
  8639. * on it.
  8640. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8641. * compiling the transclusion.
  8642. * @param {Array.<Function>} preLinkFns
  8643. * @param {Array.<Function>} postLinkFns
  8644. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8645. * node
  8646. * @returns {Function} linkFn
  8647. */
  8648. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8649. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8650. previousCompileContext) {
  8651. previousCompileContext = previousCompileContext || {};
  8652. var terminalPriority = -Number.MAX_VALUE,
  8653. newScopeDirective = previousCompileContext.newScopeDirective,
  8654. controllerDirectives = previousCompileContext.controllerDirectives,
  8655. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8656. templateDirective = previousCompileContext.templateDirective,
  8657. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8658. hasTranscludeDirective = false,
  8659. hasTemplate = false,
  8660. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8661. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8662. directive,
  8663. directiveName,
  8664. $template,
  8665. replaceDirective = originalReplaceDirective,
  8666. childTranscludeFn = transcludeFn,
  8667. linkFn,
  8668. didScanForMultipleTransclusion = false,
  8669. mightHaveMultipleTransclusionError = false,
  8670. directiveValue;
  8671. // executes all directives on the current element
  8672. for (var i = 0, ii = directives.length; i < ii; i++) {
  8673. directive = directives[i];
  8674. var attrStart = directive.$$start;
  8675. var attrEnd = directive.$$end;
  8676. // collect multiblock sections
  8677. if (attrStart) {
  8678. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8679. }
  8680. $template = undefined;
  8681. if (terminalPriority > directive.priority) {
  8682. break; // prevent further processing of directives
  8683. }
  8684. directiveValue = directive.scope;
  8685. if (directiveValue) {
  8686. // skip the check for directives with async templates, we'll check the derived sync
  8687. // directive when the template arrives
  8688. if (!directive.templateUrl) {
  8689. if (isObject(directiveValue)) {
  8690. // This directive is trying to add an isolated scope.
  8691. // Check that there is no scope of any kind already
  8692. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8693. directive, $compileNode);
  8694. newIsolateScopeDirective = directive;
  8695. } else {
  8696. // This directive is trying to add a child scope.
  8697. // Check that there is no isolated scope already
  8698. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8699. $compileNode);
  8700. }
  8701. }
  8702. newScopeDirective = newScopeDirective || directive;
  8703. }
  8704. directiveName = directive.name;
  8705. // If we encounter a condition that can result in transclusion on the directive,
  8706. // then scan ahead in the remaining directives for others that may cause a multiple
  8707. // transclusion error to be thrown during the compilation process. If a matching directive
  8708. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8709. // compile the `transclude` function rather than doing it lazily in order to throw
  8710. // exceptions at the correct time
  8711. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8712. || (directive.transclude && !directive.$$tlb))) {
  8713. var candidateDirective;
  8714. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8715. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8716. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8717. mightHaveMultipleTransclusionError = true;
  8718. break;
  8719. }
  8720. }
  8721. didScanForMultipleTransclusion = true;
  8722. }
  8723. if (!directive.templateUrl && directive.controller) {
  8724. controllerDirectives = controllerDirectives || createMap();
  8725. assertNoDuplicate('\'' + directiveName + '\' controller',
  8726. controllerDirectives[directiveName], directive, $compileNode);
  8727. controllerDirectives[directiveName] = directive;
  8728. }
  8729. directiveValue = directive.transclude;
  8730. if (directiveValue) {
  8731. hasTranscludeDirective = true;
  8732. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8733. // This option should only be used by directives that know how to safely handle element transclusion,
  8734. // where the transcluded nodes are added or replaced after linking.
  8735. if (!directive.$$tlb) {
  8736. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8737. nonTlbTranscludeDirective = directive;
  8738. }
  8739. if (directiveValue === 'element') {
  8740. hasElementTranscludeDirective = true;
  8741. terminalPriority = directive.priority;
  8742. $template = $compileNode;
  8743. $compileNode = templateAttrs.$$element =
  8744. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8745. compileNode = $compileNode[0];
  8746. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8747. // Support: Chrome < 50
  8748. // https://github.com/angular/angular.js/issues/14041
  8749. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8750. // in the `replaceWith` function is improperly garbage collected despite still
  8751. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8752. // a reference to the fragment via a different property, we can avoid that incorrect
  8753. // behavior.
  8754. // TODO: remove this line after Chrome 50 has been released
  8755. $template[0].$$parentNode = $template[0].parentNode;
  8756. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8757. replaceDirective && replaceDirective.name, {
  8758. // Don't pass in:
  8759. // - controllerDirectives - otherwise we'll create duplicates controllers
  8760. // - newIsolateScopeDirective or templateDirective - combining templates with
  8761. // element transclusion doesn't make sense.
  8762. //
  8763. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8764. // on the same element more than once.
  8765. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8766. });
  8767. } else {
  8768. var slots = createMap();
  8769. if (!isObject(directiveValue)) {
  8770. $template = jqLite(jqLiteClone(compileNode)).contents();
  8771. } else {
  8772. // We have transclusion slots,
  8773. // collect them up, compile them and store their transclusion functions
  8774. $template = [];
  8775. var slotMap = createMap();
  8776. var filledSlots = createMap();
  8777. // Parse the element selectors
  8778. forEach(directiveValue, function(elementSelector, slotName) {
  8779. // If an element selector starts with a ? then it is optional
  8780. var optional = (elementSelector.charAt(0) === '?');
  8781. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8782. slotMap[elementSelector] = slotName;
  8783. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8784. // Later when calling boundTransclusion functions with a slot name we only error if the
  8785. // slot is `undefined`
  8786. slots[slotName] = null;
  8787. // filledSlots contains `true` for all slots that are either optional or have been
  8788. // filled. This is used to check that we have not missed any required slots
  8789. filledSlots[slotName] = optional;
  8790. });
  8791. // Add the matching elements into their slot
  8792. forEach($compileNode.contents(), function(node) {
  8793. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8794. if (slotName) {
  8795. filledSlots[slotName] = true;
  8796. slots[slotName] = slots[slotName] || [];
  8797. slots[slotName].push(node);
  8798. } else {
  8799. $template.push(node);
  8800. }
  8801. });
  8802. // Check for required slots that were not filled
  8803. forEach(filledSlots, function(filled, slotName) {
  8804. if (!filled) {
  8805. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8806. }
  8807. });
  8808. for (var slotName in slots) {
  8809. if (slots[slotName]) {
  8810. // Only define a transclusion function if the slot was filled
  8811. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8812. }
  8813. }
  8814. }
  8815. $compileNode.empty(); // clear contents
  8816. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8817. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8818. childTranscludeFn.$$slots = slots;
  8819. }
  8820. }
  8821. if (directive.template) {
  8822. hasTemplate = true;
  8823. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8824. templateDirective = directive;
  8825. directiveValue = (isFunction(directive.template))
  8826. ? directive.template($compileNode, templateAttrs)
  8827. : directive.template;
  8828. directiveValue = denormalizeTemplate(directiveValue);
  8829. if (directive.replace) {
  8830. replaceDirective = directive;
  8831. if (jqLiteIsTextNode(directiveValue)) {
  8832. $template = [];
  8833. } else {
  8834. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8835. }
  8836. compileNode = $template[0];
  8837. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8838. throw $compileMinErr('tplrt',
  8839. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8840. directiveName, '');
  8841. }
  8842. replaceWith(jqCollection, $compileNode, compileNode);
  8843. var newTemplateAttrs = {$attr: {}};
  8844. // combine directives from the original node and from the template:
  8845. // - take the array of directives for this element
  8846. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8847. // - collect directives from the template and sort them by priority
  8848. // - combine directives as: processed + template + unprocessed
  8849. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8850. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8851. if (newIsolateScopeDirective || newScopeDirective) {
  8852. // The original directive caused the current element to be replaced but this element
  8853. // also needs to have a new scope, so we need to tell the template directives
  8854. // that they would need to get their scope from further up, if they require transclusion
  8855. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8856. }
  8857. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8858. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8859. ii = directives.length;
  8860. } else {
  8861. $compileNode.html(directiveValue);
  8862. }
  8863. }
  8864. if (directive.templateUrl) {
  8865. hasTemplate = true;
  8866. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8867. templateDirective = directive;
  8868. if (directive.replace) {
  8869. replaceDirective = directive;
  8870. }
  8871. // eslint-disable-next-line no-func-assign
  8872. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8873. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8874. controllerDirectives: controllerDirectives,
  8875. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8876. newIsolateScopeDirective: newIsolateScopeDirective,
  8877. templateDirective: templateDirective,
  8878. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8879. });
  8880. ii = directives.length;
  8881. } else if (directive.compile) {
  8882. try {
  8883. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8884. var context = directive.$$originalDirective || directive;
  8885. if (isFunction(linkFn)) {
  8886. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8887. } else if (linkFn) {
  8888. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8889. }
  8890. } catch (e) {
  8891. $exceptionHandler(e, startingTag($compileNode));
  8892. }
  8893. }
  8894. if (directive.terminal) {
  8895. nodeLinkFn.terminal = true;
  8896. terminalPriority = Math.max(terminalPriority, directive.priority);
  8897. }
  8898. }
  8899. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8900. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8901. nodeLinkFn.templateOnThisElement = hasTemplate;
  8902. nodeLinkFn.transclude = childTranscludeFn;
  8903. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8904. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8905. return nodeLinkFn;
  8906. ////////////////////
  8907. function addLinkFns(pre, post, attrStart, attrEnd) {
  8908. if (pre) {
  8909. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8910. pre.require = directive.require;
  8911. pre.directiveName = directiveName;
  8912. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8913. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8914. }
  8915. preLinkFns.push(pre);
  8916. }
  8917. if (post) {
  8918. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8919. post.require = directive.require;
  8920. post.directiveName = directiveName;
  8921. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8922. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8923. }
  8924. postLinkFns.push(post);
  8925. }
  8926. }
  8927. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8928. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8929. attrs, scopeBindingInfo;
  8930. if (compileNode === linkNode) {
  8931. attrs = templateAttrs;
  8932. $element = templateAttrs.$$element;
  8933. } else {
  8934. $element = jqLite(linkNode);
  8935. attrs = new Attributes($element, templateAttrs);
  8936. }
  8937. controllerScope = scope;
  8938. if (newIsolateScopeDirective) {
  8939. isolateScope = scope.$new(true);
  8940. } else if (newScopeDirective) {
  8941. controllerScope = scope.$parent;
  8942. }
  8943. if (boundTranscludeFn) {
  8944. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8945. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8946. transcludeFn = controllersBoundTransclude;
  8947. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8948. // expose the slots on the `$transclude` function
  8949. transcludeFn.isSlotFilled = function(slotName) {
  8950. return !!boundTranscludeFn.$$slots[slotName];
  8951. };
  8952. }
  8953. if (controllerDirectives) {
  8954. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8955. }
  8956. if (newIsolateScopeDirective) {
  8957. // Initialize isolate scope bindings for new isolate scope directive.
  8958. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8959. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8960. compile.$$addScopeClass($element, true);
  8961. isolateScope.$$isolateBindings =
  8962. newIsolateScopeDirective.$$isolateBindings;
  8963. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8964. isolateScope.$$isolateBindings,
  8965. newIsolateScopeDirective);
  8966. if (scopeBindingInfo.removeWatches) {
  8967. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8968. }
  8969. }
  8970. // Initialize bindToController bindings
  8971. for (var name in elementControllers) {
  8972. var controllerDirective = controllerDirectives[name];
  8973. var controller = elementControllers[name];
  8974. var bindings = controllerDirective.$$bindings.bindToController;
  8975. if (preAssignBindingsEnabled) {
  8976. if (bindings) {
  8977. controller.bindingInfo =
  8978. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8979. } else {
  8980. controller.bindingInfo = {};
  8981. }
  8982. var controllerResult = controller();
  8983. if (controllerResult !== controller.instance) {
  8984. // If the controller constructor has a return value, overwrite the instance
  8985. // from setupControllers
  8986. controller.instance = controllerResult;
  8987. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8988. if (controller.bindingInfo.removeWatches) {
  8989. controller.bindingInfo.removeWatches();
  8990. }
  8991. controller.bindingInfo =
  8992. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8993. }
  8994. } else {
  8995. controller.instance = controller();
  8996. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8997. controller.bindingInfo =
  8998. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8999. }
  9000. }
  9001. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  9002. forEach(controllerDirectives, function(controllerDirective, name) {
  9003. var require = controllerDirective.require;
  9004. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  9005. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  9006. }
  9007. });
  9008. // Handle the init and destroy lifecycle hooks on all controllers that have them
  9009. forEach(elementControllers, function(controller) {
  9010. var controllerInstance = controller.instance;
  9011. if (isFunction(controllerInstance.$onChanges)) {
  9012. try {
  9013. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  9014. } catch (e) {
  9015. $exceptionHandler(e);
  9016. }
  9017. }
  9018. if (isFunction(controllerInstance.$onInit)) {
  9019. try {
  9020. controllerInstance.$onInit();
  9021. } catch (e) {
  9022. $exceptionHandler(e);
  9023. }
  9024. }
  9025. if (isFunction(controllerInstance.$doCheck)) {
  9026. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  9027. controllerInstance.$doCheck();
  9028. }
  9029. if (isFunction(controllerInstance.$onDestroy)) {
  9030. controllerScope.$on('$destroy', function callOnDestroyHook() {
  9031. controllerInstance.$onDestroy();
  9032. });
  9033. }
  9034. });
  9035. // PRELINKING
  9036. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  9037. linkFn = preLinkFns[i];
  9038. invokeLinkFn(linkFn,
  9039. linkFn.isolateScope ? isolateScope : scope,
  9040. $element,
  9041. attrs,
  9042. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9043. transcludeFn
  9044. );
  9045. }
  9046. // RECURSION
  9047. // We only pass the isolate scope, if the isolate directive has a template,
  9048. // otherwise the child elements do not belong to the isolate directive.
  9049. var scopeToChild = scope;
  9050. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  9051. scopeToChild = isolateScope;
  9052. }
  9053. if (childLinkFn) {
  9054. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  9055. }
  9056. // POSTLINKING
  9057. for (i = postLinkFns.length - 1; i >= 0; i--) {
  9058. linkFn = postLinkFns[i];
  9059. invokeLinkFn(linkFn,
  9060. linkFn.isolateScope ? isolateScope : scope,
  9061. $element,
  9062. attrs,
  9063. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9064. transcludeFn
  9065. );
  9066. }
  9067. // Trigger $postLink lifecycle hooks
  9068. forEach(elementControllers, function(controller) {
  9069. var controllerInstance = controller.instance;
  9070. if (isFunction(controllerInstance.$postLink)) {
  9071. controllerInstance.$postLink();
  9072. }
  9073. });
  9074. // This is the function that is injected as `$transclude`.
  9075. // Note: all arguments are optional!
  9076. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  9077. var transcludeControllers;
  9078. // No scope passed in:
  9079. if (!isScope(scope)) {
  9080. slotName = futureParentElement;
  9081. futureParentElement = cloneAttachFn;
  9082. cloneAttachFn = scope;
  9083. scope = undefined;
  9084. }
  9085. if (hasElementTranscludeDirective) {
  9086. transcludeControllers = elementControllers;
  9087. }
  9088. if (!futureParentElement) {
  9089. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  9090. }
  9091. if (slotName) {
  9092. // slotTranscludeFn can be one of three things:
  9093. // * a transclude function - a filled slot
  9094. // * `null` - an optional slot that was not filled
  9095. // * `undefined` - a slot that was not declared (i.e. invalid)
  9096. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  9097. if (slotTranscludeFn) {
  9098. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9099. } else if (isUndefined(slotTranscludeFn)) {
  9100. throw $compileMinErr('noslot',
  9101. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  9102. 'Element: {1}',
  9103. slotName, startingTag($element));
  9104. }
  9105. } else {
  9106. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9107. }
  9108. }
  9109. }
  9110. }
  9111. function getControllers(directiveName, require, $element, elementControllers) {
  9112. var value;
  9113. if (isString(require)) {
  9114. var match = require.match(REQUIRE_PREFIX_REGEXP);
  9115. var name = require.substring(match[0].length);
  9116. var inheritType = match[1] || match[3];
  9117. var optional = match[2] === '?';
  9118. //If only parents then start at the parent element
  9119. if (inheritType === '^^') {
  9120. $element = $element.parent();
  9121. //Otherwise attempt getting the controller from elementControllers in case
  9122. //the element is transcluded (and has no data) and to avoid .data if possible
  9123. } else {
  9124. value = elementControllers && elementControllers[name];
  9125. value = value && value.instance;
  9126. }
  9127. if (!value) {
  9128. var dataName = '$' + name + 'Controller';
  9129. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  9130. }
  9131. if (!value && !optional) {
  9132. throw $compileMinErr('ctreq',
  9133. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  9134. name, directiveName);
  9135. }
  9136. } else if (isArray(require)) {
  9137. value = [];
  9138. for (var i = 0, ii = require.length; i < ii; i++) {
  9139. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  9140. }
  9141. } else if (isObject(require)) {
  9142. value = {};
  9143. forEach(require, function(controller, property) {
  9144. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  9145. });
  9146. }
  9147. return value || null;
  9148. }
  9149. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  9150. var elementControllers = createMap();
  9151. for (var controllerKey in controllerDirectives) {
  9152. var directive = controllerDirectives[controllerKey];
  9153. var locals = {
  9154. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  9155. $element: $element,
  9156. $attrs: attrs,
  9157. $transclude: transcludeFn
  9158. };
  9159. var controller = directive.controller;
  9160. if (controller === '@') {
  9161. controller = attrs[directive.name];
  9162. }
  9163. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  9164. // For directives with element transclusion the element is a comment.
  9165. // In this case .data will not attach any data.
  9166. // Instead, we save the controllers for the element in a local hash and attach to .data
  9167. // later, once we have the actual element.
  9168. elementControllers[directive.name] = controllerInstance;
  9169. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  9170. }
  9171. return elementControllers;
  9172. }
  9173. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  9174. // or child scope created. For instance:
  9175. // * if the directive has been pulled into a template because another directive with a higher priority
  9176. // asked for element transclusion
  9177. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  9178. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  9179. function markDirectiveScope(directives, isolateScope, newScope) {
  9180. for (var j = 0, jj = directives.length; j < jj; j++) {
  9181. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  9182. }
  9183. }
  9184. /**
  9185. * looks up the directive and decorates it with exception handling and proper parameters. We
  9186. * call this the boundDirective.
  9187. *
  9188. * @param {string} name name of the directive to look up.
  9189. * @param {string} location The directive must be found in specific format.
  9190. * String containing any of theses characters:
  9191. *
  9192. * * `E`: element name
  9193. * * `A': attribute
  9194. * * `C`: class
  9195. * * `M`: comment
  9196. * @returns {boolean} true if directive was added.
  9197. */
  9198. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9199. endAttrName) {
  9200. if (name === ignoreDirective) return null;
  9201. var match = null;
  9202. if (hasDirectives.hasOwnProperty(name)) {
  9203. for (var directive, directives = $injector.get(name + Suffix),
  9204. i = 0, ii = directives.length; i < ii; i++) {
  9205. directive = directives[i];
  9206. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9207. directive.restrict.indexOf(location) !== -1) {
  9208. if (startAttrName) {
  9209. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9210. }
  9211. if (!directive.$$bindings) {
  9212. var bindings = directive.$$bindings =
  9213. parseDirectiveBindings(directive, directive.name);
  9214. if (isObject(bindings.isolateScope)) {
  9215. directive.$$isolateBindings = bindings.isolateScope;
  9216. }
  9217. }
  9218. tDirectives.push(directive);
  9219. match = directive;
  9220. }
  9221. }
  9222. }
  9223. return match;
  9224. }
  9225. /**
  9226. * looks up the directive and returns true if it is a multi-element directive,
  9227. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9228. * together.
  9229. *
  9230. * @param {string} name name of the directive to look up.
  9231. * @returns true if directive was registered as multi-element.
  9232. */
  9233. function directiveIsMultiElement(name) {
  9234. if (hasDirectives.hasOwnProperty(name)) {
  9235. for (var directive, directives = $injector.get(name + Suffix),
  9236. i = 0, ii = directives.length; i < ii; i++) {
  9237. directive = directives[i];
  9238. if (directive.multiElement) {
  9239. return true;
  9240. }
  9241. }
  9242. }
  9243. return false;
  9244. }
  9245. /**
  9246. * When the element is replaced with HTML template then the new attributes
  9247. * on the template need to be merged with the existing attributes in the DOM.
  9248. * The desired effect is to have both of the attributes present.
  9249. *
  9250. * @param {object} dst destination attributes (original DOM)
  9251. * @param {object} src source attributes (from the directive template)
  9252. */
  9253. function mergeTemplateAttributes(dst, src) {
  9254. var srcAttr = src.$attr,
  9255. dstAttr = dst.$attr;
  9256. // reapply the old attributes to the new element
  9257. forEach(dst, function(value, key) {
  9258. if (key.charAt(0) !== '$') {
  9259. if (src[key] && src[key] !== value) {
  9260. if (value.length) {
  9261. value += (key === 'style' ? ';' : ' ') + src[key];
  9262. } else {
  9263. value = src[key];
  9264. }
  9265. }
  9266. dst.$set(key, value, true, srcAttr[key]);
  9267. }
  9268. });
  9269. // copy the new attributes on the old attrs object
  9270. forEach(src, function(value, key) {
  9271. // Check if we already set this attribute in the loop above.
  9272. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9273. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9274. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9275. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9276. dst[key] = value;
  9277. if (key !== 'class' && key !== 'style') {
  9278. dstAttr[key] = srcAttr[key];
  9279. }
  9280. }
  9281. });
  9282. }
  9283. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9284. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9285. var linkQueue = [],
  9286. afterTemplateNodeLinkFn,
  9287. afterTemplateChildLinkFn,
  9288. beforeTemplateCompileNode = $compileNode[0],
  9289. origAsyncDirective = directives.shift(),
  9290. derivedSyncDirective = inherit(origAsyncDirective, {
  9291. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9292. }),
  9293. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9294. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9295. : origAsyncDirective.templateUrl,
  9296. templateNamespace = origAsyncDirective.templateNamespace;
  9297. $compileNode.empty();
  9298. $templateRequest(templateUrl)
  9299. .then(function(content) {
  9300. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9301. content = denormalizeTemplate(content);
  9302. if (origAsyncDirective.replace) {
  9303. if (jqLiteIsTextNode(content)) {
  9304. $template = [];
  9305. } else {
  9306. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9307. }
  9308. compileNode = $template[0];
  9309. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9310. throw $compileMinErr('tplrt',
  9311. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9312. origAsyncDirective.name, templateUrl);
  9313. }
  9314. tempTemplateAttrs = {$attr: {}};
  9315. replaceWith($rootElement, $compileNode, compileNode);
  9316. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9317. if (isObject(origAsyncDirective.scope)) {
  9318. // the original directive that caused the template to be loaded async required
  9319. // an isolate scope
  9320. markDirectiveScope(templateDirectives, true);
  9321. }
  9322. directives = templateDirectives.concat(directives);
  9323. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9324. } else {
  9325. compileNode = beforeTemplateCompileNode;
  9326. $compileNode.html(content);
  9327. }
  9328. directives.unshift(derivedSyncDirective);
  9329. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9330. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9331. previousCompileContext);
  9332. forEach($rootElement, function(node, i) {
  9333. if (node === compileNode) {
  9334. $rootElement[i] = $compileNode[0];
  9335. }
  9336. });
  9337. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9338. while (linkQueue.length) {
  9339. var scope = linkQueue.shift(),
  9340. beforeTemplateLinkNode = linkQueue.shift(),
  9341. linkRootElement = linkQueue.shift(),
  9342. boundTranscludeFn = linkQueue.shift(),
  9343. linkNode = $compileNode[0];
  9344. if (scope.$$destroyed) continue;
  9345. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9346. var oldClasses = beforeTemplateLinkNode.className;
  9347. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9348. origAsyncDirective.replace)) {
  9349. // it was cloned therefore we have to clone as well.
  9350. linkNode = jqLiteClone(compileNode);
  9351. }
  9352. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9353. // Copy in CSS classes from original node
  9354. safeAddClass(jqLite(linkNode), oldClasses);
  9355. }
  9356. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9357. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9358. } else {
  9359. childBoundTranscludeFn = boundTranscludeFn;
  9360. }
  9361. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9362. childBoundTranscludeFn);
  9363. }
  9364. linkQueue = null;
  9365. }).catch(function(error) {
  9366. if (isError(error)) {
  9367. $exceptionHandler(error);
  9368. }
  9369. });
  9370. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9371. var childBoundTranscludeFn = boundTranscludeFn;
  9372. if (scope.$$destroyed) return;
  9373. if (linkQueue) {
  9374. linkQueue.push(scope,
  9375. node,
  9376. rootElement,
  9377. childBoundTranscludeFn);
  9378. } else {
  9379. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9380. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9381. }
  9382. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9383. }
  9384. };
  9385. }
  9386. /**
  9387. * Sorting function for bound directives.
  9388. */
  9389. function byPriority(a, b) {
  9390. var diff = b.priority - a.priority;
  9391. if (diff !== 0) return diff;
  9392. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9393. return a.index - b.index;
  9394. }
  9395. function assertNoDuplicate(what, previousDirective, directive, element) {
  9396. function wrapModuleNameIfDefined(moduleName) {
  9397. return moduleName ?
  9398. (' (module: ' + moduleName + ')') :
  9399. '';
  9400. }
  9401. if (previousDirective) {
  9402. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9403. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9404. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9405. }
  9406. }
  9407. function addTextInterpolateDirective(directives, text) {
  9408. var interpolateFn = $interpolate(text, true);
  9409. if (interpolateFn) {
  9410. directives.push({
  9411. priority: 0,
  9412. compile: function textInterpolateCompileFn(templateNode) {
  9413. var templateNodeParent = templateNode.parent(),
  9414. hasCompileParent = !!templateNodeParent.length;
  9415. // When transcluding a template that has bindings in the root
  9416. // we don't have a parent and thus need to add the class during linking fn.
  9417. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9418. return function textInterpolateLinkFn(scope, node) {
  9419. var parent = node.parent();
  9420. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9421. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9422. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9423. node[0].nodeValue = value;
  9424. });
  9425. };
  9426. }
  9427. });
  9428. }
  9429. }
  9430. function wrapTemplate(type, template) {
  9431. type = lowercase(type || 'html');
  9432. switch (type) {
  9433. case 'svg':
  9434. case 'math':
  9435. var wrapper = window.document.createElement('div');
  9436. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9437. return wrapper.childNodes[0].childNodes;
  9438. default:
  9439. return template;
  9440. }
  9441. }
  9442. function getTrustedContext(node, attrNormalizedName) {
  9443. if (attrNormalizedName === 'srcdoc') {
  9444. return $sce.HTML;
  9445. }
  9446. var tag = nodeName_(node);
  9447. // All tags with src attributes require a RESOURCE_URL value, except for
  9448. // img and various html5 media tags.
  9449. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9450. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9451. return $sce.RESOURCE_URL;
  9452. }
  9453. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9454. } else if (attrNormalizedName === 'xlinkHref' ||
  9455. (tag === 'form' && attrNormalizedName === 'action') ||
  9456. // links can be stylesheets or imports, which can run script in the current origin
  9457. (tag === 'link' && attrNormalizedName === 'href')
  9458. ) {
  9459. return $sce.RESOURCE_URL;
  9460. }
  9461. }
  9462. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9463. var trustedContext = getTrustedContext(node, name);
  9464. var mustHaveExpression = !isNgAttr;
  9465. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9466. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9467. // no interpolation found -> ignore
  9468. if (!interpolateFn) return;
  9469. if (name === 'multiple' && nodeName_(node) === 'select') {
  9470. throw $compileMinErr('selmulti',
  9471. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9472. startingTag(node));
  9473. }
  9474. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9475. throw $compileMinErr('nodomevents',
  9476. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9477. 'ng- versions (such as ng-click instead of onclick) instead.');
  9478. }
  9479. directives.push({
  9480. priority: 100,
  9481. compile: function() {
  9482. return {
  9483. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9484. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9485. // If the attribute has changed since last $interpolate()ed
  9486. var newValue = attr[name];
  9487. if (newValue !== value) {
  9488. // we need to interpolate again since the attribute value has been updated
  9489. // (e.g. by another directive's compile function)
  9490. // ensure unset/empty values make interpolateFn falsy
  9491. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9492. value = newValue;
  9493. }
  9494. // if attribute was updated so that there is no interpolation going on we don't want to
  9495. // register any observers
  9496. if (!interpolateFn) return;
  9497. // initialize attr object so that it's ready in case we need the value for isolate
  9498. // scope initialization, otherwise the value would not be available from isolate
  9499. // directive's linking fn during linking phase
  9500. attr[name] = interpolateFn(scope);
  9501. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9502. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9503. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9504. //special case for class attribute addition + removal
  9505. //so that class changes can tap into the animation
  9506. //hooks provided by the $animate service. Be sure to
  9507. //skip animations when the first digest occurs (when
  9508. //both the new and the old values are the same) since
  9509. //the CSS classes are the non-interpolated values
  9510. if (name === 'class' && newValue !== oldValue) {
  9511. attr.$updateClass(newValue, oldValue);
  9512. } else {
  9513. attr.$set(name, newValue);
  9514. }
  9515. });
  9516. }
  9517. };
  9518. }
  9519. });
  9520. }
  9521. /**
  9522. * This is a special jqLite.replaceWith, which can replace items which
  9523. * have no parents, provided that the containing jqLite collection is provided.
  9524. *
  9525. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9526. * in the root of the tree.
  9527. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9528. * the shell, but replace its DOM node reference.
  9529. * @param {Node} newNode The new DOM node.
  9530. */
  9531. function replaceWith($rootElement, elementsToRemove, newNode) {
  9532. var firstElementToRemove = elementsToRemove[0],
  9533. removeCount = elementsToRemove.length,
  9534. parent = firstElementToRemove.parentNode,
  9535. i, ii;
  9536. if ($rootElement) {
  9537. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9538. if ($rootElement[i] === firstElementToRemove) {
  9539. $rootElement[i++] = newNode;
  9540. for (var j = i, j2 = j + removeCount - 1,
  9541. jj = $rootElement.length;
  9542. j < jj; j++, j2++) {
  9543. if (j2 < jj) {
  9544. $rootElement[j] = $rootElement[j2];
  9545. } else {
  9546. delete $rootElement[j];
  9547. }
  9548. }
  9549. $rootElement.length -= removeCount - 1;
  9550. // If the replaced element is also the jQuery .context then replace it
  9551. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9552. // http://api.jquery.com/context/
  9553. if ($rootElement.context === firstElementToRemove) {
  9554. $rootElement.context = newNode;
  9555. }
  9556. break;
  9557. }
  9558. }
  9559. }
  9560. if (parent) {
  9561. parent.replaceChild(newNode, firstElementToRemove);
  9562. }
  9563. // Append all the `elementsToRemove` to a fragment. This will...
  9564. // - remove them from the DOM
  9565. // - allow them to still be traversed with .nextSibling
  9566. // - allow a single fragment.qSA to fetch all elements being removed
  9567. var fragment = window.document.createDocumentFragment();
  9568. for (i = 0; i < removeCount; i++) {
  9569. fragment.appendChild(elementsToRemove[i]);
  9570. }
  9571. if (jqLite.hasData(firstElementToRemove)) {
  9572. // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private
  9573. // data here because there's no public interface in jQuery to do that and copying over
  9574. // event listeners (which is the main use of private data) wouldn't work anyway.
  9575. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9576. // Remove $destroy event listeners from `firstElementToRemove`
  9577. jqLite(firstElementToRemove).off('$destroy');
  9578. }
  9579. // Cleanup any data/listeners on the elements and children.
  9580. // This includes invoking the $destroy event on any elements with listeners.
  9581. jqLite.cleanData(fragment.querySelectorAll('*'));
  9582. // Update the jqLite collection to only contain the `newNode`
  9583. for (i = 1; i < removeCount; i++) {
  9584. delete elementsToRemove[i];
  9585. }
  9586. elementsToRemove[0] = newNode;
  9587. elementsToRemove.length = 1;
  9588. }
  9589. function cloneAndAnnotateFn(fn, annotation) {
  9590. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9591. }
  9592. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9593. try {
  9594. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9595. } catch (e) {
  9596. $exceptionHandler(e, startingTag($element));
  9597. }
  9598. }
  9599. function strictBindingsCheck(attrName, directiveName) {
  9600. if (strictComponentBindingsEnabled) {
  9601. throw $compileMinErr('missingattr',
  9602. 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!',
  9603. attrName, directiveName);
  9604. }
  9605. }
  9606. // Set up $watches for isolate scope and controller bindings.
  9607. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9608. var removeWatchCollection = [];
  9609. var initialChanges = {};
  9610. var changes;
  9611. forEach(bindings, function initializeBinding(definition, scopeName) {
  9612. var attrName = definition.attrName,
  9613. optional = definition.optional,
  9614. mode = definition.mode, // @, =, <, or &
  9615. lastValue,
  9616. parentGet, parentSet, compare, removeWatch;
  9617. switch (mode) {
  9618. case '@':
  9619. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9620. strictBindingsCheck(attrName, directive.name);
  9621. destination[scopeName] = attrs[attrName] = undefined;
  9622. }
  9623. removeWatch = attrs.$observe(attrName, function(value) {
  9624. if (isString(value) || isBoolean(value)) {
  9625. var oldValue = destination[scopeName];
  9626. recordChanges(scopeName, value, oldValue);
  9627. destination[scopeName] = value;
  9628. }
  9629. });
  9630. attrs.$$observers[attrName].$$scope = scope;
  9631. lastValue = attrs[attrName];
  9632. if (isString(lastValue)) {
  9633. // If the attribute has been provided then we trigger an interpolation to ensure
  9634. // the value is there for use in the link fn
  9635. destination[scopeName] = $interpolate(lastValue)(scope);
  9636. } else if (isBoolean(lastValue)) {
  9637. // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted
  9638. // the value to boolean rather than a string, so we special case this situation
  9639. destination[scopeName] = lastValue;
  9640. }
  9641. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9642. removeWatchCollection.push(removeWatch);
  9643. break;
  9644. case '=':
  9645. if (!hasOwnProperty.call(attrs, attrName)) {
  9646. if (optional) break;
  9647. strictBindingsCheck(attrName, directive.name);
  9648. attrs[attrName] = undefined;
  9649. }
  9650. if (optional && !attrs[attrName]) break;
  9651. parentGet = $parse(attrs[attrName]);
  9652. if (parentGet.literal) {
  9653. compare = equals;
  9654. } else {
  9655. compare = simpleCompare;
  9656. }
  9657. parentSet = parentGet.assign || function() {
  9658. // reset the change, or we will throw this exception on every $digest
  9659. lastValue = destination[scopeName] = parentGet(scope);
  9660. throw $compileMinErr('nonassign',
  9661. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9662. attrs[attrName], attrName, directive.name);
  9663. };
  9664. lastValue = destination[scopeName] = parentGet(scope);
  9665. var parentValueWatch = function parentValueWatch(parentValue) {
  9666. if (!compare(parentValue, destination[scopeName])) {
  9667. // we are out of sync and need to copy
  9668. if (!compare(parentValue, lastValue)) {
  9669. // parent changed and it has precedence
  9670. destination[scopeName] = parentValue;
  9671. } else {
  9672. // if the parent can be assigned then do so
  9673. parentSet(scope, parentValue = destination[scopeName]);
  9674. }
  9675. }
  9676. lastValue = parentValue;
  9677. return lastValue;
  9678. };
  9679. parentValueWatch.$stateful = true;
  9680. if (definition.collection) {
  9681. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9682. } else {
  9683. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9684. }
  9685. removeWatchCollection.push(removeWatch);
  9686. break;
  9687. case '<':
  9688. if (!hasOwnProperty.call(attrs, attrName)) {
  9689. if (optional) break;
  9690. strictBindingsCheck(attrName, directive.name);
  9691. attrs[attrName] = undefined;
  9692. }
  9693. if (optional && !attrs[attrName]) break;
  9694. parentGet = $parse(attrs[attrName]);
  9695. var deepWatch = parentGet.literal;
  9696. var initialValue = destination[scopeName] = parentGet(scope);
  9697. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9698. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9699. if (oldValue === newValue) {
  9700. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9701. return;
  9702. }
  9703. oldValue = initialValue;
  9704. }
  9705. recordChanges(scopeName, newValue, oldValue);
  9706. destination[scopeName] = newValue;
  9707. }, deepWatch);
  9708. removeWatchCollection.push(removeWatch);
  9709. break;
  9710. case '&':
  9711. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9712. strictBindingsCheck(attrName, directive.name);
  9713. }
  9714. // Don't assign Object.prototype method to scope
  9715. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9716. // Don't assign noop to destination if expression is not valid
  9717. if (parentGet === noop && optional) break;
  9718. destination[scopeName] = function(locals) {
  9719. return parentGet(scope, locals);
  9720. };
  9721. break;
  9722. }
  9723. });
  9724. function recordChanges(key, currentValue, previousValue) {
  9725. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  9726. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9727. if (!onChangesQueue) {
  9728. scope.$$postDigest(flushOnChangesQueue);
  9729. onChangesQueue = [];
  9730. }
  9731. // If we have not already queued a trigger of onChanges for this controller then do so now
  9732. if (!changes) {
  9733. changes = {};
  9734. onChangesQueue.push(triggerOnChangesHook);
  9735. }
  9736. // If the has been a change on this property already then we need to reuse the previous value
  9737. if (changes[key]) {
  9738. previousValue = changes[key].previousValue;
  9739. }
  9740. // Store this change
  9741. changes[key] = new SimpleChange(previousValue, currentValue);
  9742. }
  9743. }
  9744. function triggerOnChangesHook() {
  9745. destination.$onChanges(changes);
  9746. // Now clear the changes so that we schedule onChanges when more changes arrive
  9747. changes = undefined;
  9748. }
  9749. return {
  9750. initialChanges: initialChanges,
  9751. removeWatches: removeWatchCollection.length && function removeWatches() {
  9752. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9753. removeWatchCollection[i]();
  9754. }
  9755. }
  9756. };
  9757. }
  9758. }];
  9759. }
  9760. function SimpleChange(previous, current) {
  9761. this.previousValue = previous;
  9762. this.currentValue = current;
  9763. }
  9764. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9765. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9766. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9767. /**
  9768. * Converts all accepted directives format into proper directive name.
  9769. * @param name Name to normalize
  9770. */
  9771. function directiveNormalize(name) {
  9772. return name
  9773. .replace(PREFIX_REGEXP, '')
  9774. .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) {
  9775. return offset ? letter.toUpperCase() : letter;
  9776. });
  9777. }
  9778. /**
  9779. * @ngdoc type
  9780. * @name $compile.directive.Attributes
  9781. *
  9782. * @description
  9783. * A shared object between directive compile / linking functions which contains normalized DOM
  9784. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9785. * needed since all of these are treated as equivalent in AngularJS:
  9786. *
  9787. * ```
  9788. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9789. * ```
  9790. */
  9791. /**
  9792. * @ngdoc property
  9793. * @name $compile.directive.Attributes#$attr
  9794. *
  9795. * @description
  9796. * A map of DOM element attribute names to the normalized name. This is
  9797. * needed to do reverse lookup from normalized name back to actual name.
  9798. */
  9799. /**
  9800. * @ngdoc method
  9801. * @name $compile.directive.Attributes#$set
  9802. * @kind function
  9803. *
  9804. * @description
  9805. * Set DOM element attribute value.
  9806. *
  9807. *
  9808. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9809. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9810. * property to the original name.
  9811. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9812. */
  9813. /**
  9814. * Closure compiler type information
  9815. */
  9816. function nodesetLinkingFn(
  9817. /* angular.Scope */ scope,
  9818. /* NodeList */ nodeList,
  9819. /* Element */ rootElement,
  9820. /* function(Function) */ boundTranscludeFn
  9821. ) {}
  9822. function directiveLinkingFn(
  9823. /* nodesetLinkingFn */ nodesetLinkingFn,
  9824. /* angular.Scope */ scope,
  9825. /* Node */ node,
  9826. /* Element */ rootElement,
  9827. /* function(Function) */ boundTranscludeFn
  9828. ) {}
  9829. function tokenDifference(str1, str2) {
  9830. var values = '',
  9831. tokens1 = str1.split(/\s+/),
  9832. tokens2 = str2.split(/\s+/);
  9833. outer:
  9834. for (var i = 0; i < tokens1.length; i++) {
  9835. var token = tokens1[i];
  9836. for (var j = 0; j < tokens2.length; j++) {
  9837. if (token === tokens2[j]) continue outer;
  9838. }
  9839. values += (values.length > 0 ? ' ' : '') + token;
  9840. }
  9841. return values;
  9842. }
  9843. function removeComments(jqNodes) {
  9844. jqNodes = jqLite(jqNodes);
  9845. var i = jqNodes.length;
  9846. if (i <= 1) {
  9847. return jqNodes;
  9848. }
  9849. while (i--) {
  9850. var node = jqNodes[i];
  9851. if (node.nodeType === NODE_TYPE_COMMENT ||
  9852. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9853. splice.call(jqNodes, i, 1);
  9854. }
  9855. }
  9856. return jqNodes;
  9857. }
  9858. var $controllerMinErr = minErr('$controller');
  9859. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9860. function identifierForController(controller, ident) {
  9861. if (ident && isString(ident)) return ident;
  9862. if (isString(controller)) {
  9863. var match = CNTRL_REG.exec(controller);
  9864. if (match) return match[3];
  9865. }
  9866. }
  9867. /**
  9868. * @ngdoc provider
  9869. * @name $controllerProvider
  9870. * @this
  9871. *
  9872. * @description
  9873. * The {@link ng.$controller $controller service} is used by AngularJS to create new
  9874. * controllers.
  9875. *
  9876. * This provider allows controller registration via the
  9877. * {@link ng.$controllerProvider#register register} method.
  9878. */
  9879. function $ControllerProvider() {
  9880. var controllers = {},
  9881. globals = false;
  9882. /**
  9883. * @ngdoc method
  9884. * @name $controllerProvider#has
  9885. * @param {string} name Controller name to check.
  9886. */
  9887. this.has = function(name) {
  9888. return controllers.hasOwnProperty(name);
  9889. };
  9890. /**
  9891. * @ngdoc method
  9892. * @name $controllerProvider#register
  9893. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9894. * the names and the values are the constructors.
  9895. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9896. * annotations in the array notation).
  9897. */
  9898. this.register = function(name, constructor) {
  9899. assertNotHasOwnProperty(name, 'controller');
  9900. if (isObject(name)) {
  9901. extend(controllers, name);
  9902. } else {
  9903. controllers[name] = constructor;
  9904. }
  9905. };
  9906. /**
  9907. * @ngdoc method
  9908. * @name $controllerProvider#allowGlobals
  9909. * @description If called, allows `$controller` to find controller constructors on `window`
  9910. *
  9911. * @deprecated
  9912. * sinceVersion="v1.3.0"
  9913. * removeVersion="v1.7.0"
  9914. * This method of finding controllers has been deprecated.
  9915. */
  9916. this.allowGlobals = function() {
  9917. globals = true;
  9918. };
  9919. this.$get = ['$injector', '$window', function($injector, $window) {
  9920. /**
  9921. * @ngdoc service
  9922. * @name $controller
  9923. * @requires $injector
  9924. *
  9925. * @param {Function|string} constructor If called with a function then it's considered to be the
  9926. * controller constructor function. Otherwise it's considered to be a string which is used
  9927. * to retrieve the controller constructor using the following steps:
  9928. *
  9929. * * check if a controller with given name is registered via `$controllerProvider`
  9930. * * check if evaluating the string on the current scope returns a constructor
  9931. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9932. * `window` object (deprecated, not recommended)
  9933. *
  9934. * The string can use the `controller as property` syntax, where the controller instance is published
  9935. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9936. * to work correctly.
  9937. *
  9938. * @param {Object} locals Injection locals for Controller.
  9939. * @return {Object} Instance of given controller.
  9940. *
  9941. * @description
  9942. * `$controller` service is responsible for instantiating controllers.
  9943. *
  9944. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9945. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9946. */
  9947. return function $controller(expression, locals, later, ident) {
  9948. // PRIVATE API:
  9949. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9950. // If true, $controller will allocate the object with the correct
  9951. // prototype chain, but will not invoke the controller until a returned
  9952. // callback is invoked.
  9953. // param `ident` --- An optional label which overrides the label parsed from the controller
  9954. // expression, if any.
  9955. var instance, match, constructor, identifier;
  9956. later = later === true;
  9957. if (ident && isString(ident)) {
  9958. identifier = ident;
  9959. }
  9960. if (isString(expression)) {
  9961. match = expression.match(CNTRL_REG);
  9962. if (!match) {
  9963. throw $controllerMinErr('ctrlfmt',
  9964. 'Badly formed controller string \'{0}\'. ' +
  9965. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9966. }
  9967. constructor = match[1];
  9968. identifier = identifier || match[3];
  9969. expression = controllers.hasOwnProperty(constructor)
  9970. ? controllers[constructor]
  9971. : getter(locals.$scope, constructor, true) ||
  9972. (globals ? getter($window, constructor, true) : undefined);
  9973. if (!expression) {
  9974. throw $controllerMinErr('ctrlreg',
  9975. 'The controller with the name \'{0}\' is not registered.', constructor);
  9976. }
  9977. assertArgFn(expression, constructor, true);
  9978. }
  9979. if (later) {
  9980. // Instantiate controller later:
  9981. // This machinery is used to create an instance of the object before calling the
  9982. // controller's constructor itself.
  9983. //
  9984. // This allows properties to be added to the controller before the constructor is
  9985. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9986. //
  9987. // This feature is not intended for use by applications, and is thus not documented
  9988. // publicly.
  9989. // Object creation: http://jsperf.com/create-constructor/2
  9990. var controllerPrototype = (isArray(expression) ?
  9991. expression[expression.length - 1] : expression).prototype;
  9992. instance = Object.create(controllerPrototype || null);
  9993. if (identifier) {
  9994. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9995. }
  9996. return extend(function $controllerInit() {
  9997. var result = $injector.invoke(expression, instance, locals, constructor);
  9998. if (result !== instance && (isObject(result) || isFunction(result))) {
  9999. instance = result;
  10000. if (identifier) {
  10001. // If result changed, re-assign controllerAs value to scope.
  10002. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10003. }
  10004. }
  10005. return instance;
  10006. }, {
  10007. instance: instance,
  10008. identifier: identifier
  10009. });
  10010. }
  10011. instance = $injector.instantiate(expression, locals, constructor);
  10012. if (identifier) {
  10013. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10014. }
  10015. return instance;
  10016. };
  10017. function addIdentifier(locals, identifier, instance, name) {
  10018. if (!(locals && isObject(locals.$scope))) {
  10019. throw minErr('$controller')('noscp',
  10020. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  10021. name, identifier);
  10022. }
  10023. locals.$scope[identifier] = instance;
  10024. }
  10025. }];
  10026. }
  10027. /**
  10028. * @ngdoc service
  10029. * @name $document
  10030. * @requires $window
  10031. * @this
  10032. *
  10033. * @description
  10034. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  10035. *
  10036. * @example
  10037. <example module="documentExample" name="document">
  10038. <file name="index.html">
  10039. <div ng-controller="ExampleController">
  10040. <p>$document title: <b ng-bind="title"></b></p>
  10041. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  10042. </div>
  10043. </file>
  10044. <file name="script.js">
  10045. angular.module('documentExample', [])
  10046. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  10047. $scope.title = $document[0].title;
  10048. $scope.windowTitle = angular.element(window.document)[0].title;
  10049. }]);
  10050. </file>
  10051. </example>
  10052. */
  10053. function $DocumentProvider() {
  10054. this.$get = ['$window', function(window) {
  10055. return jqLite(window.document);
  10056. }];
  10057. }
  10058. /**
  10059. * @private
  10060. * @this
  10061. * Listens for document visibility change and makes the current status accessible.
  10062. */
  10063. function $$IsDocumentHiddenProvider() {
  10064. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  10065. var doc = $document[0];
  10066. var hidden = doc && doc.hidden;
  10067. $document.on('visibilitychange', changeListener);
  10068. $rootScope.$on('$destroy', function() {
  10069. $document.off('visibilitychange', changeListener);
  10070. });
  10071. function changeListener() {
  10072. hidden = doc.hidden;
  10073. }
  10074. return function() {
  10075. return hidden;
  10076. };
  10077. }];
  10078. }
  10079. /**
  10080. * @ngdoc service
  10081. * @name $exceptionHandler
  10082. * @requires ng.$log
  10083. * @this
  10084. *
  10085. * @description
  10086. * Any uncaught exception in AngularJS expressions is delegated to this service.
  10087. * The default implementation simply delegates to `$log.error` which logs it into
  10088. * the browser console.
  10089. *
  10090. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  10091. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  10092. *
  10093. * ## Example:
  10094. *
  10095. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  10096. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  10097. * of `$log.error()`.
  10098. *
  10099. * ```js
  10100. * angular.
  10101. * module('exceptionOverwrite', []).
  10102. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  10103. * return function myExceptionHandler(exception, cause) {
  10104. * logErrorsToBackend(exception, cause);
  10105. * $log.warn(exception, cause);
  10106. * };
  10107. * }]);
  10108. * ```
  10109. *
  10110. * <hr />
  10111. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  10112. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  10113. * (unless executed during a digest).
  10114. *
  10115. * If you wish, you can manually delegate exceptions, e.g.
  10116. * `try { ... } catch(e) { $exceptionHandler(e); }`
  10117. *
  10118. * @param {Error} exception Exception associated with the error.
  10119. * @param {string=} cause Optional information about the context in which
  10120. * the error was thrown.
  10121. *
  10122. */
  10123. function $ExceptionHandlerProvider() {
  10124. this.$get = ['$log', function($log) {
  10125. return function(exception, cause) {
  10126. $log.error.apply($log, arguments);
  10127. };
  10128. }];
  10129. }
  10130. var $$ForceReflowProvider = /** @this */ function() {
  10131. this.$get = ['$document', function($document) {
  10132. return function(domNode) {
  10133. //the line below will force the browser to perform a repaint so
  10134. //that all the animated elements within the animation frame will
  10135. //be properly updated and drawn on screen. This is required to
  10136. //ensure that the preparation animation is properly flushed so that
  10137. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  10138. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  10139. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  10140. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  10141. if (domNode) {
  10142. if (!domNode.nodeType && domNode instanceof jqLite) {
  10143. domNode = domNode[0];
  10144. }
  10145. } else {
  10146. domNode = $document[0].body;
  10147. }
  10148. return domNode.offsetWidth + 1;
  10149. };
  10150. }];
  10151. };
  10152. var APPLICATION_JSON = 'application/json';
  10153. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  10154. var JSON_START = /^\[|^\{(?!\{)/;
  10155. var JSON_ENDS = {
  10156. '[': /]$/,
  10157. '{': /}$/
  10158. };
  10159. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  10160. var $httpMinErr = minErr('$http');
  10161. function serializeValue(v) {
  10162. if (isObject(v)) {
  10163. return isDate(v) ? v.toISOString() : toJson(v);
  10164. }
  10165. return v;
  10166. }
  10167. /** @this */
  10168. function $HttpParamSerializerProvider() {
  10169. /**
  10170. * @ngdoc service
  10171. * @name $httpParamSerializer
  10172. * @description
  10173. *
  10174. * Default {@link $http `$http`} params serializer that converts objects to strings
  10175. * according to the following rules:
  10176. *
  10177. * * `{'foo': 'bar'}` results in `foo=bar`
  10178. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  10179. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  10180. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  10181. *
  10182. * Note that serializer will sort the request parameters alphabetically.
  10183. * */
  10184. this.$get = function() {
  10185. return function ngParamSerializer(params) {
  10186. if (!params) return '';
  10187. var parts = [];
  10188. forEachSorted(params, function(value, key) {
  10189. if (value === null || isUndefined(value) || isFunction(value)) return;
  10190. if (isArray(value)) {
  10191. forEach(value, function(v) {
  10192. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  10193. });
  10194. } else {
  10195. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  10196. }
  10197. });
  10198. return parts.join('&');
  10199. };
  10200. };
  10201. }
  10202. /** @this */
  10203. function $HttpParamSerializerJQLikeProvider() {
  10204. /**
  10205. * @ngdoc service
  10206. * @name $httpParamSerializerJQLike
  10207. *
  10208. * @description
  10209. *
  10210. * Alternative {@link $http `$http`} params serializer that follows
  10211. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10212. * The serializer will also sort the params alphabetically.
  10213. *
  10214. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10215. *
  10216. * ```js
  10217. * $http({
  10218. * url: myUrl,
  10219. * method: 'GET',
  10220. * params: myParams,
  10221. * paramSerializer: '$httpParamSerializerJQLike'
  10222. * });
  10223. * ```
  10224. *
  10225. * It is also possible to set it as the default `paramSerializer` in the
  10226. * {@link $httpProvider#defaults `$httpProvider`}.
  10227. *
  10228. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10229. * form data for submission:
  10230. *
  10231. * ```js
  10232. * .controller(function($http, $httpParamSerializerJQLike) {
  10233. * //...
  10234. *
  10235. * $http({
  10236. * url: myUrl,
  10237. * method: 'POST',
  10238. * data: $httpParamSerializerJQLike(myData),
  10239. * headers: {
  10240. * 'Content-Type': 'application/x-www-form-urlencoded'
  10241. * }
  10242. * });
  10243. *
  10244. * });
  10245. * ```
  10246. *
  10247. * */
  10248. this.$get = function() {
  10249. return function jQueryLikeParamSerializer(params) {
  10250. if (!params) return '';
  10251. var parts = [];
  10252. serialize(params, '', true);
  10253. return parts.join('&');
  10254. function serialize(toSerialize, prefix, topLevel) {
  10255. if (toSerialize === null || isUndefined(toSerialize)) return;
  10256. if (isArray(toSerialize)) {
  10257. forEach(toSerialize, function(value, index) {
  10258. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10259. });
  10260. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10261. forEachSorted(toSerialize, function(value, key) {
  10262. serialize(value, prefix +
  10263. (topLevel ? '' : '[') +
  10264. key +
  10265. (topLevel ? '' : ']'));
  10266. });
  10267. } else {
  10268. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  10269. }
  10270. }
  10271. };
  10272. };
  10273. }
  10274. function defaultHttpResponseTransform(data, headers) {
  10275. if (isString(data)) {
  10276. // Strip json vulnerability protection prefix and trim whitespace
  10277. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10278. if (tempData) {
  10279. var contentType = headers('Content-Type');
  10280. var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);
  10281. if (hasJsonContentType || isJsonLike(tempData)) {
  10282. try {
  10283. data = fromJson(tempData);
  10284. } catch (e) {
  10285. if (!hasJsonContentType) {
  10286. return data;
  10287. }
  10288. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10289. 'Parse error: "{1}"', data, e);
  10290. }
  10291. }
  10292. }
  10293. }
  10294. return data;
  10295. }
  10296. function isJsonLike(str) {
  10297. var jsonStart = str.match(JSON_START);
  10298. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10299. }
  10300. /**
  10301. * Parse headers into key value object
  10302. *
  10303. * @param {string} headers Raw headers as a string
  10304. * @returns {Object} Parsed headers as key value object
  10305. */
  10306. function parseHeaders(headers) {
  10307. var parsed = createMap(), i;
  10308. function fillInParsed(key, val) {
  10309. if (key) {
  10310. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10311. }
  10312. }
  10313. if (isString(headers)) {
  10314. forEach(headers.split('\n'), function(line) {
  10315. i = line.indexOf(':');
  10316. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10317. });
  10318. } else if (isObject(headers)) {
  10319. forEach(headers, function(headerVal, headerKey) {
  10320. fillInParsed(lowercase(headerKey), trim(headerVal));
  10321. });
  10322. }
  10323. return parsed;
  10324. }
  10325. /**
  10326. * Returns a function that provides access to parsed headers.
  10327. *
  10328. * Headers are lazy parsed when first requested.
  10329. * @see parseHeaders
  10330. *
  10331. * @param {(string|Object)} headers Headers to provide access to.
  10332. * @returns {function(string=)} Returns a getter function which if called with:
  10333. *
  10334. * - if called with an argument returns a single header value or null
  10335. * - if called with no arguments returns an object containing all headers.
  10336. */
  10337. function headersGetter(headers) {
  10338. var headersObj;
  10339. return function(name) {
  10340. if (!headersObj) headersObj = parseHeaders(headers);
  10341. if (name) {
  10342. var value = headersObj[lowercase(name)];
  10343. if (value === undefined) {
  10344. value = null;
  10345. }
  10346. return value;
  10347. }
  10348. return headersObj;
  10349. };
  10350. }
  10351. /**
  10352. * Chain all given functions
  10353. *
  10354. * This function is used for both request and response transforming
  10355. *
  10356. * @param {*} data Data to transform.
  10357. * @param {function(string=)} headers HTTP headers getter fn.
  10358. * @param {number} status HTTP status code of the response.
  10359. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10360. * @returns {*} Transformed data.
  10361. */
  10362. function transformData(data, headers, status, fns) {
  10363. if (isFunction(fns)) {
  10364. return fns(data, headers, status);
  10365. }
  10366. forEach(fns, function(fn) {
  10367. data = fn(data, headers, status);
  10368. });
  10369. return data;
  10370. }
  10371. function isSuccess(status) {
  10372. return 200 <= status && status < 300;
  10373. }
  10374. /**
  10375. * @ngdoc provider
  10376. * @name $httpProvider
  10377. * @this
  10378. *
  10379. * @description
  10380. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10381. * */
  10382. function $HttpProvider() {
  10383. /**
  10384. * @ngdoc property
  10385. * @name $httpProvider#defaults
  10386. * @description
  10387. *
  10388. * Object containing default values for all {@link ng.$http $http} requests.
  10389. *
  10390. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10391. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10392. * by default. See {@link $http#caching $http Caching} for more information.
  10393. *
  10394. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10395. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10396. * setting default headers.
  10397. * - **`defaults.headers.common`**
  10398. * - **`defaults.headers.post`**
  10399. * - **`defaults.headers.put`**
  10400. * - **`defaults.headers.patch`**
  10401. *
  10402. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10403. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10404. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10405. *
  10406. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10407. * used to the prepare string representation of request parameters (specified as an object).
  10408. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10409. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10410. *
  10411. * - **`defaults.transformRequest`** -
  10412. * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` -
  10413. * An array of functions (or a single function) which are applied to the request data.
  10414. * By default, this is an array with one request transformation function:
  10415. *
  10416. * - If the `data` property of the request configuration object contains an object, serialize it
  10417. * into JSON format.
  10418. *
  10419. * - **`defaults.transformResponse`** -
  10420. * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` -
  10421. * An array of functions (or a single function) which are applied to the response data. By default,
  10422. * this is an array which applies one response transformation function that does two things:
  10423. *
  10424. * - If XSRF prefix is detected, strip it
  10425. * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).
  10426. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10427. * deserialize it using a JSON parser.
  10428. *
  10429. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10430. * Defaults value is `'XSRF-TOKEN'`.
  10431. *
  10432. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10433. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10434. *
  10435. **/
  10436. var defaults = this.defaults = {
  10437. // transform incoming response data
  10438. transformResponse: [defaultHttpResponseTransform],
  10439. // transform outgoing request data
  10440. transformRequest: [function(d) {
  10441. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10442. }],
  10443. // default headers
  10444. headers: {
  10445. common: {
  10446. 'Accept': 'application/json, text/plain, */*'
  10447. },
  10448. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10449. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10450. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10451. },
  10452. xsrfCookieName: 'XSRF-TOKEN',
  10453. xsrfHeaderName: 'X-XSRF-TOKEN',
  10454. paramSerializer: '$httpParamSerializer',
  10455. jsonpCallbackParam: 'callback'
  10456. };
  10457. var useApplyAsync = false;
  10458. /**
  10459. * @ngdoc method
  10460. * @name $httpProvider#useApplyAsync
  10461. * @description
  10462. *
  10463. * Configure $http service to combine processing of multiple http responses received at around
  10464. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10465. * significant performance improvement for bigger applications that make many HTTP requests
  10466. * concurrently (common during application bootstrap).
  10467. *
  10468. * Defaults to false. If no value is specified, returns the current configured value.
  10469. *
  10470. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10471. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10472. * to load and share the same digest cycle.
  10473. *
  10474. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10475. * otherwise, returns the current configured value.
  10476. **/
  10477. this.useApplyAsync = function(value) {
  10478. if (isDefined(value)) {
  10479. useApplyAsync = !!value;
  10480. return this;
  10481. }
  10482. return useApplyAsync;
  10483. };
  10484. /**
  10485. * @ngdoc property
  10486. * @name $httpProvider#interceptors
  10487. * @description
  10488. *
  10489. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10490. * pre-processing of request or postprocessing of responses.
  10491. *
  10492. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10493. * array, on request, but reverse order, on response.
  10494. *
  10495. * {@link ng.$http#interceptors Interceptors detailed info}
  10496. **/
  10497. var interceptorFactories = this.interceptors = [];
  10498. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10499. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10500. var defaultCache = $cacheFactory('$http');
  10501. /**
  10502. * Make sure that default param serializer is exposed as a function
  10503. */
  10504. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10505. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10506. /**
  10507. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10508. * The reversal is needed so that we can build up the interception chain around the
  10509. * server request.
  10510. */
  10511. var reversedInterceptors = [];
  10512. forEach(interceptorFactories, function(interceptorFactory) {
  10513. reversedInterceptors.unshift(isString(interceptorFactory)
  10514. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10515. });
  10516. /**
  10517. * @ngdoc service
  10518. * @kind function
  10519. * @name $http
  10520. * @requires ng.$httpBackend
  10521. * @requires $cacheFactory
  10522. * @requires $rootScope
  10523. * @requires $q
  10524. * @requires $injector
  10525. *
  10526. * @description
  10527. * The `$http` service is a core AngularJS service that facilitates communication with the remote
  10528. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10529. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10530. *
  10531. * For unit testing applications that use `$http` service, see
  10532. * {@link ngMock.$httpBackend $httpBackend mock}.
  10533. *
  10534. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10535. * $resource} service.
  10536. *
  10537. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10538. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10539. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10540. *
  10541. *
  10542. * ## General usage
  10543. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10544. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10545. *
  10546. * ```js
  10547. * // Simple GET request example:
  10548. * $http({
  10549. * method: 'GET',
  10550. * url: '/someUrl'
  10551. * }).then(function successCallback(response) {
  10552. * // this callback will be called asynchronously
  10553. * // when the response is available
  10554. * }, function errorCallback(response) {
  10555. * // called asynchronously if an error occurs
  10556. * // or server returns response with an error status.
  10557. * });
  10558. * ```
  10559. *
  10560. * The response object has these properties:
  10561. *
  10562. * - **data** – `{string|Object}` – The response body transformed with the transform
  10563. * functions.
  10564. * - **status** – `{number}` – HTTP status code of the response.
  10565. * - **headers** – `{function([headerName])}` – Header getter function.
  10566. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10567. * - **statusText** – `{string}` – HTTP status text of the response.
  10568. * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest (`complete`, `error`, `timeout` or `abort`).
  10569. *
  10570. * A response status code between 200 and 299 is considered a success status and will result in
  10571. * the success callback being called. Any response status code outside of that range is
  10572. * considered an error status and will result in the error callback being called.
  10573. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10574. * aborted, e.g. using a `config.timeout`.
  10575. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10576. * that the outcome (success or error) will be determined by the final response status code.
  10577. *
  10578. *
  10579. * ## Shortcut methods
  10580. *
  10581. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10582. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10583. * last argument.
  10584. *
  10585. * ```js
  10586. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10587. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10588. * ```
  10589. *
  10590. * Complete list of shortcut methods:
  10591. *
  10592. * - {@link ng.$http#get $http.get}
  10593. * - {@link ng.$http#head $http.head}
  10594. * - {@link ng.$http#post $http.post}
  10595. * - {@link ng.$http#put $http.put}
  10596. * - {@link ng.$http#delete $http.delete}
  10597. * - {@link ng.$http#jsonp $http.jsonp}
  10598. * - {@link ng.$http#patch $http.patch}
  10599. *
  10600. *
  10601. * ## Writing Unit Tests that use $http
  10602. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10603. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10604. * request using trained responses.
  10605. *
  10606. * ```
  10607. * $httpBackend.expectGET(...);
  10608. * $http.get(...);
  10609. * $httpBackend.flush();
  10610. * ```
  10611. *
  10612. * ## Setting HTTP Headers
  10613. *
  10614. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10615. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10616. * object, which currently contains this default configuration:
  10617. *
  10618. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10619. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10620. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10621. * - `Content-Type: application/json`
  10622. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10623. * - `Content-Type: application/json`
  10624. *
  10625. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10626. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10627. * with the lowercased HTTP method name as the key, e.g.
  10628. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10629. *
  10630. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10631. * fashion. For example:
  10632. *
  10633. * ```
  10634. * module.run(function($http) {
  10635. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10636. * });
  10637. * ```
  10638. *
  10639. * In addition, you can supply a `headers` property in the config object passed when
  10640. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10641. *
  10642. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10643. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10644. *
  10645. * ```js
  10646. * var req = {
  10647. * method: 'POST',
  10648. * url: 'http://example.com',
  10649. * headers: {
  10650. * 'Content-Type': undefined
  10651. * },
  10652. * data: { test: 'test' }
  10653. * }
  10654. *
  10655. * $http(req).then(function(){...}, function(){...});
  10656. * ```
  10657. *
  10658. * ## Transforming Requests and Responses
  10659. *
  10660. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10661. * and `transformResponse`. These properties can be a single function that returns
  10662. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10663. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10664. *
  10665. * <div class="alert alert-warning">
  10666. * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10667. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10668. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10669. * function will be reflected on the scope and in any templates where the object is data-bound.
  10670. * To prevent this, transform functions should have no side-effects.
  10671. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10672. * </div>
  10673. *
  10674. * ### Default Transformations
  10675. *
  10676. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10677. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10678. * then these will be applied.
  10679. *
  10680. * You can augment or replace the default transformations by modifying these properties by adding to or
  10681. * replacing the array.
  10682. *
  10683. * AngularJS provides the following default transformations:
  10684. *
  10685. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is
  10686. * an array with one function that does the following:
  10687. *
  10688. * - If the `data` property of the request configuration object contains an object, serialize it
  10689. * into JSON format.
  10690. *
  10691. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is
  10692. * an array with one function that does the following:
  10693. *
  10694. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10695. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10696. * deserialize it using a JSON parser.
  10697. *
  10698. *
  10699. * ### Overriding the Default Transformations Per Request
  10700. *
  10701. * If you wish to override the request/response transformations only for a single request then provide
  10702. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10703. * into `$http`.
  10704. *
  10705. * Note that if you provide these properties on the config object the default transformations will be
  10706. * overwritten. If you wish to augment the default transformations then you must include them in your
  10707. * local transformation array.
  10708. *
  10709. * The following code demonstrates adding a new response transformation to be run after the default response
  10710. * transformations have been run.
  10711. *
  10712. * ```js
  10713. * function appendTransform(defaults, transform) {
  10714. *
  10715. * // We can't guarantee that the default transformation is an array
  10716. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10717. *
  10718. * // Append the new transformation to the defaults
  10719. * return defaults.concat(transform);
  10720. * }
  10721. *
  10722. * $http({
  10723. * url: '...',
  10724. * method: 'GET',
  10725. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10726. * return doTransform(value);
  10727. * })
  10728. * });
  10729. * ```
  10730. *
  10731. *
  10732. * ## Caching
  10733. *
  10734. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10735. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10736. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10737. * precedence over the default cache value.
  10738. *
  10739. * In order to:
  10740. * * cache all responses - set the default cache value to TRUE or to a cache object
  10741. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10742. *
  10743. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10744. * then the default `$cacheFactory("$http")` object is used.
  10745. *
  10746. * The default cache value can be set by updating the
  10747. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10748. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10749. *
  10750. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10751. * the relevant cache object. The next time the same request is made, the response is returned
  10752. * from the cache without sending a request to the server.
  10753. *
  10754. * Take note that:
  10755. *
  10756. * * Only GET and JSONP requests are cached.
  10757. * * The cache key is the request URL including search parameters; headers are not considered.
  10758. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10759. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10760. * one request will be made to the server and remaining requests will return the same response.
  10761. * * A cache-control header on the response does not affect if or how responses are cached.
  10762. *
  10763. *
  10764. * ## Interceptors
  10765. *
  10766. * Before you start creating interceptors, be sure to understand the
  10767. * {@link ng.$q $q and deferred/promise APIs}.
  10768. *
  10769. * For purposes of global error handling, authentication, or any kind of synchronous or
  10770. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10771. * able to intercept requests before they are handed to the server and
  10772. * responses before they are handed over to the application code that
  10773. * initiated these requests. The interceptors leverage the {@link ng.$q
  10774. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10775. *
  10776. * The interceptors are service factories that are registered with the `$httpProvider` by
  10777. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10778. * injected with dependencies (if specified) and returns the interceptor.
  10779. *
  10780. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10781. *
  10782. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10783. * modify the `config` object or create a new one. The function needs to return the `config`
  10784. * object directly, or a promise containing the `config` or a new `config` object.
  10785. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10786. * resolved with a rejection.
  10787. * * `response`: interceptors get called with http `response` object. The function is free to
  10788. * modify the `response` object or create a new one. The function needs to return the `response`
  10789. * object directly, or as a promise containing the `response` or a new `response` object.
  10790. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10791. * resolved with a rejection.
  10792. *
  10793. *
  10794. * ```js
  10795. * // register the interceptor as a service
  10796. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10797. * return {
  10798. * // optional method
  10799. * 'request': function(config) {
  10800. * // do something on success
  10801. * return config;
  10802. * },
  10803. *
  10804. * // optional method
  10805. * 'requestError': function(rejection) {
  10806. * // do something on error
  10807. * if (canRecover(rejection)) {
  10808. * return responseOrNewPromise
  10809. * }
  10810. * return $q.reject(rejection);
  10811. * },
  10812. *
  10813. *
  10814. *
  10815. * // optional method
  10816. * 'response': function(response) {
  10817. * // do something on success
  10818. * return response;
  10819. * },
  10820. *
  10821. * // optional method
  10822. * 'responseError': function(rejection) {
  10823. * // do something on error
  10824. * if (canRecover(rejection)) {
  10825. * return responseOrNewPromise
  10826. * }
  10827. * return $q.reject(rejection);
  10828. * }
  10829. * };
  10830. * });
  10831. *
  10832. * $httpProvider.interceptors.push('myHttpInterceptor');
  10833. *
  10834. *
  10835. * // alternatively, register the interceptor via an anonymous factory
  10836. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10837. * return {
  10838. * 'request': function(config) {
  10839. * // same as above
  10840. * },
  10841. *
  10842. * 'response': function(response) {
  10843. * // same as above
  10844. * }
  10845. * };
  10846. * });
  10847. * ```
  10848. *
  10849. * ## Security Considerations
  10850. *
  10851. * When designing web applications, consider security threats from:
  10852. *
  10853. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10854. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10855. *
  10856. * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes
  10857. * pre-configured with strategies that address these issues, but for this to work backend server
  10858. * cooperation is required.
  10859. *
  10860. * ### JSON Vulnerability Protection
  10861. *
  10862. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10863. * allows third party website to turn your JSON resource URL into
  10864. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10865. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10866. * AngularJS will automatically strip the prefix before processing it as JSON.
  10867. *
  10868. * For example if your server needs to return:
  10869. * ```js
  10870. * ['one','two']
  10871. * ```
  10872. *
  10873. * which is vulnerable to attack, your server can return:
  10874. * ```js
  10875. * )]}',
  10876. * ['one','two']
  10877. * ```
  10878. *
  10879. * AngularJS will strip the prefix, before processing the JSON.
  10880. *
  10881. *
  10882. * ### Cross Site Request Forgery (XSRF) Protection
  10883. *
  10884. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10885. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10886. * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the
  10887. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10888. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10889. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10890. * The header will not be set for cross-domain requests.
  10891. *
  10892. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10893. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10894. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10895. * that only JavaScript running on your domain could have sent the request. The token must be
  10896. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10897. * making up its own tokens). We recommend that the token is a digest of your site's
  10898. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10899. * for added security.
  10900. *
  10901. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10902. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10903. * or the per-request config object.
  10904. *
  10905. * In order to prevent collisions in environments where multiple AngularJS apps share the
  10906. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10907. *
  10908. * @param {object} config Object describing the request to be made and how it should be
  10909. * processed. The object has following properties:
  10910. *
  10911. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10912. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10913. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10914. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10915. * with the `paramSerializer` and appended as GET parameters.
  10916. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10917. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10918. * HTTP headers to send to the server. If the return value of a function is null, the
  10919. * header will not be sent. Functions accept a config object as an argument.
  10920. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10921. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10922. * The handler will be called in the context of a `$apply` block.
  10923. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10924. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10925. * The handler will be called in the context of a `$apply` block.
  10926. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10927. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10928. * - **transformRequest** –
  10929. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10930. * transform function or an array of such functions. The transform function takes the http
  10931. * request body and headers and returns its transformed (typically serialized) version.
  10932. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10933. * Overriding the Default Transformations}
  10934. * - **transformResponse** –
  10935. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10936. * transform function or an array of such functions. The transform function takes the http
  10937. * response body, headers and status and returns its transformed (typically deserialized) version.
  10938. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10939. * Overriding the Default Transformations}
  10940. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10941. * prepare the string representation of request parameters (specified as an object).
  10942. * If specified as string, it is interpreted as function registered with the
  10943. * {@link $injector $injector}, which means you can create your own serializer
  10944. * by registering it as a {@link auto.$provide#service service}.
  10945. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10946. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10947. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10948. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10949. * See {@link $http#caching $http Caching} for more information.
  10950. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10951. * that should abort the request when resolved.
  10952. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10953. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10954. * for more information.
  10955. * - **responseType** - `{string}` - see
  10956. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10957. *
  10958. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10959. * when the request succeeds or fails.
  10960. *
  10961. *
  10962. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10963. * requests. This is primarily meant to be used for debugging purposes.
  10964. *
  10965. *
  10966. * @example
  10967. <example module="httpExample" name="http-service">
  10968. <file name="index.html">
  10969. <div ng-controller="FetchController">
  10970. <select ng-model="method" aria-label="Request method">
  10971. <option>GET</option>
  10972. <option>JSONP</option>
  10973. </select>
  10974. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10975. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10976. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10977. <button id="samplejsonpbtn"
  10978. ng-click="updateModel('JSONP',
  10979. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10980. Sample JSONP
  10981. </button>
  10982. <button id="invalidjsonpbtn"
  10983. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10984. Invalid JSONP
  10985. </button>
  10986. <pre>http status code: {{status}}</pre>
  10987. <pre>http response data: {{data}}</pre>
  10988. </div>
  10989. </file>
  10990. <file name="script.js">
  10991. angular.module('httpExample', [])
  10992. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10993. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10994. $sceDelegateProvider.resourceUrlWhitelist([
  10995. 'self',
  10996. 'https://angularjs.org/**'
  10997. ]);
  10998. }])
  10999. .controller('FetchController', ['$scope', '$http', '$templateCache',
  11000. function($scope, $http, $templateCache) {
  11001. $scope.method = 'GET';
  11002. $scope.url = 'http-hello.html';
  11003. $scope.fetch = function() {
  11004. $scope.code = null;
  11005. $scope.response = null;
  11006. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  11007. then(function(response) {
  11008. $scope.status = response.status;
  11009. $scope.data = response.data;
  11010. }, function(response) {
  11011. $scope.data = response.data || 'Request failed';
  11012. $scope.status = response.status;
  11013. });
  11014. };
  11015. $scope.updateModel = function(method, url) {
  11016. $scope.method = method;
  11017. $scope.url = url;
  11018. };
  11019. }]);
  11020. </file>
  11021. <file name="http-hello.html">
  11022. Hello, $http!
  11023. </file>
  11024. <file name="protractor.js" type="protractor">
  11025. var status = element(by.binding('status'));
  11026. var data = element(by.binding('data'));
  11027. var fetchBtn = element(by.id('fetchbtn'));
  11028. var sampleGetBtn = element(by.id('samplegetbtn'));
  11029. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  11030. it('should make an xhr GET request', function() {
  11031. sampleGetBtn.click();
  11032. fetchBtn.click();
  11033. expect(status.getText()).toMatch('200');
  11034. expect(data.getText()).toMatch(/Hello, \$http!/);
  11035. });
  11036. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  11037. // it('should make a JSONP request to angularjs.org', function() {
  11038. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  11039. // sampleJsonpBtn.click();
  11040. // fetchBtn.click();
  11041. // expect(status.getText()).toMatch('200');
  11042. // expect(data.getText()).toMatch(/Super Hero!/);
  11043. // });
  11044. it('should make JSONP request to invalid URL and invoke the error handler',
  11045. function() {
  11046. invalidJsonpBtn.click();
  11047. fetchBtn.click();
  11048. expect(status.getText()).toMatch('0');
  11049. expect(data.getText()).toMatch('Request failed');
  11050. });
  11051. </file>
  11052. </example>
  11053. */
  11054. function $http(requestConfig) {
  11055. if (!isObject(requestConfig)) {
  11056. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  11057. }
  11058. if (!isString($sce.valueOf(requestConfig.url))) {
  11059. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  11060. }
  11061. var config = extend({
  11062. method: 'get',
  11063. transformRequest: defaults.transformRequest,
  11064. transformResponse: defaults.transformResponse,
  11065. paramSerializer: defaults.paramSerializer,
  11066. jsonpCallbackParam: defaults.jsonpCallbackParam
  11067. }, requestConfig);
  11068. config.headers = mergeHeaders(requestConfig);
  11069. config.method = uppercase(config.method);
  11070. config.paramSerializer = isString(config.paramSerializer) ?
  11071. $injector.get(config.paramSerializer) : config.paramSerializer;
  11072. $browser.$$incOutstandingRequestCount();
  11073. var requestInterceptors = [];
  11074. var responseInterceptors = [];
  11075. var promise = $q.resolve(config);
  11076. // apply interceptors
  11077. forEach(reversedInterceptors, function(interceptor) {
  11078. if (interceptor.request || interceptor.requestError) {
  11079. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  11080. }
  11081. if (interceptor.response || interceptor.responseError) {
  11082. responseInterceptors.push(interceptor.response, interceptor.responseError);
  11083. }
  11084. });
  11085. promise = chainInterceptors(promise, requestInterceptors);
  11086. promise = promise.then(serverRequest);
  11087. promise = chainInterceptors(promise, responseInterceptors);
  11088. promise = promise.finally(completeOutstandingRequest);
  11089. return promise;
  11090. function chainInterceptors(promise, interceptors) {
  11091. for (var i = 0, ii = interceptors.length; i < ii;) {
  11092. var thenFn = interceptors[i++];
  11093. var rejectFn = interceptors[i++];
  11094. promise = promise.then(thenFn, rejectFn);
  11095. }
  11096. interceptors.length = 0;
  11097. return promise;
  11098. }
  11099. function completeOutstandingRequest() {
  11100. $browser.$$completeOutstandingRequest(noop);
  11101. }
  11102. function executeHeaderFns(headers, config) {
  11103. var headerContent, processedHeaders = {};
  11104. forEach(headers, function(headerFn, header) {
  11105. if (isFunction(headerFn)) {
  11106. headerContent = headerFn(config);
  11107. if (headerContent != null) {
  11108. processedHeaders[header] = headerContent;
  11109. }
  11110. } else {
  11111. processedHeaders[header] = headerFn;
  11112. }
  11113. });
  11114. return processedHeaders;
  11115. }
  11116. function mergeHeaders(config) {
  11117. var defHeaders = defaults.headers,
  11118. reqHeaders = extend({}, config.headers),
  11119. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  11120. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  11121. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  11122. defaultHeadersIteration:
  11123. for (defHeaderName in defHeaders) {
  11124. lowercaseDefHeaderName = lowercase(defHeaderName);
  11125. for (reqHeaderName in reqHeaders) {
  11126. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  11127. continue defaultHeadersIteration;
  11128. }
  11129. }
  11130. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  11131. }
  11132. // execute if header value is a function for merged headers
  11133. return executeHeaderFns(reqHeaders, shallowCopy(config));
  11134. }
  11135. function serverRequest(config) {
  11136. var headers = config.headers;
  11137. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  11138. // strip content-type if data is undefined
  11139. if (isUndefined(reqData)) {
  11140. forEach(headers, function(value, header) {
  11141. if (lowercase(header) === 'content-type') {
  11142. delete headers[header];
  11143. }
  11144. });
  11145. }
  11146. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  11147. config.withCredentials = defaults.withCredentials;
  11148. }
  11149. // send request
  11150. return sendReq(config, reqData).then(transformResponse, transformResponse);
  11151. }
  11152. function transformResponse(response) {
  11153. // make a copy since the response must be cacheable
  11154. var resp = extend({}, response);
  11155. resp.data = transformData(response.data, response.headers, response.status,
  11156. config.transformResponse);
  11157. return (isSuccess(response.status))
  11158. ? resp
  11159. : $q.reject(resp);
  11160. }
  11161. }
  11162. $http.pendingRequests = [];
  11163. /**
  11164. * @ngdoc method
  11165. * @name $http#get
  11166. *
  11167. * @description
  11168. * Shortcut method to perform `GET` request.
  11169. *
  11170. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11171. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11172. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11173. * @returns {HttpPromise} Future object
  11174. */
  11175. /**
  11176. * @ngdoc method
  11177. * @name $http#delete
  11178. *
  11179. * @description
  11180. * Shortcut method to perform `DELETE` request.
  11181. *
  11182. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11183. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11184. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11185. * @returns {HttpPromise} Future object
  11186. */
  11187. /**
  11188. * @ngdoc method
  11189. * @name $http#head
  11190. *
  11191. * @description
  11192. * Shortcut method to perform `HEAD` request.
  11193. *
  11194. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11195. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11196. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11197. * @returns {HttpPromise} Future object
  11198. */
  11199. /**
  11200. * @ngdoc method
  11201. * @name $http#jsonp
  11202. *
  11203. * @description
  11204. * Shortcut method to perform `JSONP` request.
  11205. *
  11206. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  11207. * the url must be declared, via {@link $sce} as a trusted resource URL.
  11208. * You can trust a URL by adding it to the whitelist via
  11209. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  11210. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  11211. *
  11212. * You should avoid generating the URL for the JSONP request from user provided data.
  11213. * Provide additional query parameters via `params` property of the `config` parameter, rather than
  11214. * modifying the URL itself.
  11215. *
  11216. * JSONP requests must specify a callback to be used in the response from the server. This callback
  11217. * is passed as a query parameter in the request. You must specify the name of this parameter by
  11218. * setting the `jsonpCallbackParam` property on the request config object.
  11219. *
  11220. * ```
  11221. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  11222. * ```
  11223. *
  11224. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  11225. * Initially this is set to `'callback'`.
  11226. *
  11227. * <div class="alert alert-danger">
  11228. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  11229. * parameter value should go.
  11230. * </div>
  11231. *
  11232. * If you would like to customise where and how the callbacks are stored then try overriding
  11233. * or decorating the {@link $jsonpCallbacks} service.
  11234. *
  11235. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11236. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11237. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11238. * @returns {HttpPromise} Future object
  11239. */
  11240. createShortMethods('get', 'delete', 'head', 'jsonp');
  11241. /**
  11242. * @ngdoc method
  11243. * @name $http#post
  11244. *
  11245. * @description
  11246. * Shortcut method to perform `POST` request.
  11247. *
  11248. * @param {string} url Relative or absolute URL specifying the destination of the request
  11249. * @param {*} data Request content
  11250. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11251. * @returns {HttpPromise} Future object
  11252. */
  11253. /**
  11254. * @ngdoc method
  11255. * @name $http#put
  11256. *
  11257. * @description
  11258. * Shortcut method to perform `PUT` request.
  11259. *
  11260. * @param {string} url Relative or absolute URL specifying the destination of the request
  11261. * @param {*} data Request content
  11262. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11263. * @returns {HttpPromise} Future object
  11264. */
  11265. /**
  11266. * @ngdoc method
  11267. * @name $http#patch
  11268. *
  11269. * @description
  11270. * Shortcut method to perform `PATCH` request.
  11271. *
  11272. * @param {string} url Relative or absolute URL specifying the destination of the request
  11273. * @param {*} data Request content
  11274. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11275. * @returns {HttpPromise} Future object
  11276. */
  11277. createShortMethodsWithData('post', 'put', 'patch');
  11278. /**
  11279. * @ngdoc property
  11280. * @name $http#defaults
  11281. *
  11282. * @description
  11283. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11284. * default headers, withCredentials as well as request and response transformations.
  11285. *
  11286. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11287. */
  11288. $http.defaults = defaults;
  11289. return $http;
  11290. function createShortMethods(names) {
  11291. forEach(arguments, function(name) {
  11292. $http[name] = function(url, config) {
  11293. return $http(extend({}, config || {}, {
  11294. method: name,
  11295. url: url
  11296. }));
  11297. };
  11298. });
  11299. }
  11300. function createShortMethodsWithData(name) {
  11301. forEach(arguments, function(name) {
  11302. $http[name] = function(url, data, config) {
  11303. return $http(extend({}, config || {}, {
  11304. method: name,
  11305. url: url,
  11306. data: data
  11307. }));
  11308. };
  11309. });
  11310. }
  11311. /**
  11312. * Makes the request.
  11313. *
  11314. * !!! ACCESSES CLOSURE VARS:
  11315. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11316. */
  11317. function sendReq(config, reqData) {
  11318. var deferred = $q.defer(),
  11319. promise = deferred.promise,
  11320. cache,
  11321. cachedResp,
  11322. reqHeaders = config.headers,
  11323. isJsonp = lowercase(config.method) === 'jsonp',
  11324. url = config.url;
  11325. if (isJsonp) {
  11326. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11327. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11328. url = $sce.getTrustedResourceUrl(url);
  11329. } else if (!isString(url)) {
  11330. // If it is not a string then the URL must be a $sce trusted object
  11331. url = $sce.valueOf(url);
  11332. }
  11333. url = buildUrl(url, config.paramSerializer(config.params));
  11334. if (isJsonp) {
  11335. // Check the url and add the JSONP callback placeholder
  11336. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11337. }
  11338. $http.pendingRequests.push(config);
  11339. promise.then(removePendingReq, removePendingReq);
  11340. if ((config.cache || defaults.cache) && config.cache !== false &&
  11341. (config.method === 'GET' || config.method === 'JSONP')) {
  11342. cache = isObject(config.cache) ? config.cache
  11343. : isObject(/** @type {?} */ (defaults).cache)
  11344. ? /** @type {?} */ (defaults).cache
  11345. : defaultCache;
  11346. }
  11347. if (cache) {
  11348. cachedResp = cache.get(url);
  11349. if (isDefined(cachedResp)) {
  11350. if (isPromiseLike(cachedResp)) {
  11351. // cached request has already been sent, but there is no response yet
  11352. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11353. } else {
  11354. // serving from cache
  11355. if (isArray(cachedResp)) {
  11356. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);
  11357. } else {
  11358. resolvePromise(cachedResp, 200, {}, 'OK', 'complete');
  11359. }
  11360. }
  11361. } else {
  11362. // put the promise for the non-transformed response into cache as a placeholder
  11363. cache.put(url, promise);
  11364. }
  11365. }
  11366. // if we won't have the response in cache, set the xsrf headers and
  11367. // send the request to the backend
  11368. if (isUndefined(cachedResp)) {
  11369. var xsrfValue = urlIsSameOrigin(config.url)
  11370. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  11371. : undefined;
  11372. if (xsrfValue) {
  11373. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11374. }
  11375. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11376. config.withCredentials, config.responseType,
  11377. createApplyHandlers(config.eventHandlers),
  11378. createApplyHandlers(config.uploadEventHandlers));
  11379. }
  11380. return promise;
  11381. function createApplyHandlers(eventHandlers) {
  11382. if (eventHandlers) {
  11383. var applyHandlers = {};
  11384. forEach(eventHandlers, function(eventHandler, key) {
  11385. applyHandlers[key] = function(event) {
  11386. if (useApplyAsync) {
  11387. $rootScope.$applyAsync(callEventHandler);
  11388. } else if ($rootScope.$$phase) {
  11389. callEventHandler();
  11390. } else {
  11391. $rootScope.$apply(callEventHandler);
  11392. }
  11393. function callEventHandler() {
  11394. eventHandler(event);
  11395. }
  11396. };
  11397. });
  11398. return applyHandlers;
  11399. }
  11400. }
  11401. /**
  11402. * Callback registered to $httpBackend():
  11403. * - caches the response if desired
  11404. * - resolves the raw $http promise
  11405. * - calls $apply
  11406. */
  11407. function done(status, response, headersString, statusText, xhrStatus) {
  11408. if (cache) {
  11409. if (isSuccess(status)) {
  11410. cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);
  11411. } else {
  11412. // remove promise from the cache
  11413. cache.remove(url);
  11414. }
  11415. }
  11416. function resolveHttpPromise() {
  11417. resolvePromise(response, status, headersString, statusText, xhrStatus);
  11418. }
  11419. if (useApplyAsync) {
  11420. $rootScope.$applyAsync(resolveHttpPromise);
  11421. } else {
  11422. resolveHttpPromise();
  11423. if (!$rootScope.$$phase) $rootScope.$apply();
  11424. }
  11425. }
  11426. /**
  11427. * Resolves the raw $http promise.
  11428. */
  11429. function resolvePromise(response, status, headers, statusText, xhrStatus) {
  11430. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11431. status = status >= -1 ? status : 0;
  11432. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11433. data: response,
  11434. status: status,
  11435. headers: headersGetter(headers),
  11436. config: config,
  11437. statusText: statusText,
  11438. xhrStatus: xhrStatus
  11439. });
  11440. }
  11441. function resolvePromiseWithResult(result) {
  11442. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);
  11443. }
  11444. function removePendingReq() {
  11445. var idx = $http.pendingRequests.indexOf(config);
  11446. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11447. }
  11448. }
  11449. function buildUrl(url, serializedParams) {
  11450. if (serializedParams.length > 0) {
  11451. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11452. }
  11453. return url;
  11454. }
  11455. function sanitizeJsonpCallbackParam(url, cbKey) {
  11456. var parts = url.split('?');
  11457. if (parts.length > 2) {
  11458. // Throw if the url contains more than one `?` query indicator
  11459. throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url);
  11460. }
  11461. var params = parseKeyValue(parts[1]);
  11462. forEach(params, function(value, key) {
  11463. if (value === 'JSON_CALLBACK') {
  11464. // Throw if the url already contains a reference to JSON_CALLBACK
  11465. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11466. }
  11467. if (key === cbKey) {
  11468. // Throw if the callback param was already provided
  11469. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url);
  11470. }
  11471. });
  11472. // Add in the JSON_CALLBACK callback param value
  11473. url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK';
  11474. return url;
  11475. }
  11476. }];
  11477. }
  11478. /**
  11479. * @ngdoc service
  11480. * @name $xhrFactory
  11481. * @this
  11482. *
  11483. * @description
  11484. * Factory function used to create XMLHttpRequest objects.
  11485. *
  11486. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11487. *
  11488. * ```
  11489. * angular.module('myApp', [])
  11490. * .factory('$xhrFactory', function() {
  11491. * return function createXhr(method, url) {
  11492. * return new window.XMLHttpRequest({mozSystem: true});
  11493. * };
  11494. * });
  11495. * ```
  11496. *
  11497. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11498. * @param {string} url URL of the request.
  11499. */
  11500. function $xhrFactoryProvider() {
  11501. this.$get = function() {
  11502. return function createXhr() {
  11503. return new window.XMLHttpRequest();
  11504. };
  11505. };
  11506. }
  11507. /**
  11508. * @ngdoc service
  11509. * @name $httpBackend
  11510. * @requires $jsonpCallbacks
  11511. * @requires $document
  11512. * @requires $xhrFactory
  11513. * @this
  11514. *
  11515. * @description
  11516. * HTTP backend used by the {@link ng.$http service} that delegates to
  11517. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11518. *
  11519. * You should never need to use this service directly, instead use the higher-level abstractions:
  11520. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11521. *
  11522. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11523. * $httpBackend} which can be trained with responses.
  11524. */
  11525. function $HttpBackendProvider() {
  11526. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11527. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11528. }];
  11529. }
  11530. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11531. // TODO(vojta): fix the signature
  11532. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11533. url = url || $browser.url();
  11534. if (lowercase(method) === 'jsonp') {
  11535. var callbackPath = callbacks.createCallback(url);
  11536. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11537. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11538. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11539. completeRequest(callback, status, response, '', text, 'complete');
  11540. callbacks.removeCallback(callbackPath);
  11541. });
  11542. } else {
  11543. var xhr = createXhr(method, url);
  11544. xhr.open(method, url, true);
  11545. forEach(headers, function(value, key) {
  11546. if (isDefined(value)) {
  11547. xhr.setRequestHeader(key, value);
  11548. }
  11549. });
  11550. xhr.onload = function requestLoaded() {
  11551. var statusText = xhr.statusText || '';
  11552. // responseText is the old-school way of retrieving response (supported by IE9)
  11553. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11554. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11555. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11556. var status = xhr.status === 1223 ? 204 : xhr.status;
  11557. // fix status code when it is 0 (0 status is undocumented).
  11558. // Occurs when accessing file resources or on Android 4.1 stock browser
  11559. // while retrieving files from application cache.
  11560. if (status === 0) {
  11561. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11562. }
  11563. completeRequest(callback,
  11564. status,
  11565. response,
  11566. xhr.getAllResponseHeaders(),
  11567. statusText,
  11568. 'complete');
  11569. };
  11570. var requestError = function() {
  11571. // The response is always empty
  11572. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11573. completeRequest(callback, -1, null, null, '', 'error');
  11574. };
  11575. var requestAborted = function() {
  11576. completeRequest(callback, -1, null, null, '', 'abort');
  11577. };
  11578. var requestTimeout = function() {
  11579. // The response is always empty
  11580. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11581. completeRequest(callback, -1, null, null, '', 'timeout');
  11582. };
  11583. xhr.onerror = requestError;
  11584. xhr.onabort = requestAborted;
  11585. xhr.ontimeout = requestTimeout;
  11586. forEach(eventHandlers, function(value, key) {
  11587. xhr.addEventListener(key, value);
  11588. });
  11589. forEach(uploadEventHandlers, function(value, key) {
  11590. xhr.upload.addEventListener(key, value);
  11591. });
  11592. if (withCredentials) {
  11593. xhr.withCredentials = true;
  11594. }
  11595. if (responseType) {
  11596. try {
  11597. xhr.responseType = responseType;
  11598. } catch (e) {
  11599. // WebKit added support for the json responseType value on 09/03/2013
  11600. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11601. // known to throw when setting the value "json" as the response type. Other older
  11602. // browsers implementing the responseType
  11603. //
  11604. // The json response type can be ignored if not supported, because JSON payloads are
  11605. // parsed on the client-side regardless.
  11606. if (responseType !== 'json') {
  11607. throw e;
  11608. }
  11609. }
  11610. }
  11611. xhr.send(isUndefined(post) ? null : post);
  11612. }
  11613. if (timeout > 0) {
  11614. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11615. } else if (isPromiseLike(timeout)) {
  11616. timeout.then(timeoutRequest);
  11617. }
  11618. function timeoutRequest() {
  11619. if (jsonpDone) {
  11620. jsonpDone();
  11621. }
  11622. if (xhr) {
  11623. xhr.abort();
  11624. }
  11625. }
  11626. function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {
  11627. // cancel timeout and subsequent timeout promise resolution
  11628. if (isDefined(timeoutId)) {
  11629. $browserDefer.cancel(timeoutId);
  11630. }
  11631. jsonpDone = xhr = null;
  11632. callback(status, response, headersString, statusText, xhrStatus);
  11633. }
  11634. };
  11635. function jsonpReq(url, callbackPath, done) {
  11636. url = url.replace('JSON_CALLBACK', callbackPath);
  11637. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11638. // - fetches local scripts via XHR and evals them
  11639. // - adds and immediately removes script elements from the document
  11640. var script = rawDocument.createElement('script'), callback = null;
  11641. script.type = 'text/javascript';
  11642. script.src = url;
  11643. script.async = true;
  11644. callback = function(event) {
  11645. script.removeEventListener('load', callback);
  11646. script.removeEventListener('error', callback);
  11647. rawDocument.body.removeChild(script);
  11648. script = null;
  11649. var status = -1;
  11650. var text = 'unknown';
  11651. if (event) {
  11652. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11653. event = { type: 'error' };
  11654. }
  11655. text = event.type;
  11656. status = event.type === 'error' ? 404 : 200;
  11657. }
  11658. if (done) {
  11659. done(status, text);
  11660. }
  11661. };
  11662. script.addEventListener('load', callback);
  11663. script.addEventListener('error', callback);
  11664. rawDocument.body.appendChild(script);
  11665. return callback;
  11666. }
  11667. }
  11668. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11669. $interpolateMinErr.throwNoconcat = function(text) {
  11670. throw $interpolateMinErr('noconcat',
  11671. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11672. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11673. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11674. };
  11675. $interpolateMinErr.interr = function(text, err) {
  11676. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11677. };
  11678. /**
  11679. * @ngdoc provider
  11680. * @name $interpolateProvider
  11681. * @this
  11682. *
  11683. * @description
  11684. *
  11685. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11686. *
  11687. * <div class="alert alert-danger">
  11688. * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS
  11689. * template within a Python Jinja template (or any other template language). Mixing templating
  11690. * languages is **very dangerous**. The embedding template language will not safely escape AngularJS
  11691. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11692. * security bugs!
  11693. * </div>
  11694. *
  11695. * @example
  11696. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11697. <file name="index.html">
  11698. <script>
  11699. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11700. customInterpolationApp.config(function($interpolateProvider) {
  11701. $interpolateProvider.startSymbol('//');
  11702. $interpolateProvider.endSymbol('//');
  11703. });
  11704. customInterpolationApp.controller('DemoController', function() {
  11705. this.label = "This binding is brought you by // interpolation symbols.";
  11706. });
  11707. </script>
  11708. <div ng-controller="DemoController as demo">
  11709. //demo.label//
  11710. </div>
  11711. </file>
  11712. <file name="protractor.js" type="protractor">
  11713. it('should interpolate binding with custom symbols', function() {
  11714. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11715. });
  11716. </file>
  11717. </example>
  11718. */
  11719. function $InterpolateProvider() {
  11720. var startSymbol = '{{';
  11721. var endSymbol = '}}';
  11722. /**
  11723. * @ngdoc method
  11724. * @name $interpolateProvider#startSymbol
  11725. * @description
  11726. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11727. *
  11728. * @param {string=} value new value to set the starting symbol to.
  11729. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11730. */
  11731. this.startSymbol = function(value) {
  11732. if (value) {
  11733. startSymbol = value;
  11734. return this;
  11735. } else {
  11736. return startSymbol;
  11737. }
  11738. };
  11739. /**
  11740. * @ngdoc method
  11741. * @name $interpolateProvider#endSymbol
  11742. * @description
  11743. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11744. *
  11745. * @param {string=} value new value to set the ending symbol to.
  11746. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11747. */
  11748. this.endSymbol = function(value) {
  11749. if (value) {
  11750. endSymbol = value;
  11751. return this;
  11752. } else {
  11753. return endSymbol;
  11754. }
  11755. };
  11756. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11757. var startSymbolLength = startSymbol.length,
  11758. endSymbolLength = endSymbol.length,
  11759. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11760. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11761. function escape(ch) {
  11762. return '\\\\\\' + ch;
  11763. }
  11764. function unescapeText(text) {
  11765. return text.replace(escapedStartRegexp, startSymbol).
  11766. replace(escapedEndRegexp, endSymbol);
  11767. }
  11768. // TODO: this is the same as the constantWatchDelegate in parse.js
  11769. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11770. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11771. unwatch();
  11772. return constantInterp(scope);
  11773. }, listener, objectEquality);
  11774. return unwatch;
  11775. }
  11776. /**
  11777. * @ngdoc service
  11778. * @name $interpolate
  11779. * @kind function
  11780. *
  11781. * @requires $parse
  11782. * @requires $sce
  11783. *
  11784. * @description
  11785. *
  11786. * Compiles a string with markup into an interpolation function. This service is used by the
  11787. * HTML {@link ng.$compile $compile} service for data binding. See
  11788. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11789. * interpolation markup.
  11790. *
  11791. *
  11792. * ```js
  11793. * var $interpolate = ...; // injected
  11794. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11795. * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULAR!');
  11796. * ```
  11797. *
  11798. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11799. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11800. * evaluate to a value other than `undefined`.
  11801. *
  11802. * ```js
  11803. * var $interpolate = ...; // injected
  11804. * var context = {greeting: 'Hello', name: undefined };
  11805. *
  11806. * // default "forgiving" mode
  11807. * var exp = $interpolate('{{greeting}} {{name}}!');
  11808. * expect(exp(context)).toEqual('Hello !');
  11809. *
  11810. * // "allOrNothing" mode
  11811. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11812. * expect(exp(context)).toBeUndefined();
  11813. * context.name = 'AngularJS';
  11814. * expect(exp(context)).toEqual('Hello AngularJS!');
  11815. * ```
  11816. *
  11817. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11818. *
  11819. * #### Escaped Interpolation
  11820. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11821. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11822. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11823. * or binding.
  11824. *
  11825. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11826. * degree, while also enabling code examples to work without relying on the
  11827. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11828. *
  11829. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11830. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11831. * interpolation start/end markers with their escaped counterparts.**
  11832. *
  11833. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11834. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11835. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11836. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11837. * this is typically useful only when user-data is used in rendering a template from the server, or
  11838. * when otherwise untrusted data is used by a directive.
  11839. *
  11840. * <example name="interpolation">
  11841. * <file name="index.html">
  11842. * <div ng-init="username='A user'">
  11843. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11844. * </p>
  11845. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11846. * application, but fails to accomplish their task, because the server has correctly
  11847. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11848. * characters.</p>
  11849. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11850. * from the database by an administrator.</p>
  11851. * </div>
  11852. * </file>
  11853. * </example>
  11854. *
  11855. * @knownIssue
  11856. * It is currently not possible for an interpolated expression to contain the interpolation end
  11857. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11858. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11859. *
  11860. * @knownIssue
  11861. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11862. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11863. * service will attempt to denormalize the standard symbols to the custom symbols.
  11864. * The denormalization process is not clever enough to know not to replace instances of the standard
  11865. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11866. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11867. *
  11868. * ```
  11869. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11870. * ```
  11871. *
  11872. * The workaround is to ensure that such instances are separated by whitespace:
  11873. * ```
  11874. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11875. * ```
  11876. *
  11877. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11878. *
  11879. * @param {string} text The text with markup to interpolate.
  11880. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11881. * embedded expression in order to return an interpolation function. Strings with no
  11882. * embedded expression will return null for the interpolation function.
  11883. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11884. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11885. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11886. * provides Strict Contextual Escaping for details.
  11887. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11888. * unless all embedded expressions evaluate to a value other than `undefined`.
  11889. * @returns {function(context)} an interpolation function which is used to compute the
  11890. * interpolated string. The function has these parameters:
  11891. *
  11892. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11893. */
  11894. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11895. // Provide a quick exit and simplified result function for text with no interpolation
  11896. if (!text.length || text.indexOf(startSymbol) === -1) {
  11897. var constantInterp;
  11898. if (!mustHaveExpression) {
  11899. var unescapedText = unescapeText(text);
  11900. constantInterp = valueFn(unescapedText);
  11901. constantInterp.exp = text;
  11902. constantInterp.expressions = [];
  11903. constantInterp.$$watchDelegate = constantWatchDelegate;
  11904. }
  11905. return constantInterp;
  11906. }
  11907. allOrNothing = !!allOrNothing;
  11908. var startIndex,
  11909. endIndex,
  11910. index = 0,
  11911. expressions = [],
  11912. parseFns = [],
  11913. textLength = text.length,
  11914. exp,
  11915. concat = [],
  11916. expressionPositions = [];
  11917. while (index < textLength) {
  11918. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11919. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11920. if (index !== startIndex) {
  11921. concat.push(unescapeText(text.substring(index, startIndex)));
  11922. }
  11923. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11924. expressions.push(exp);
  11925. parseFns.push($parse(exp, parseStringifyInterceptor));
  11926. index = endIndex + endSymbolLength;
  11927. expressionPositions.push(concat.length);
  11928. concat.push('');
  11929. } else {
  11930. // we did not find an interpolation, so we have to add the remainder to the separators array
  11931. if (index !== textLength) {
  11932. concat.push(unescapeText(text.substring(index)));
  11933. }
  11934. break;
  11935. }
  11936. }
  11937. // Concatenating expressions makes it hard to reason about whether some combination of
  11938. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11939. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11940. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11941. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11942. // the load when auditing for XSS issues.
  11943. if (trustedContext && concat.length > 1) {
  11944. $interpolateMinErr.throwNoconcat(text);
  11945. }
  11946. if (!mustHaveExpression || expressions.length) {
  11947. var compute = function(values) {
  11948. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11949. if (allOrNothing && isUndefined(values[i])) return;
  11950. concat[expressionPositions[i]] = values[i];
  11951. }
  11952. return concat.join('');
  11953. };
  11954. var getValue = function(value) {
  11955. return trustedContext ?
  11956. $sce.getTrusted(trustedContext, value) :
  11957. $sce.valueOf(value);
  11958. };
  11959. return extend(function interpolationFn(context) {
  11960. var i = 0;
  11961. var ii = expressions.length;
  11962. var values = new Array(ii);
  11963. try {
  11964. for (; i < ii; i++) {
  11965. values[i] = parseFns[i](context);
  11966. }
  11967. return compute(values);
  11968. } catch (err) {
  11969. $exceptionHandler($interpolateMinErr.interr(text, err));
  11970. }
  11971. }, {
  11972. // all of these properties are undocumented for now
  11973. exp: text, //just for compatibility with regular watchers created via $watch
  11974. expressions: expressions,
  11975. $$watchDelegate: function(scope, listener) {
  11976. var lastValue;
  11977. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11978. var currValue = compute(values);
  11979. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11980. lastValue = currValue;
  11981. });
  11982. }
  11983. });
  11984. }
  11985. function parseStringifyInterceptor(value) {
  11986. try {
  11987. value = getValue(value);
  11988. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11989. } catch (err) {
  11990. $exceptionHandler($interpolateMinErr.interr(text, err));
  11991. }
  11992. }
  11993. }
  11994. /**
  11995. * @ngdoc method
  11996. * @name $interpolate#startSymbol
  11997. * @description
  11998. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11999. *
  12000. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  12001. * the symbol.
  12002. *
  12003. * @returns {string} start symbol.
  12004. */
  12005. $interpolate.startSymbol = function() {
  12006. return startSymbol;
  12007. };
  12008. /**
  12009. * @ngdoc method
  12010. * @name $interpolate#endSymbol
  12011. * @description
  12012. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12013. *
  12014. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  12015. * the symbol.
  12016. *
  12017. * @returns {string} end symbol.
  12018. */
  12019. $interpolate.endSymbol = function() {
  12020. return endSymbol;
  12021. };
  12022. return $interpolate;
  12023. }];
  12024. }
  12025. /** @this */
  12026. function $IntervalProvider() {
  12027. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  12028. function($rootScope, $window, $q, $$q, $browser) {
  12029. var intervals = {};
  12030. /**
  12031. * @ngdoc service
  12032. * @name $interval
  12033. *
  12034. * @description
  12035. * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  12036. * milliseconds.
  12037. *
  12038. * The return value of registering an interval function is a promise. This promise will be
  12039. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  12040. * run indefinitely if `count` is not defined. The value of the notification will be the
  12041. * number of iterations that have run.
  12042. * To cancel an interval, call `$interval.cancel(promise)`.
  12043. *
  12044. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  12045. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  12046. * time.
  12047. *
  12048. * <div class="alert alert-warning">
  12049. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  12050. * with them. In particular they are not automatically destroyed when a controller's scope or a
  12051. * directive's element are destroyed.
  12052. * You should take this into consideration and make sure to always cancel the interval at the
  12053. * appropriate moment. See the example below for more details on how and when to do this.
  12054. * </div>
  12055. *
  12056. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  12057. * are passed (see below), the function is called with the current iteration count.
  12058. * @param {number} delay Number of milliseconds between each function call.
  12059. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  12060. * indefinitely.
  12061. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12062. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12063. * @param {...*=} Pass additional parameters to the executed function.
  12064. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  12065. *
  12066. * @example
  12067. * <example module="intervalExample" name="interval-service">
  12068. * <file name="index.html">
  12069. * <script>
  12070. * angular.module('intervalExample', [])
  12071. * .controller('ExampleController', ['$scope', '$interval',
  12072. * function($scope, $interval) {
  12073. * $scope.format = 'M/d/yy h:mm:ss a';
  12074. * $scope.blood_1 = 100;
  12075. * $scope.blood_2 = 120;
  12076. *
  12077. * var stop;
  12078. * $scope.fight = function() {
  12079. * // Don't start a new fight if we are already fighting
  12080. * if ( angular.isDefined(stop) ) return;
  12081. *
  12082. * stop = $interval(function() {
  12083. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12084. * $scope.blood_1 = $scope.blood_1 - 3;
  12085. * $scope.blood_2 = $scope.blood_2 - 4;
  12086. * } else {
  12087. * $scope.stopFight();
  12088. * }
  12089. * }, 100);
  12090. * };
  12091. *
  12092. * $scope.stopFight = function() {
  12093. * if (angular.isDefined(stop)) {
  12094. * $interval.cancel(stop);
  12095. * stop = undefined;
  12096. * }
  12097. * };
  12098. *
  12099. * $scope.resetFight = function() {
  12100. * $scope.blood_1 = 100;
  12101. * $scope.blood_2 = 120;
  12102. * };
  12103. *
  12104. * $scope.$on('$destroy', function() {
  12105. * // Make sure that the interval is destroyed too
  12106. * $scope.stopFight();
  12107. * });
  12108. * }])
  12109. * // Register the 'myCurrentTime' directive factory method.
  12110. * // We inject $interval and dateFilter service since the factory method is DI.
  12111. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  12112. * function($interval, dateFilter) {
  12113. * // return the directive link function. (compile function not needed)
  12114. * return function(scope, element, attrs) {
  12115. * var format, // date format
  12116. * stopTime; // so that we can cancel the time updates
  12117. *
  12118. * // used to update the UI
  12119. * function updateTime() {
  12120. * element.text(dateFilter(new Date(), format));
  12121. * }
  12122. *
  12123. * // watch the expression, and update the UI on change.
  12124. * scope.$watch(attrs.myCurrentTime, function(value) {
  12125. * format = value;
  12126. * updateTime();
  12127. * });
  12128. *
  12129. * stopTime = $interval(updateTime, 1000);
  12130. *
  12131. * // listen on DOM destroy (removal) event, and cancel the next UI update
  12132. * // to prevent updating time after the DOM element was removed.
  12133. * element.on('$destroy', function() {
  12134. * $interval.cancel(stopTime);
  12135. * });
  12136. * }
  12137. * }]);
  12138. * </script>
  12139. *
  12140. * <div>
  12141. * <div ng-controller="ExampleController">
  12142. * <label>Date format: <input ng-model="format"></label> <hr/>
  12143. * Current time is: <span my-current-time="format"></span>
  12144. * <hr/>
  12145. * Blood 1 : <font color='red'>{{blood_1}}</font>
  12146. * Blood 2 : <font color='red'>{{blood_2}}</font>
  12147. * <button type="button" data-ng-click="fight()">Fight</button>
  12148. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  12149. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  12150. * </div>
  12151. * </div>
  12152. *
  12153. * </file>
  12154. * </example>
  12155. */
  12156. function interval(fn, delay, count, invokeApply) {
  12157. var hasParams = arguments.length > 4,
  12158. args = hasParams ? sliceArgs(arguments, 4) : [],
  12159. setInterval = $window.setInterval,
  12160. clearInterval = $window.clearInterval,
  12161. iteration = 0,
  12162. skipApply = (isDefined(invokeApply) && !invokeApply),
  12163. deferred = (skipApply ? $$q : $q).defer(),
  12164. promise = deferred.promise;
  12165. count = isDefined(count) ? count : 0;
  12166. promise.$$intervalId = setInterval(function tick() {
  12167. if (skipApply) {
  12168. $browser.defer(callback);
  12169. } else {
  12170. $rootScope.$evalAsync(callback);
  12171. }
  12172. deferred.notify(iteration++);
  12173. if (count > 0 && iteration >= count) {
  12174. deferred.resolve(iteration);
  12175. clearInterval(promise.$$intervalId);
  12176. delete intervals[promise.$$intervalId];
  12177. }
  12178. if (!skipApply) $rootScope.$apply();
  12179. }, delay);
  12180. intervals[promise.$$intervalId] = deferred;
  12181. return promise;
  12182. function callback() {
  12183. if (!hasParams) {
  12184. fn(iteration);
  12185. } else {
  12186. fn.apply(null, args);
  12187. }
  12188. }
  12189. }
  12190. /**
  12191. * @ngdoc method
  12192. * @name $interval#cancel
  12193. *
  12194. * @description
  12195. * Cancels a task associated with the `promise`.
  12196. *
  12197. * @param {Promise=} promise returned by the `$interval` function.
  12198. * @returns {boolean} Returns `true` if the task was successfully canceled.
  12199. */
  12200. interval.cancel = function(promise) {
  12201. if (promise && promise.$$intervalId in intervals) {
  12202. // Interval cancels should not report as unhandled promise.
  12203. markQExceptionHandled(intervals[promise.$$intervalId].promise);
  12204. intervals[promise.$$intervalId].reject('canceled');
  12205. $window.clearInterval(promise.$$intervalId);
  12206. delete intervals[promise.$$intervalId];
  12207. return true;
  12208. }
  12209. return false;
  12210. };
  12211. return interval;
  12212. }];
  12213. }
  12214. /**
  12215. * @ngdoc service
  12216. * @name $jsonpCallbacks
  12217. * @requires $window
  12218. * @description
  12219. * This service handles the lifecycle of callbacks to handle JSONP requests.
  12220. * Override this service if you wish to customise where the callbacks are stored and
  12221. * how they vary compared to the requested url.
  12222. */
  12223. var $jsonpCallbacksProvider = /** @this */ function() {
  12224. this.$get = function() {
  12225. var callbacks = angular.callbacks;
  12226. var callbackMap = {};
  12227. function createCallback(callbackId) {
  12228. var callback = function(data) {
  12229. callback.data = data;
  12230. callback.called = true;
  12231. };
  12232. callback.id = callbackId;
  12233. return callback;
  12234. }
  12235. return {
  12236. /**
  12237. * @ngdoc method
  12238. * @name $jsonpCallbacks#createCallback
  12239. * @param {string} url the url of the JSONP request
  12240. * @returns {string} the callback path to send to the server as part of the JSONP request
  12241. * @description
  12242. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  12243. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  12244. */
  12245. createCallback: function(url) {
  12246. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  12247. var callbackPath = 'angular.callbacks.' + callbackId;
  12248. var callback = createCallback(callbackId);
  12249. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  12250. return callbackPath;
  12251. },
  12252. /**
  12253. * @ngdoc method
  12254. * @name $jsonpCallbacks#wasCalled
  12255. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12256. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12257. * @description
  12258. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12259. * callback that was passed in the request.
  12260. */
  12261. wasCalled: function(callbackPath) {
  12262. return callbackMap[callbackPath].called;
  12263. },
  12264. /**
  12265. * @ngdoc method
  12266. * @name $jsonpCallbacks#getResponse
  12267. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12268. * @returns {*} the data received from the response via the registered callback
  12269. * @description
  12270. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12271. * in the JSONP response.
  12272. */
  12273. getResponse: function(callbackPath) {
  12274. return callbackMap[callbackPath].data;
  12275. },
  12276. /**
  12277. * @ngdoc method
  12278. * @name $jsonpCallbacks#removeCallback
  12279. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12280. * @description
  12281. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12282. * completed or timed-out.
  12283. */
  12284. removeCallback: function(callbackPath) {
  12285. var callback = callbackMap[callbackPath];
  12286. delete callbacks[callback.id];
  12287. delete callbackMap[callbackPath];
  12288. }
  12289. };
  12290. };
  12291. };
  12292. /**
  12293. * @ngdoc service
  12294. * @name $locale
  12295. *
  12296. * @description
  12297. * $locale service provides localization rules for various AngularJS components. As of right now the
  12298. * only public api is:
  12299. *
  12300. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12301. */
  12302. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12303. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12304. var $locationMinErr = minErr('$location');
  12305. /**
  12306. * Encode path using encodeUriSegment, ignoring forward slashes
  12307. *
  12308. * @param {string} path Path to encode
  12309. * @returns {string}
  12310. */
  12311. function encodePath(path) {
  12312. var segments = path.split('/'),
  12313. i = segments.length;
  12314. while (i--) {
  12315. // decode forward slashes to prevent them from being double encoded
  12316. segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
  12317. }
  12318. return segments.join('/');
  12319. }
  12320. function decodePath(path, html5Mode) {
  12321. var segments = path.split('/'),
  12322. i = segments.length;
  12323. while (i--) {
  12324. segments[i] = decodeURIComponent(segments[i]);
  12325. if (html5Mode) {
  12326. // encode forward slashes to prevent them from being mistaken for path separators
  12327. segments[i] = segments[i].replace(/\//g, '%2F');
  12328. }
  12329. }
  12330. return segments.join('/');
  12331. }
  12332. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  12333. var parsedUrl = urlResolve(absoluteUrl);
  12334. locationObj.$$protocol = parsedUrl.protocol;
  12335. locationObj.$$host = parsedUrl.hostname;
  12336. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  12337. }
  12338. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  12339. function parseAppUrl(url, locationObj, html5Mode) {
  12340. if (DOUBLE_SLASH_REGEX.test(url)) {
  12341. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  12342. }
  12343. var prefixed = (url.charAt(0) !== '/');
  12344. if (prefixed) {
  12345. url = '/' + url;
  12346. }
  12347. var match = urlResolve(url);
  12348. var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
  12349. locationObj.$$path = decodePath(path, html5Mode);
  12350. locationObj.$$search = parseKeyValue(match.search);
  12351. locationObj.$$hash = decodeURIComponent(match.hash);
  12352. // make sure path starts with '/';
  12353. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  12354. locationObj.$$path = '/' + locationObj.$$path;
  12355. }
  12356. }
  12357. function startsWith(str, search) {
  12358. return str.slice(0, search.length) === search;
  12359. }
  12360. /**
  12361. *
  12362. * @param {string} base
  12363. * @param {string} url
  12364. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  12365. * the expected string.
  12366. */
  12367. function stripBaseUrl(base, url) {
  12368. if (startsWith(url, base)) {
  12369. return url.substr(base.length);
  12370. }
  12371. }
  12372. function stripHash(url) {
  12373. var index = url.indexOf('#');
  12374. return index === -1 ? url : url.substr(0, index);
  12375. }
  12376. function trimEmptyHash(url) {
  12377. return url.replace(/(#.+)|#$/, '$1');
  12378. }
  12379. function stripFile(url) {
  12380. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  12381. }
  12382. /* return the server only (scheme://host:port) */
  12383. function serverBase(url) {
  12384. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  12385. }
  12386. /**
  12387. * LocationHtml5Url represents a URL
  12388. * This object is exposed as $location service when HTML5 mode is enabled and supported
  12389. *
  12390. * @constructor
  12391. * @param {string} appBase application base URL
  12392. * @param {string} appBaseNoFile application base URL stripped of any filename
  12393. * @param {string} basePrefix URL path prefix
  12394. */
  12395. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  12396. this.$$html5 = true;
  12397. basePrefix = basePrefix || '';
  12398. parseAbsoluteUrl(appBase, this);
  12399. /**
  12400. * Parse given HTML5 (regular) URL string into properties
  12401. * @param {string} url HTML5 URL
  12402. * @private
  12403. */
  12404. this.$$parse = function(url) {
  12405. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12406. if (!isString(pathUrl)) {
  12407. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12408. appBaseNoFile);
  12409. }
  12410. parseAppUrl(pathUrl, this, true);
  12411. if (!this.$$path) {
  12412. this.$$path = '/';
  12413. }
  12414. this.$$compose();
  12415. };
  12416. /**
  12417. * Compose url and update `absUrl` property
  12418. * @private
  12419. */
  12420. this.$$compose = function() {
  12421. var search = toKeyValue(this.$$search),
  12422. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12423. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12424. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12425. this.$$urlUpdatedByLocation = true;
  12426. };
  12427. this.$$parseLinkUrl = function(url, relHref) {
  12428. if (relHref && relHref[0] === '#') {
  12429. // special case for links to hash fragments:
  12430. // keep the old url and only replace the hash fragment
  12431. this.hash(relHref.slice(1));
  12432. return true;
  12433. }
  12434. var appUrl, prevAppUrl;
  12435. var rewrittenUrl;
  12436. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12437. prevAppUrl = appUrl;
  12438. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12439. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12440. } else {
  12441. rewrittenUrl = appBase + prevAppUrl;
  12442. }
  12443. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12444. rewrittenUrl = appBaseNoFile + appUrl;
  12445. } else if (appBaseNoFile === url + '/') {
  12446. rewrittenUrl = appBaseNoFile;
  12447. }
  12448. if (rewrittenUrl) {
  12449. this.$$parse(rewrittenUrl);
  12450. }
  12451. return !!rewrittenUrl;
  12452. };
  12453. }
  12454. /**
  12455. * LocationHashbangUrl represents URL
  12456. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12457. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12458. *
  12459. * @constructor
  12460. * @param {string} appBase application base URL
  12461. * @param {string} appBaseNoFile application base URL stripped of any filename
  12462. * @param {string} hashPrefix hashbang prefix
  12463. */
  12464. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12465. parseAbsoluteUrl(appBase, this);
  12466. /**
  12467. * Parse given hashbang URL into properties
  12468. * @param {string} url Hashbang URL
  12469. * @private
  12470. */
  12471. this.$$parse = function(url) {
  12472. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12473. var withoutHashUrl;
  12474. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12475. // The rest of the URL starts with a hash so we have
  12476. // got either a hashbang path or a plain hash fragment
  12477. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12478. if (isUndefined(withoutHashUrl)) {
  12479. // There was no hashbang prefix so we just have a hash fragment
  12480. withoutHashUrl = withoutBaseUrl;
  12481. }
  12482. } else {
  12483. // There was no hashbang path nor hash fragment:
  12484. // If we are in HTML5 mode we use what is left as the path;
  12485. // Otherwise we ignore what is left
  12486. if (this.$$html5) {
  12487. withoutHashUrl = withoutBaseUrl;
  12488. } else {
  12489. withoutHashUrl = '';
  12490. if (isUndefined(withoutBaseUrl)) {
  12491. appBase = url;
  12492. /** @type {?} */ (this).replace();
  12493. }
  12494. }
  12495. }
  12496. parseAppUrl(withoutHashUrl, this, false);
  12497. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12498. this.$$compose();
  12499. /*
  12500. * In Windows, on an anchor node on documents loaded from
  12501. * the filesystem, the browser will return a pathname
  12502. * prefixed with the drive name ('/C:/path') when a
  12503. * pathname without a drive is set:
  12504. * * a.setAttribute('href', '/foo')
  12505. * * a.pathname === '/C:/foo' //true
  12506. *
  12507. * Inside of AngularJS, we're always using pathnames that
  12508. * do not include drive names for routing.
  12509. */
  12510. function removeWindowsDriveName(path, url, base) {
  12511. /*
  12512. Matches paths for file protocol on windows,
  12513. such as /C:/foo/bar, and captures only /foo/bar.
  12514. */
  12515. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12516. var firstPathSegmentMatch;
  12517. //Get the relative path from the input URL.
  12518. if (startsWith(url, base)) {
  12519. url = url.replace(base, '');
  12520. }
  12521. // The input URL intentionally contains a first path segment that ends with a colon.
  12522. if (windowsFilePathExp.exec(url)) {
  12523. return path;
  12524. }
  12525. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12526. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12527. }
  12528. };
  12529. /**
  12530. * Compose hashbang URL and update `absUrl` property
  12531. * @private
  12532. */
  12533. this.$$compose = function() {
  12534. var search = toKeyValue(this.$$search),
  12535. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12536. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12537. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12538. this.$$urlUpdatedByLocation = true;
  12539. };
  12540. this.$$parseLinkUrl = function(url, relHref) {
  12541. if (stripHash(appBase) === stripHash(url)) {
  12542. this.$$parse(url);
  12543. return true;
  12544. }
  12545. return false;
  12546. };
  12547. }
  12548. /**
  12549. * LocationHashbangUrl represents URL
  12550. * This object is exposed as $location service when html5 history api is enabled but the browser
  12551. * does not support it.
  12552. *
  12553. * @constructor
  12554. * @param {string} appBase application base URL
  12555. * @param {string} appBaseNoFile application base URL stripped of any filename
  12556. * @param {string} hashPrefix hashbang prefix
  12557. */
  12558. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12559. this.$$html5 = true;
  12560. LocationHashbangUrl.apply(this, arguments);
  12561. this.$$parseLinkUrl = function(url, relHref) {
  12562. if (relHref && relHref[0] === '#') {
  12563. // special case for links to hash fragments:
  12564. // keep the old url and only replace the hash fragment
  12565. this.hash(relHref.slice(1));
  12566. return true;
  12567. }
  12568. var rewrittenUrl;
  12569. var appUrl;
  12570. if (appBase === stripHash(url)) {
  12571. rewrittenUrl = url;
  12572. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12573. rewrittenUrl = appBase + hashPrefix + appUrl;
  12574. } else if (appBaseNoFile === url + '/') {
  12575. rewrittenUrl = appBaseNoFile;
  12576. }
  12577. if (rewrittenUrl) {
  12578. this.$$parse(rewrittenUrl);
  12579. }
  12580. return !!rewrittenUrl;
  12581. };
  12582. this.$$compose = function() {
  12583. var search = toKeyValue(this.$$search),
  12584. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12585. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12586. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12587. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12588. this.$$urlUpdatedByLocation = true;
  12589. };
  12590. }
  12591. var locationPrototype = {
  12592. /**
  12593. * Ensure absolute URL is initialized.
  12594. * @private
  12595. */
  12596. $$absUrl:'',
  12597. /**
  12598. * Are we in html5 mode?
  12599. * @private
  12600. */
  12601. $$html5: false,
  12602. /**
  12603. * Has any change been replacing?
  12604. * @private
  12605. */
  12606. $$replace: false,
  12607. /**
  12608. * @ngdoc method
  12609. * @name $location#absUrl
  12610. *
  12611. * @description
  12612. * This method is getter only.
  12613. *
  12614. * Return full URL representation with all segments encoded according to rules specified in
  12615. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12616. *
  12617. *
  12618. * ```js
  12619. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12620. * var absUrl = $location.absUrl();
  12621. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12622. * ```
  12623. *
  12624. * @return {string} full URL
  12625. */
  12626. absUrl: locationGetter('$$absUrl'),
  12627. /**
  12628. * @ngdoc method
  12629. * @name $location#url
  12630. *
  12631. * @description
  12632. * This method is getter / setter.
  12633. *
  12634. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12635. *
  12636. * Change path, search and hash, when called with parameter and return `$location`.
  12637. *
  12638. *
  12639. * ```js
  12640. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12641. * var url = $location.url();
  12642. * // => "/some/path?foo=bar&baz=xoxo"
  12643. * ```
  12644. *
  12645. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12646. * @return {string} url
  12647. */
  12648. url: function(url) {
  12649. if (isUndefined(url)) {
  12650. return this.$$url;
  12651. }
  12652. var match = PATH_MATCH.exec(url);
  12653. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12654. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12655. this.hash(match[5] || '');
  12656. return this;
  12657. },
  12658. /**
  12659. * @ngdoc method
  12660. * @name $location#protocol
  12661. *
  12662. * @description
  12663. * This method is getter only.
  12664. *
  12665. * Return protocol of current URL.
  12666. *
  12667. *
  12668. * ```js
  12669. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12670. * var protocol = $location.protocol();
  12671. * // => "http"
  12672. * ```
  12673. *
  12674. * @return {string} protocol of current URL
  12675. */
  12676. protocol: locationGetter('$$protocol'),
  12677. /**
  12678. * @ngdoc method
  12679. * @name $location#host
  12680. *
  12681. * @description
  12682. * This method is getter only.
  12683. *
  12684. * Return host of current URL.
  12685. *
  12686. * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12687. *
  12688. *
  12689. * ```js
  12690. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12691. * var host = $location.host();
  12692. * // => "example.com"
  12693. *
  12694. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12695. * host = $location.host();
  12696. * // => "example.com"
  12697. * host = location.host;
  12698. * // => "example.com:8080"
  12699. * ```
  12700. *
  12701. * @return {string} host of current URL.
  12702. */
  12703. host: locationGetter('$$host'),
  12704. /**
  12705. * @ngdoc method
  12706. * @name $location#port
  12707. *
  12708. * @description
  12709. * This method is getter only.
  12710. *
  12711. * Return port of current URL.
  12712. *
  12713. *
  12714. * ```js
  12715. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12716. * var port = $location.port();
  12717. * // => 80
  12718. * ```
  12719. *
  12720. * @return {Number} port
  12721. */
  12722. port: locationGetter('$$port'),
  12723. /**
  12724. * @ngdoc method
  12725. * @name $location#path
  12726. *
  12727. * @description
  12728. * This method is getter / setter.
  12729. *
  12730. * Return path of current URL when called without any parameter.
  12731. *
  12732. * Change path when called with parameter and return `$location`.
  12733. *
  12734. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12735. * if it is missing.
  12736. *
  12737. *
  12738. * ```js
  12739. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12740. * var path = $location.path();
  12741. * // => "/some/path"
  12742. * ```
  12743. *
  12744. * @param {(string|number)=} path New path
  12745. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12746. */
  12747. path: locationGetterSetter('$$path', function(path) {
  12748. path = path !== null ? path.toString() : '';
  12749. return path.charAt(0) === '/' ? path : '/' + path;
  12750. }),
  12751. /**
  12752. * @ngdoc method
  12753. * @name $location#search
  12754. *
  12755. * @description
  12756. * This method is getter / setter.
  12757. *
  12758. * Return search part (as object) of current URL when called without any parameter.
  12759. *
  12760. * Change search part when called with parameter and return `$location`.
  12761. *
  12762. *
  12763. * ```js
  12764. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12765. * var searchObject = $location.search();
  12766. * // => {foo: 'bar', baz: 'xoxo'}
  12767. *
  12768. * // set foo to 'yipee'
  12769. * $location.search('foo', 'yipee');
  12770. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12771. * ```
  12772. *
  12773. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12774. * hash object.
  12775. *
  12776. * When called with a single argument the method acts as a setter, setting the `search` component
  12777. * of `$location` to the specified value.
  12778. *
  12779. * If the argument is a hash object containing an array of values, these values will be encoded
  12780. * as duplicate search parameters in the URL.
  12781. *
  12782. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12783. * will override only a single search property.
  12784. *
  12785. * If `paramValue` is an array, it will override the property of the `search` component of
  12786. * `$location` specified via the first argument.
  12787. *
  12788. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12789. *
  12790. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12791. * value nor trailing equal sign.
  12792. *
  12793. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12794. * one or more arguments returns `$location` object itself.
  12795. */
  12796. search: function(search, paramValue) {
  12797. switch (arguments.length) {
  12798. case 0:
  12799. return this.$$search;
  12800. case 1:
  12801. if (isString(search) || isNumber(search)) {
  12802. search = search.toString();
  12803. this.$$search = parseKeyValue(search);
  12804. } else if (isObject(search)) {
  12805. search = copy(search, {});
  12806. // remove object undefined or null properties
  12807. forEach(search, function(value, key) {
  12808. if (value == null) delete search[key];
  12809. });
  12810. this.$$search = search;
  12811. } else {
  12812. throw $locationMinErr('isrcharg',
  12813. 'The first argument of the `$location#search()` call must be a string or an object.');
  12814. }
  12815. break;
  12816. default:
  12817. if (isUndefined(paramValue) || paramValue === null) {
  12818. delete this.$$search[search];
  12819. } else {
  12820. this.$$search[search] = paramValue;
  12821. }
  12822. }
  12823. this.$$compose();
  12824. return this;
  12825. },
  12826. /**
  12827. * @ngdoc method
  12828. * @name $location#hash
  12829. *
  12830. * @description
  12831. * This method is getter / setter.
  12832. *
  12833. * Returns the hash fragment when called without any parameters.
  12834. *
  12835. * Changes the hash fragment when called with a parameter and returns `$location`.
  12836. *
  12837. *
  12838. * ```js
  12839. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12840. * var hash = $location.hash();
  12841. * // => "hashValue"
  12842. * ```
  12843. *
  12844. * @param {(string|number)=} hash New hash fragment
  12845. * @return {string} hash
  12846. */
  12847. hash: locationGetterSetter('$$hash', function(hash) {
  12848. return hash !== null ? hash.toString() : '';
  12849. }),
  12850. /**
  12851. * @ngdoc method
  12852. * @name $location#replace
  12853. *
  12854. * @description
  12855. * If called, all changes to $location during the current `$digest` will replace the current history
  12856. * record, instead of adding a new one.
  12857. */
  12858. replace: function() {
  12859. this.$$replace = true;
  12860. return this;
  12861. }
  12862. };
  12863. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12864. Location.prototype = Object.create(locationPrototype);
  12865. /**
  12866. * @ngdoc method
  12867. * @name $location#state
  12868. *
  12869. * @description
  12870. * This method is getter / setter.
  12871. *
  12872. * Return the history state object when called without any parameter.
  12873. *
  12874. * Change the history state object when called with one parameter and return `$location`.
  12875. * The state object is later passed to `pushState` or `replaceState`.
  12876. *
  12877. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12878. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12879. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12880. *
  12881. * @param {object=} state State object for pushState or replaceState
  12882. * @return {object} state
  12883. */
  12884. Location.prototype.state = function(state) {
  12885. if (!arguments.length) {
  12886. return this.$$state;
  12887. }
  12888. if (Location !== LocationHtml5Url || !this.$$html5) {
  12889. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12890. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12891. }
  12892. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12893. // but we're changing the $$state reference to $browser.state() during the $digest
  12894. // so the modification window is narrow.
  12895. this.$$state = isUndefined(state) ? null : state;
  12896. this.$$urlUpdatedByLocation = true;
  12897. return this;
  12898. };
  12899. });
  12900. function locationGetter(property) {
  12901. return /** @this */ function() {
  12902. return this[property];
  12903. };
  12904. }
  12905. function locationGetterSetter(property, preprocess) {
  12906. return /** @this */ function(value) {
  12907. if (isUndefined(value)) {
  12908. return this[property];
  12909. }
  12910. this[property] = preprocess(value);
  12911. this.$$compose();
  12912. return this;
  12913. };
  12914. }
  12915. /**
  12916. * @ngdoc service
  12917. * @name $location
  12918. *
  12919. * @requires $rootElement
  12920. *
  12921. * @description
  12922. * The $location service parses the URL in the browser address bar (based on the
  12923. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12924. * available to your application. Changes to the URL in the address bar are reflected into
  12925. * $location service and changes to $location are reflected into the browser address bar.
  12926. *
  12927. * **The $location service:**
  12928. *
  12929. * - Exposes the current URL in the browser address bar, so you can
  12930. * - Watch and observe the URL.
  12931. * - Change the URL.
  12932. * - Synchronizes the URL with the browser when the user
  12933. * - Changes the address bar.
  12934. * - Clicks the back or forward button (or clicks a History link).
  12935. * - Clicks on a link.
  12936. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12937. *
  12938. * For more information see {@link guide/$location Developer Guide: Using $location}
  12939. */
  12940. /**
  12941. * @ngdoc provider
  12942. * @name $locationProvider
  12943. * @this
  12944. *
  12945. * @description
  12946. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12947. */
  12948. function $LocationProvider() {
  12949. var hashPrefix = '!',
  12950. html5Mode = {
  12951. enabled: false,
  12952. requireBase: true,
  12953. rewriteLinks: true
  12954. };
  12955. /**
  12956. * @ngdoc method
  12957. * @name $locationProvider#hashPrefix
  12958. * @description
  12959. * The default value for the prefix is `'!'`.
  12960. * @param {string=} prefix Prefix for hash part (containing path and search)
  12961. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12962. */
  12963. this.hashPrefix = function(prefix) {
  12964. if (isDefined(prefix)) {
  12965. hashPrefix = prefix;
  12966. return this;
  12967. } else {
  12968. return hashPrefix;
  12969. }
  12970. };
  12971. /**
  12972. * @ngdoc method
  12973. * @name $locationProvider#html5Mode
  12974. * @description
  12975. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12976. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12977. * properties:
  12978. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12979. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12980. * support `pushState`.
  12981. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12982. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12983. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12984. * See the {@link guide/$location $location guide for more information}
  12985. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12986. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12987. * only happen on links with an attribute that matches the given string. For example, if set
  12988. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12989. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12990. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12991. *
  12992. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12993. */
  12994. this.html5Mode = function(mode) {
  12995. if (isBoolean(mode)) {
  12996. html5Mode.enabled = mode;
  12997. return this;
  12998. } else if (isObject(mode)) {
  12999. if (isBoolean(mode.enabled)) {
  13000. html5Mode.enabled = mode.enabled;
  13001. }
  13002. if (isBoolean(mode.requireBase)) {
  13003. html5Mode.requireBase = mode.requireBase;
  13004. }
  13005. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  13006. html5Mode.rewriteLinks = mode.rewriteLinks;
  13007. }
  13008. return this;
  13009. } else {
  13010. return html5Mode;
  13011. }
  13012. };
  13013. /**
  13014. * @ngdoc event
  13015. * @name $location#$locationChangeStart
  13016. * @eventType broadcast on root scope
  13017. * @description
  13018. * Broadcasted before a URL will change.
  13019. *
  13020. * This change can be prevented by calling
  13021. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  13022. * details about event object. Upon successful change
  13023. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  13024. *
  13025. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13026. * the browser supports the HTML5 History API.
  13027. *
  13028. * @param {Object} angularEvent Synthetic event object.
  13029. * @param {string} newUrl New URL
  13030. * @param {string=} oldUrl URL that was before it was changed.
  13031. * @param {string=} newState New history state object
  13032. * @param {string=} oldState History state object that was before it was changed.
  13033. */
  13034. /**
  13035. * @ngdoc event
  13036. * @name $location#$locationChangeSuccess
  13037. * @eventType broadcast on root scope
  13038. * @description
  13039. * Broadcasted after a URL was changed.
  13040. *
  13041. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13042. * the browser supports the HTML5 History API.
  13043. *
  13044. * @param {Object} angularEvent Synthetic event object.
  13045. * @param {string} newUrl New URL
  13046. * @param {string=} oldUrl URL that was before it was changed.
  13047. * @param {string=} newState New history state object
  13048. * @param {string=} oldState History state object that was before it was changed.
  13049. */
  13050. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  13051. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  13052. var $location,
  13053. LocationMode,
  13054. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  13055. initialUrl = $browser.url(),
  13056. appBase;
  13057. if (html5Mode.enabled) {
  13058. if (!baseHref && html5Mode.requireBase) {
  13059. throw $locationMinErr('nobase',
  13060. '$location in HTML5 mode requires a <base> tag to be present!');
  13061. }
  13062. appBase = serverBase(initialUrl) + (baseHref || '/');
  13063. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  13064. } else {
  13065. appBase = stripHash(initialUrl);
  13066. LocationMode = LocationHashbangUrl;
  13067. }
  13068. var appBaseNoFile = stripFile(appBase);
  13069. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  13070. $location.$$parseLinkUrl(initialUrl, initialUrl);
  13071. $location.$$state = $browser.state();
  13072. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  13073. function setBrowserUrlWithFallback(url, replace, state) {
  13074. var oldUrl = $location.url();
  13075. var oldState = $location.$$state;
  13076. try {
  13077. $browser.url(url, replace, state);
  13078. // Make sure $location.state() returns referentially identical (not just deeply equal)
  13079. // state object; this makes possible quick checking if the state changed in the digest
  13080. // loop. Checking deep equality would be too expensive.
  13081. $location.$$state = $browser.state();
  13082. } catch (e) {
  13083. // Restore old values if pushState fails
  13084. $location.url(oldUrl);
  13085. $location.$$state = oldState;
  13086. throw e;
  13087. }
  13088. }
  13089. $rootElement.on('click', function(event) {
  13090. var rewriteLinks = html5Mode.rewriteLinks;
  13091. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  13092. // currently we open nice url link and redirect then
  13093. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  13094. var elm = jqLite(event.target);
  13095. // traverse the DOM up to find first A tag
  13096. while (nodeName_(elm[0]) !== 'a') {
  13097. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  13098. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  13099. }
  13100. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  13101. var absHref = elm.prop('href');
  13102. // get the actual href attribute - see
  13103. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  13104. var relHref = elm.attr('href') || elm.attr('xlink:href');
  13105. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  13106. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  13107. // an animation.
  13108. absHref = urlResolve(absHref.animVal).href;
  13109. }
  13110. // Ignore when url is started with javascript: or mailto:
  13111. if (IGNORE_URI_REGEXP.test(absHref)) return;
  13112. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  13113. if ($location.$$parseLinkUrl(absHref, relHref)) {
  13114. // We do a preventDefault for all urls that are part of the AngularJS application,
  13115. // in html5mode and also without, so that we are able to abort navigation without
  13116. // getting double entries in the location history.
  13117. event.preventDefault();
  13118. // update location manually
  13119. if ($location.absUrl() !== $browser.url()) {
  13120. $rootScope.$apply();
  13121. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  13122. $window.angular['ff-684208-preventDefault'] = true;
  13123. }
  13124. }
  13125. }
  13126. });
  13127. // rewrite hashbang url <> html5 url
  13128. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  13129. $browser.url($location.absUrl(), true);
  13130. }
  13131. var initializing = true;
  13132. // update $location when $browser url changes
  13133. $browser.onUrlChange(function(newUrl, newState) {
  13134. if (!startsWith(newUrl, appBaseNoFile)) {
  13135. // If we are navigating outside of the app then force a reload
  13136. $window.location.href = newUrl;
  13137. return;
  13138. }
  13139. $rootScope.$evalAsync(function() {
  13140. var oldUrl = $location.absUrl();
  13141. var oldState = $location.$$state;
  13142. var defaultPrevented;
  13143. newUrl = trimEmptyHash(newUrl);
  13144. $location.$$parse(newUrl);
  13145. $location.$$state = newState;
  13146. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13147. newState, oldState).defaultPrevented;
  13148. // if the location was changed by a `$locationChangeStart` handler then stop
  13149. // processing this location change
  13150. if ($location.absUrl() !== newUrl) return;
  13151. if (defaultPrevented) {
  13152. $location.$$parse(oldUrl);
  13153. $location.$$state = oldState;
  13154. setBrowserUrlWithFallback(oldUrl, false, oldState);
  13155. } else {
  13156. initializing = false;
  13157. afterLocationChange(oldUrl, oldState);
  13158. }
  13159. });
  13160. if (!$rootScope.$$phase) $rootScope.$digest();
  13161. });
  13162. // update browser
  13163. $rootScope.$watch(function $locationWatch() {
  13164. if (initializing || $location.$$urlUpdatedByLocation) {
  13165. $location.$$urlUpdatedByLocation = false;
  13166. var oldUrl = trimEmptyHash($browser.url());
  13167. var newUrl = trimEmptyHash($location.absUrl());
  13168. var oldState = $browser.state();
  13169. var currentReplace = $location.$$replace;
  13170. var urlOrStateChanged = oldUrl !== newUrl ||
  13171. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  13172. if (initializing || urlOrStateChanged) {
  13173. initializing = false;
  13174. $rootScope.$evalAsync(function() {
  13175. var newUrl = $location.absUrl();
  13176. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13177. $location.$$state, oldState).defaultPrevented;
  13178. // if the location was changed by a `$locationChangeStart` handler then stop
  13179. // processing this location change
  13180. if ($location.absUrl() !== newUrl) return;
  13181. if (defaultPrevented) {
  13182. $location.$$parse(oldUrl);
  13183. $location.$$state = oldState;
  13184. } else {
  13185. if (urlOrStateChanged) {
  13186. setBrowserUrlWithFallback(newUrl, currentReplace,
  13187. oldState === $location.$$state ? null : $location.$$state);
  13188. }
  13189. afterLocationChange(oldUrl, oldState);
  13190. }
  13191. });
  13192. }
  13193. }
  13194. $location.$$replace = false;
  13195. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  13196. // there is a change
  13197. });
  13198. return $location;
  13199. function afterLocationChange(oldUrl, oldState) {
  13200. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  13201. $location.$$state, oldState);
  13202. }
  13203. }];
  13204. }
  13205. /**
  13206. * @ngdoc service
  13207. * @name $log
  13208. * @requires $window
  13209. *
  13210. * @description
  13211. * Simple service for logging. Default implementation safely writes the message
  13212. * into the browser's console (if present).
  13213. *
  13214. * The main purpose of this service is to simplify debugging and troubleshooting.
  13215. *
  13216. * To reveal the location of the calls to `$log` in the JavaScript console,
  13217. * you can "blackbox" the AngularJS source in your browser:
  13218. *
  13219. * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).
  13220. * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).
  13221. *
  13222. * Note: Not all browsers support blackboxing.
  13223. *
  13224. * The default is to log `debug` messages. You can use
  13225. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  13226. *
  13227. * @example
  13228. <example module="logExample" name="log-service">
  13229. <file name="script.js">
  13230. angular.module('logExample', [])
  13231. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  13232. $scope.$log = $log;
  13233. $scope.message = 'Hello World!';
  13234. }]);
  13235. </file>
  13236. <file name="index.html">
  13237. <div ng-controller="LogController">
  13238. <p>Reload this page with open console, enter text and hit the log button...</p>
  13239. <label>Message:
  13240. <input type="text" ng-model="message" /></label>
  13241. <button ng-click="$log.log(message)">log</button>
  13242. <button ng-click="$log.warn(message)">warn</button>
  13243. <button ng-click="$log.info(message)">info</button>
  13244. <button ng-click="$log.error(message)">error</button>
  13245. <button ng-click="$log.debug(message)">debug</button>
  13246. </div>
  13247. </file>
  13248. </example>
  13249. */
  13250. /**
  13251. * @ngdoc provider
  13252. * @name $logProvider
  13253. * @this
  13254. *
  13255. * @description
  13256. * Use the `$logProvider` to configure how the application logs messages
  13257. */
  13258. function $LogProvider() {
  13259. var debug = true,
  13260. self = this;
  13261. /**
  13262. * @ngdoc method
  13263. * @name $logProvider#debugEnabled
  13264. * @description
  13265. * @param {boolean=} flag enable or disable debug level messages
  13266. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13267. */
  13268. this.debugEnabled = function(flag) {
  13269. if (isDefined(flag)) {
  13270. debug = flag;
  13271. return this;
  13272. } else {
  13273. return debug;
  13274. }
  13275. };
  13276. this.$get = ['$window', function($window) {
  13277. // Support: IE 9-11, Edge 12-14+
  13278. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13279. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13280. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13281. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13282. // traces along source maps if available so it makes sense to let browsers display it
  13283. // as they want.
  13284. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13285. return {
  13286. /**
  13287. * @ngdoc method
  13288. * @name $log#log
  13289. *
  13290. * @description
  13291. * Write a log message
  13292. */
  13293. log: consoleLog('log'),
  13294. /**
  13295. * @ngdoc method
  13296. * @name $log#info
  13297. *
  13298. * @description
  13299. * Write an information message
  13300. */
  13301. info: consoleLog('info'),
  13302. /**
  13303. * @ngdoc method
  13304. * @name $log#warn
  13305. *
  13306. * @description
  13307. * Write a warning message
  13308. */
  13309. warn: consoleLog('warn'),
  13310. /**
  13311. * @ngdoc method
  13312. * @name $log#error
  13313. *
  13314. * @description
  13315. * Write an error message
  13316. */
  13317. error: consoleLog('error'),
  13318. /**
  13319. * @ngdoc method
  13320. * @name $log#debug
  13321. *
  13322. * @description
  13323. * Write a debug message
  13324. */
  13325. debug: (function() {
  13326. var fn = consoleLog('debug');
  13327. return function() {
  13328. if (debug) {
  13329. fn.apply(self, arguments);
  13330. }
  13331. };
  13332. })()
  13333. };
  13334. function formatError(arg) {
  13335. if (isError(arg)) {
  13336. if (arg.stack && formatStackTrace) {
  13337. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  13338. ? 'Error: ' + arg.message + '\n' + arg.stack
  13339. : arg.stack;
  13340. } else if (arg.sourceURL) {
  13341. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  13342. }
  13343. }
  13344. return arg;
  13345. }
  13346. function consoleLog(type) {
  13347. var console = $window.console || {},
  13348. logFn = console[type] || console.log || noop;
  13349. return function() {
  13350. var args = [];
  13351. forEach(arguments, function(arg) {
  13352. args.push(formatError(arg));
  13353. });
  13354. // Support: IE 9 only
  13355. // console methods don't inherit from Function.prototype in IE 9 so we can't
  13356. // call `logFn.apply(console, args)` directly.
  13357. return Function.prototype.apply.call(logFn, console, args);
  13358. };
  13359. }
  13360. }];
  13361. }
  13362. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13363. * Any commits to this file should be reviewed with security in mind. *
  13364. * Changes to this file can potentially create security vulnerabilities. *
  13365. * An approval from 2 Core members with history of modifying *
  13366. * this file is required. *
  13367. * *
  13368. * Does the change somehow allow for arbitrary javascript to be executed? *
  13369. * Or allows for someone to change the prototype of built-in objects? *
  13370. * Or gives undesired access to variables likes document or window? *
  13371. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13372. var $parseMinErr = minErr('$parse');
  13373. var objectValueOf = {}.constructor.prototype.valueOf;
  13374. // Sandboxing AngularJS Expressions
  13375. // ------------------------------
  13376. // AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  13377. // various means such as obtaining a reference to native JS functions like the Function constructor.
  13378. //
  13379. // As an example, consider the following AngularJS expression:
  13380. //
  13381. // {}.toString.constructor('alert("evil JS code")')
  13382. //
  13383. // It is important to realize that if you create an expression from a string that contains user provided
  13384. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  13385. //
  13386. // See https://docs.angularjs.org/guide/security
  13387. function getStringValue(name) {
  13388. // Property names must be strings. This means that non-string objects cannot be used
  13389. // as keys in an object. Any non-string object, including a number, is typecasted
  13390. // into a string via the toString method.
  13391. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  13392. //
  13393. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  13394. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  13395. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  13396. //
  13397. // TypeError: Cannot convert object to primitive value
  13398. //
  13399. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  13400. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  13401. // such a 'broken' object as a key.
  13402. return name + '';
  13403. }
  13404. var OPERATORS = createMap();
  13405. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13406. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13407. /////////////////////////////////////////
  13408. /**
  13409. * @constructor
  13410. */
  13411. var Lexer = function Lexer(options) {
  13412. this.options = options;
  13413. };
  13414. Lexer.prototype = {
  13415. constructor: Lexer,
  13416. lex: function(text) {
  13417. this.text = text;
  13418. this.index = 0;
  13419. this.tokens = [];
  13420. while (this.index < this.text.length) {
  13421. var ch = this.text.charAt(this.index);
  13422. if (ch === '"' || ch === '\'') {
  13423. this.readString(ch);
  13424. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13425. this.readNumber();
  13426. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13427. this.readIdent();
  13428. } else if (this.is(ch, '(){}[].,;:?')) {
  13429. this.tokens.push({index: this.index, text: ch});
  13430. this.index++;
  13431. } else if (this.isWhitespace(ch)) {
  13432. this.index++;
  13433. } else {
  13434. var ch2 = ch + this.peek();
  13435. var ch3 = ch2 + this.peek(2);
  13436. var op1 = OPERATORS[ch];
  13437. var op2 = OPERATORS[ch2];
  13438. var op3 = OPERATORS[ch3];
  13439. if (op1 || op2 || op3) {
  13440. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13441. this.tokens.push({index: this.index, text: token, operator: true});
  13442. this.index += token.length;
  13443. } else {
  13444. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13445. }
  13446. }
  13447. }
  13448. return this.tokens;
  13449. },
  13450. is: function(ch, chars) {
  13451. return chars.indexOf(ch) !== -1;
  13452. },
  13453. peek: function(i) {
  13454. var num = i || 1;
  13455. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13456. },
  13457. isNumber: function(ch) {
  13458. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13459. },
  13460. isWhitespace: function(ch) {
  13461. // IE treats non-breaking space as \u00A0
  13462. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13463. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13464. },
  13465. isIdentifierStart: function(ch) {
  13466. return this.options.isIdentifierStart ?
  13467. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13468. this.isValidIdentifierStart(ch);
  13469. },
  13470. isValidIdentifierStart: function(ch) {
  13471. return ('a' <= ch && ch <= 'z' ||
  13472. 'A' <= ch && ch <= 'Z' ||
  13473. '_' === ch || ch === '$');
  13474. },
  13475. isIdentifierContinue: function(ch) {
  13476. return this.options.isIdentifierContinue ?
  13477. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13478. this.isValidIdentifierContinue(ch);
  13479. },
  13480. isValidIdentifierContinue: function(ch, cp) {
  13481. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13482. },
  13483. codePointAt: function(ch) {
  13484. if (ch.length === 1) return ch.charCodeAt(0);
  13485. // eslint-disable-next-line no-bitwise
  13486. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13487. },
  13488. peekMultichar: function() {
  13489. var ch = this.text.charAt(this.index);
  13490. var peek = this.peek();
  13491. if (!peek) {
  13492. return ch;
  13493. }
  13494. var cp1 = ch.charCodeAt(0);
  13495. var cp2 = peek.charCodeAt(0);
  13496. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13497. return ch + peek;
  13498. }
  13499. return ch;
  13500. },
  13501. isExpOperator: function(ch) {
  13502. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13503. },
  13504. throwError: function(error, start, end) {
  13505. end = end || this.index;
  13506. var colStr = (isDefined(start)
  13507. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13508. : ' ' + end);
  13509. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13510. error, colStr, this.text);
  13511. },
  13512. readNumber: function() {
  13513. var number = '';
  13514. var start = this.index;
  13515. while (this.index < this.text.length) {
  13516. var ch = lowercase(this.text.charAt(this.index));
  13517. if (ch === '.' || this.isNumber(ch)) {
  13518. number += ch;
  13519. } else {
  13520. var peekCh = this.peek();
  13521. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13522. number += ch;
  13523. } else if (this.isExpOperator(ch) &&
  13524. peekCh && this.isNumber(peekCh) &&
  13525. number.charAt(number.length - 1) === 'e') {
  13526. number += ch;
  13527. } else if (this.isExpOperator(ch) &&
  13528. (!peekCh || !this.isNumber(peekCh)) &&
  13529. number.charAt(number.length - 1) === 'e') {
  13530. this.throwError('Invalid exponent');
  13531. } else {
  13532. break;
  13533. }
  13534. }
  13535. this.index++;
  13536. }
  13537. this.tokens.push({
  13538. index: start,
  13539. text: number,
  13540. constant: true,
  13541. value: Number(number)
  13542. });
  13543. },
  13544. readIdent: function() {
  13545. var start = this.index;
  13546. this.index += this.peekMultichar().length;
  13547. while (this.index < this.text.length) {
  13548. var ch = this.peekMultichar();
  13549. if (!this.isIdentifierContinue(ch)) {
  13550. break;
  13551. }
  13552. this.index += ch.length;
  13553. }
  13554. this.tokens.push({
  13555. index: start,
  13556. text: this.text.slice(start, this.index),
  13557. identifier: true
  13558. });
  13559. },
  13560. readString: function(quote) {
  13561. var start = this.index;
  13562. this.index++;
  13563. var string = '';
  13564. var rawString = quote;
  13565. var escape = false;
  13566. while (this.index < this.text.length) {
  13567. var ch = this.text.charAt(this.index);
  13568. rawString += ch;
  13569. if (escape) {
  13570. if (ch === 'u') {
  13571. var hex = this.text.substring(this.index + 1, this.index + 5);
  13572. if (!hex.match(/[\da-f]{4}/i)) {
  13573. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13574. }
  13575. this.index += 4;
  13576. string += String.fromCharCode(parseInt(hex, 16));
  13577. } else {
  13578. var rep = ESCAPE[ch];
  13579. string = string + (rep || ch);
  13580. }
  13581. escape = false;
  13582. } else if (ch === '\\') {
  13583. escape = true;
  13584. } else if (ch === quote) {
  13585. this.index++;
  13586. this.tokens.push({
  13587. index: start,
  13588. text: rawString,
  13589. constant: true,
  13590. value: string
  13591. });
  13592. return;
  13593. } else {
  13594. string += ch;
  13595. }
  13596. this.index++;
  13597. }
  13598. this.throwError('Unterminated quote', start);
  13599. }
  13600. };
  13601. var AST = function AST(lexer, options) {
  13602. this.lexer = lexer;
  13603. this.options = options;
  13604. };
  13605. AST.Program = 'Program';
  13606. AST.ExpressionStatement = 'ExpressionStatement';
  13607. AST.AssignmentExpression = 'AssignmentExpression';
  13608. AST.ConditionalExpression = 'ConditionalExpression';
  13609. AST.LogicalExpression = 'LogicalExpression';
  13610. AST.BinaryExpression = 'BinaryExpression';
  13611. AST.UnaryExpression = 'UnaryExpression';
  13612. AST.CallExpression = 'CallExpression';
  13613. AST.MemberExpression = 'MemberExpression';
  13614. AST.Identifier = 'Identifier';
  13615. AST.Literal = 'Literal';
  13616. AST.ArrayExpression = 'ArrayExpression';
  13617. AST.Property = 'Property';
  13618. AST.ObjectExpression = 'ObjectExpression';
  13619. AST.ThisExpression = 'ThisExpression';
  13620. AST.LocalsExpression = 'LocalsExpression';
  13621. // Internal use only
  13622. AST.NGValueParameter = 'NGValueParameter';
  13623. AST.prototype = {
  13624. ast: function(text) {
  13625. this.text = text;
  13626. this.tokens = this.lexer.lex(text);
  13627. var value = this.program();
  13628. if (this.tokens.length !== 0) {
  13629. this.throwError('is an unexpected token', this.tokens[0]);
  13630. }
  13631. return value;
  13632. },
  13633. program: function() {
  13634. var body = [];
  13635. while (true) {
  13636. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13637. body.push(this.expressionStatement());
  13638. if (!this.expect(';')) {
  13639. return { type: AST.Program, body: body};
  13640. }
  13641. }
  13642. },
  13643. expressionStatement: function() {
  13644. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13645. },
  13646. filterChain: function() {
  13647. var left = this.expression();
  13648. while (this.expect('|')) {
  13649. left = this.filter(left);
  13650. }
  13651. return left;
  13652. },
  13653. expression: function() {
  13654. return this.assignment();
  13655. },
  13656. assignment: function() {
  13657. var result = this.ternary();
  13658. if (this.expect('=')) {
  13659. if (!isAssignable(result)) {
  13660. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13661. }
  13662. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13663. }
  13664. return result;
  13665. },
  13666. ternary: function() {
  13667. var test = this.logicalOR();
  13668. var alternate;
  13669. var consequent;
  13670. if (this.expect('?')) {
  13671. alternate = this.expression();
  13672. if (this.consume(':')) {
  13673. consequent = this.expression();
  13674. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13675. }
  13676. }
  13677. return test;
  13678. },
  13679. logicalOR: function() {
  13680. var left = this.logicalAND();
  13681. while (this.expect('||')) {
  13682. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13683. }
  13684. return left;
  13685. },
  13686. logicalAND: function() {
  13687. var left = this.equality();
  13688. while (this.expect('&&')) {
  13689. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13690. }
  13691. return left;
  13692. },
  13693. equality: function() {
  13694. var left = this.relational();
  13695. var token;
  13696. while ((token = this.expect('==','!=','===','!=='))) {
  13697. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13698. }
  13699. return left;
  13700. },
  13701. relational: function() {
  13702. var left = this.additive();
  13703. var token;
  13704. while ((token = this.expect('<', '>', '<=', '>='))) {
  13705. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13706. }
  13707. return left;
  13708. },
  13709. additive: function() {
  13710. var left = this.multiplicative();
  13711. var token;
  13712. while ((token = this.expect('+','-'))) {
  13713. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13714. }
  13715. return left;
  13716. },
  13717. multiplicative: function() {
  13718. var left = this.unary();
  13719. var token;
  13720. while ((token = this.expect('*','/','%'))) {
  13721. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13722. }
  13723. return left;
  13724. },
  13725. unary: function() {
  13726. var token;
  13727. if ((token = this.expect('+', '-', '!'))) {
  13728. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13729. } else {
  13730. return this.primary();
  13731. }
  13732. },
  13733. primary: function() {
  13734. var primary;
  13735. if (this.expect('(')) {
  13736. primary = this.filterChain();
  13737. this.consume(')');
  13738. } else if (this.expect('[')) {
  13739. primary = this.arrayDeclaration();
  13740. } else if (this.expect('{')) {
  13741. primary = this.object();
  13742. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13743. primary = copy(this.selfReferential[this.consume().text]);
  13744. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13745. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13746. } else if (this.peek().identifier) {
  13747. primary = this.identifier();
  13748. } else if (this.peek().constant) {
  13749. primary = this.constant();
  13750. } else {
  13751. this.throwError('not a primary expression', this.peek());
  13752. }
  13753. var next;
  13754. while ((next = this.expect('(', '[', '.'))) {
  13755. if (next.text === '(') {
  13756. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13757. this.consume(')');
  13758. } else if (next.text === '[') {
  13759. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13760. this.consume(']');
  13761. } else if (next.text === '.') {
  13762. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13763. } else {
  13764. this.throwError('IMPOSSIBLE');
  13765. }
  13766. }
  13767. return primary;
  13768. },
  13769. filter: function(baseExpression) {
  13770. var args = [baseExpression];
  13771. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13772. while (this.expect(':')) {
  13773. args.push(this.expression());
  13774. }
  13775. return result;
  13776. },
  13777. parseArguments: function() {
  13778. var args = [];
  13779. if (this.peekToken().text !== ')') {
  13780. do {
  13781. args.push(this.filterChain());
  13782. } while (this.expect(','));
  13783. }
  13784. return args;
  13785. },
  13786. identifier: function() {
  13787. var token = this.consume();
  13788. if (!token.identifier) {
  13789. this.throwError('is not a valid identifier', token);
  13790. }
  13791. return { type: AST.Identifier, name: token.text };
  13792. },
  13793. constant: function() {
  13794. // TODO check that it is a constant
  13795. return { type: AST.Literal, value: this.consume().value };
  13796. },
  13797. arrayDeclaration: function() {
  13798. var elements = [];
  13799. if (this.peekToken().text !== ']') {
  13800. do {
  13801. if (this.peek(']')) {
  13802. // Support trailing commas per ES5.1.
  13803. break;
  13804. }
  13805. elements.push(this.expression());
  13806. } while (this.expect(','));
  13807. }
  13808. this.consume(']');
  13809. return { type: AST.ArrayExpression, elements: elements };
  13810. },
  13811. object: function() {
  13812. var properties = [], property;
  13813. if (this.peekToken().text !== '}') {
  13814. do {
  13815. if (this.peek('}')) {
  13816. // Support trailing commas per ES5.1.
  13817. break;
  13818. }
  13819. property = {type: AST.Property, kind: 'init'};
  13820. if (this.peek().constant) {
  13821. property.key = this.constant();
  13822. property.computed = false;
  13823. this.consume(':');
  13824. property.value = this.expression();
  13825. } else if (this.peek().identifier) {
  13826. property.key = this.identifier();
  13827. property.computed = false;
  13828. if (this.peek(':')) {
  13829. this.consume(':');
  13830. property.value = this.expression();
  13831. } else {
  13832. property.value = property.key;
  13833. }
  13834. } else if (this.peek('[')) {
  13835. this.consume('[');
  13836. property.key = this.expression();
  13837. this.consume(']');
  13838. property.computed = true;
  13839. this.consume(':');
  13840. property.value = this.expression();
  13841. } else {
  13842. this.throwError('invalid key', this.peek());
  13843. }
  13844. properties.push(property);
  13845. } while (this.expect(','));
  13846. }
  13847. this.consume('}');
  13848. return {type: AST.ObjectExpression, properties: properties };
  13849. },
  13850. throwError: function(msg, token) {
  13851. throw $parseMinErr('syntax',
  13852. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13853. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13854. },
  13855. consume: function(e1) {
  13856. if (this.tokens.length === 0) {
  13857. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13858. }
  13859. var token = this.expect(e1);
  13860. if (!token) {
  13861. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13862. }
  13863. return token;
  13864. },
  13865. peekToken: function() {
  13866. if (this.tokens.length === 0) {
  13867. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13868. }
  13869. return this.tokens[0];
  13870. },
  13871. peek: function(e1, e2, e3, e4) {
  13872. return this.peekAhead(0, e1, e2, e3, e4);
  13873. },
  13874. peekAhead: function(i, e1, e2, e3, e4) {
  13875. if (this.tokens.length > i) {
  13876. var token = this.tokens[i];
  13877. var t = token.text;
  13878. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13879. (!e1 && !e2 && !e3 && !e4)) {
  13880. return token;
  13881. }
  13882. }
  13883. return false;
  13884. },
  13885. expect: function(e1, e2, e3, e4) {
  13886. var token = this.peek(e1, e2, e3, e4);
  13887. if (token) {
  13888. this.tokens.shift();
  13889. return token;
  13890. }
  13891. return false;
  13892. },
  13893. selfReferential: {
  13894. 'this': {type: AST.ThisExpression },
  13895. '$locals': {type: AST.LocalsExpression }
  13896. }
  13897. };
  13898. function ifDefined(v, d) {
  13899. return typeof v !== 'undefined' ? v : d;
  13900. }
  13901. function plusFn(l, r) {
  13902. if (typeof l === 'undefined') return r;
  13903. if (typeof r === 'undefined') return l;
  13904. return l + r;
  13905. }
  13906. function isStateless($filter, filterName) {
  13907. var fn = $filter(filterName);
  13908. return !fn.$stateful;
  13909. }
  13910. var PURITY_ABSOLUTE = 1;
  13911. var PURITY_RELATIVE = 2;
  13912. // Detect nodes which could depend on non-shallow state of objects
  13913. function isPure(node, parentIsPure) {
  13914. switch (node.type) {
  13915. // Computed members might invoke a stateful toString()
  13916. case AST.MemberExpression:
  13917. if (node.computed) {
  13918. return false;
  13919. }
  13920. break;
  13921. // Unary always convert to primative
  13922. case AST.UnaryExpression:
  13923. return PURITY_ABSOLUTE;
  13924. // The binary + operator can invoke a stateful toString().
  13925. case AST.BinaryExpression:
  13926. return node.operator !== '+' ? PURITY_ABSOLUTE : false;
  13927. // Functions / filters probably read state from within objects
  13928. case AST.CallExpression:
  13929. return false;
  13930. }
  13931. return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;
  13932. }
  13933. function findConstantAndWatchExpressions(ast, $filter, parentIsPure) {
  13934. var allConstants;
  13935. var argsToWatch;
  13936. var isStatelessFilter;
  13937. var astIsPure = ast.isPure = isPure(ast, parentIsPure);
  13938. switch (ast.type) {
  13939. case AST.Program:
  13940. allConstants = true;
  13941. forEach(ast.body, function(expr) {
  13942. findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);
  13943. allConstants = allConstants && expr.expression.constant;
  13944. });
  13945. ast.constant = allConstants;
  13946. break;
  13947. case AST.Literal:
  13948. ast.constant = true;
  13949. ast.toWatch = [];
  13950. break;
  13951. case AST.UnaryExpression:
  13952. findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);
  13953. ast.constant = ast.argument.constant;
  13954. ast.toWatch = ast.argument.toWatch;
  13955. break;
  13956. case AST.BinaryExpression:
  13957. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13958. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13959. ast.constant = ast.left.constant && ast.right.constant;
  13960. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13961. break;
  13962. case AST.LogicalExpression:
  13963. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13964. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13965. ast.constant = ast.left.constant && ast.right.constant;
  13966. ast.toWatch = ast.constant ? [] : [ast];
  13967. break;
  13968. case AST.ConditionalExpression:
  13969. findConstantAndWatchExpressions(ast.test, $filter, astIsPure);
  13970. findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);
  13971. findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);
  13972. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13973. ast.toWatch = ast.constant ? [] : [ast];
  13974. break;
  13975. case AST.Identifier:
  13976. ast.constant = false;
  13977. ast.toWatch = [ast];
  13978. break;
  13979. case AST.MemberExpression:
  13980. findConstantAndWatchExpressions(ast.object, $filter, astIsPure);
  13981. if (ast.computed) {
  13982. findConstantAndWatchExpressions(ast.property, $filter, astIsPure);
  13983. }
  13984. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13985. ast.toWatch = ast.constant ? [] : [ast];
  13986. break;
  13987. case AST.CallExpression:
  13988. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13989. allConstants = isStatelessFilter;
  13990. argsToWatch = [];
  13991. forEach(ast.arguments, function(expr) {
  13992. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  13993. allConstants = allConstants && expr.constant;
  13994. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13995. });
  13996. ast.constant = allConstants;
  13997. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13998. break;
  13999. case AST.AssignmentExpression:
  14000. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14001. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14002. ast.constant = ast.left.constant && ast.right.constant;
  14003. ast.toWatch = [ast];
  14004. break;
  14005. case AST.ArrayExpression:
  14006. allConstants = true;
  14007. argsToWatch = [];
  14008. forEach(ast.elements, function(expr) {
  14009. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14010. allConstants = allConstants && expr.constant;
  14011. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14012. });
  14013. ast.constant = allConstants;
  14014. ast.toWatch = argsToWatch;
  14015. break;
  14016. case AST.ObjectExpression:
  14017. allConstants = true;
  14018. argsToWatch = [];
  14019. forEach(ast.properties, function(property) {
  14020. findConstantAndWatchExpressions(property.value, $filter, astIsPure);
  14021. allConstants = allConstants && property.value.constant;
  14022. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  14023. if (property.computed) {
  14024. //`{[key]: value}` implicitly does `key.toString()` which may be non-pure
  14025. findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);
  14026. allConstants = allConstants && property.key.constant;
  14027. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  14028. }
  14029. });
  14030. ast.constant = allConstants;
  14031. ast.toWatch = argsToWatch;
  14032. break;
  14033. case AST.ThisExpression:
  14034. ast.constant = false;
  14035. ast.toWatch = [];
  14036. break;
  14037. case AST.LocalsExpression:
  14038. ast.constant = false;
  14039. ast.toWatch = [];
  14040. break;
  14041. }
  14042. }
  14043. function getInputs(body) {
  14044. if (body.length !== 1) return;
  14045. var lastExpression = body[0].expression;
  14046. var candidate = lastExpression.toWatch;
  14047. if (candidate.length !== 1) return candidate;
  14048. return candidate[0] !== lastExpression ? candidate : undefined;
  14049. }
  14050. function isAssignable(ast) {
  14051. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  14052. }
  14053. function assignableAST(ast) {
  14054. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  14055. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  14056. }
  14057. }
  14058. function isLiteral(ast) {
  14059. return ast.body.length === 0 ||
  14060. ast.body.length === 1 && (
  14061. ast.body[0].expression.type === AST.Literal ||
  14062. ast.body[0].expression.type === AST.ArrayExpression ||
  14063. ast.body[0].expression.type === AST.ObjectExpression);
  14064. }
  14065. function isConstant(ast) {
  14066. return ast.constant;
  14067. }
  14068. function ASTCompiler($filter) {
  14069. this.$filter = $filter;
  14070. }
  14071. ASTCompiler.prototype = {
  14072. compile: function(ast) {
  14073. var self = this;
  14074. this.state = {
  14075. nextId: 0,
  14076. filters: {},
  14077. fn: {vars: [], body: [], own: {}},
  14078. assign: {vars: [], body: [], own: {}},
  14079. inputs: []
  14080. };
  14081. findConstantAndWatchExpressions(ast, self.$filter);
  14082. var extra = '';
  14083. var assignable;
  14084. this.stage = 'assign';
  14085. if ((assignable = assignableAST(ast))) {
  14086. this.state.computing = 'assign';
  14087. var result = this.nextId();
  14088. this.recurse(assignable, result);
  14089. this.return_(result);
  14090. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  14091. }
  14092. var toWatch = getInputs(ast.body);
  14093. self.stage = 'inputs';
  14094. forEach(toWatch, function(watch, key) {
  14095. var fnKey = 'fn' + key;
  14096. self.state[fnKey] = {vars: [], body: [], own: {}};
  14097. self.state.computing = fnKey;
  14098. var intoId = self.nextId();
  14099. self.recurse(watch, intoId);
  14100. self.return_(intoId);
  14101. self.state.inputs.push({name: fnKey, isPure: watch.isPure});
  14102. watch.watchId = key;
  14103. });
  14104. this.state.computing = 'fn';
  14105. this.stage = 'main';
  14106. this.recurse(ast);
  14107. var fnString =
  14108. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  14109. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  14110. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  14111. this.filterPrefix() +
  14112. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  14113. extra +
  14114. this.watchFns() +
  14115. 'return fn;';
  14116. // eslint-disable-next-line no-new-func
  14117. var fn = (new Function('$filter',
  14118. 'getStringValue',
  14119. 'ifDefined',
  14120. 'plus',
  14121. fnString))(
  14122. this.$filter,
  14123. getStringValue,
  14124. ifDefined,
  14125. plusFn);
  14126. this.state = this.stage = undefined;
  14127. return fn;
  14128. },
  14129. USE: 'use',
  14130. STRICT: 'strict',
  14131. watchFns: function() {
  14132. var result = [];
  14133. var inputs = this.state.inputs;
  14134. var self = this;
  14135. forEach(inputs, function(input) {
  14136. result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));
  14137. if (input.isPure) {
  14138. result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');
  14139. }
  14140. });
  14141. if (inputs.length) {
  14142. result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');
  14143. }
  14144. return result.join('');
  14145. },
  14146. generateFunction: function(name, params) {
  14147. return 'function(' + params + '){' +
  14148. this.varsPrefix(name) +
  14149. this.body(name) +
  14150. '};';
  14151. },
  14152. filterPrefix: function() {
  14153. var parts = [];
  14154. var self = this;
  14155. forEach(this.state.filters, function(id, filter) {
  14156. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  14157. });
  14158. if (parts.length) return 'var ' + parts.join(',') + ';';
  14159. return '';
  14160. },
  14161. varsPrefix: function(section) {
  14162. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  14163. },
  14164. body: function(section) {
  14165. return this.state[section].body.join('');
  14166. },
  14167. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14168. var left, right, self = this, args, expression, computed;
  14169. recursionFn = recursionFn || noop;
  14170. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  14171. intoId = intoId || this.nextId();
  14172. this.if_('i',
  14173. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  14174. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  14175. );
  14176. return;
  14177. }
  14178. switch (ast.type) {
  14179. case AST.Program:
  14180. forEach(ast.body, function(expression, pos) {
  14181. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  14182. if (pos !== ast.body.length - 1) {
  14183. self.current().body.push(right, ';');
  14184. } else {
  14185. self.return_(right);
  14186. }
  14187. });
  14188. break;
  14189. case AST.Literal:
  14190. expression = this.escape(ast.value);
  14191. this.assign(intoId, expression);
  14192. recursionFn(intoId || expression);
  14193. break;
  14194. case AST.UnaryExpression:
  14195. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  14196. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  14197. this.assign(intoId, expression);
  14198. recursionFn(expression);
  14199. break;
  14200. case AST.BinaryExpression:
  14201. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  14202. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  14203. if (ast.operator === '+') {
  14204. expression = this.plus(left, right);
  14205. } else if (ast.operator === '-') {
  14206. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  14207. } else {
  14208. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  14209. }
  14210. this.assign(intoId, expression);
  14211. recursionFn(expression);
  14212. break;
  14213. case AST.LogicalExpression:
  14214. intoId = intoId || this.nextId();
  14215. self.recurse(ast.left, intoId);
  14216. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  14217. recursionFn(intoId);
  14218. break;
  14219. case AST.ConditionalExpression:
  14220. intoId = intoId || this.nextId();
  14221. self.recurse(ast.test, intoId);
  14222. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  14223. recursionFn(intoId);
  14224. break;
  14225. case AST.Identifier:
  14226. intoId = intoId || this.nextId();
  14227. if (nameId) {
  14228. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  14229. nameId.computed = false;
  14230. nameId.name = ast.name;
  14231. }
  14232. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  14233. function() {
  14234. self.if_(self.stage === 'inputs' || 's', function() {
  14235. if (create && create !== 1) {
  14236. self.if_(
  14237. self.isNull(self.nonComputedMember('s', ast.name)),
  14238. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  14239. }
  14240. self.assign(intoId, self.nonComputedMember('s', ast.name));
  14241. });
  14242. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  14243. );
  14244. recursionFn(intoId);
  14245. break;
  14246. case AST.MemberExpression:
  14247. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  14248. intoId = intoId || this.nextId();
  14249. self.recurse(ast.object, left, undefined, function() {
  14250. self.if_(self.notNull(left), function() {
  14251. if (ast.computed) {
  14252. right = self.nextId();
  14253. self.recurse(ast.property, right);
  14254. self.getStringValue(right);
  14255. if (create && create !== 1) {
  14256. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  14257. }
  14258. expression = self.computedMember(left, right);
  14259. self.assign(intoId, expression);
  14260. if (nameId) {
  14261. nameId.computed = true;
  14262. nameId.name = right;
  14263. }
  14264. } else {
  14265. if (create && create !== 1) {
  14266. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  14267. }
  14268. expression = self.nonComputedMember(left, ast.property.name);
  14269. self.assign(intoId, expression);
  14270. if (nameId) {
  14271. nameId.computed = false;
  14272. nameId.name = ast.property.name;
  14273. }
  14274. }
  14275. }, function() {
  14276. self.assign(intoId, 'undefined');
  14277. });
  14278. recursionFn(intoId);
  14279. }, !!create);
  14280. break;
  14281. case AST.CallExpression:
  14282. intoId = intoId || this.nextId();
  14283. if (ast.filter) {
  14284. right = self.filter(ast.callee.name);
  14285. args = [];
  14286. forEach(ast.arguments, function(expr) {
  14287. var argument = self.nextId();
  14288. self.recurse(expr, argument);
  14289. args.push(argument);
  14290. });
  14291. expression = right + '(' + args.join(',') + ')';
  14292. self.assign(intoId, expression);
  14293. recursionFn(intoId);
  14294. } else {
  14295. right = self.nextId();
  14296. left = {};
  14297. args = [];
  14298. self.recurse(ast.callee, right, left, function() {
  14299. self.if_(self.notNull(right), function() {
  14300. forEach(ast.arguments, function(expr) {
  14301. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14302. args.push(argument);
  14303. });
  14304. });
  14305. if (left.name) {
  14306. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14307. } else {
  14308. expression = right + '(' + args.join(',') + ')';
  14309. }
  14310. self.assign(intoId, expression);
  14311. }, function() {
  14312. self.assign(intoId, 'undefined');
  14313. });
  14314. recursionFn(intoId);
  14315. });
  14316. }
  14317. break;
  14318. case AST.AssignmentExpression:
  14319. right = this.nextId();
  14320. left = {};
  14321. this.recurse(ast.left, undefined, left, function() {
  14322. self.if_(self.notNull(left.context), function() {
  14323. self.recurse(ast.right, right);
  14324. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  14325. self.assign(intoId, expression);
  14326. recursionFn(intoId || expression);
  14327. });
  14328. }, 1);
  14329. break;
  14330. case AST.ArrayExpression:
  14331. args = [];
  14332. forEach(ast.elements, function(expr) {
  14333. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14334. args.push(argument);
  14335. });
  14336. });
  14337. expression = '[' + args.join(',') + ']';
  14338. this.assign(intoId, expression);
  14339. recursionFn(intoId || expression);
  14340. break;
  14341. case AST.ObjectExpression:
  14342. args = [];
  14343. computed = false;
  14344. forEach(ast.properties, function(property) {
  14345. if (property.computed) {
  14346. computed = true;
  14347. }
  14348. });
  14349. if (computed) {
  14350. intoId = intoId || this.nextId();
  14351. this.assign(intoId, '{}');
  14352. forEach(ast.properties, function(property) {
  14353. if (property.computed) {
  14354. left = self.nextId();
  14355. self.recurse(property.key, left);
  14356. } else {
  14357. left = property.key.type === AST.Identifier ?
  14358. property.key.name :
  14359. ('' + property.key.value);
  14360. }
  14361. right = self.nextId();
  14362. self.recurse(property.value, right);
  14363. self.assign(self.member(intoId, left, property.computed), right);
  14364. });
  14365. } else {
  14366. forEach(ast.properties, function(property) {
  14367. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  14368. args.push(self.escape(
  14369. property.key.type === AST.Identifier ? property.key.name :
  14370. ('' + property.key.value)) +
  14371. ':' + expr);
  14372. });
  14373. });
  14374. expression = '{' + args.join(',') + '}';
  14375. this.assign(intoId, expression);
  14376. }
  14377. recursionFn(intoId || expression);
  14378. break;
  14379. case AST.ThisExpression:
  14380. this.assign(intoId, 's');
  14381. recursionFn(intoId || 's');
  14382. break;
  14383. case AST.LocalsExpression:
  14384. this.assign(intoId, 'l');
  14385. recursionFn(intoId || 'l');
  14386. break;
  14387. case AST.NGValueParameter:
  14388. this.assign(intoId, 'v');
  14389. recursionFn(intoId || 'v');
  14390. break;
  14391. }
  14392. },
  14393. getHasOwnProperty: function(element, property) {
  14394. var key = element + '.' + property;
  14395. var own = this.current().own;
  14396. if (!own.hasOwnProperty(key)) {
  14397. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  14398. }
  14399. return own[key];
  14400. },
  14401. assign: function(id, value) {
  14402. if (!id) return;
  14403. this.current().body.push(id, '=', value, ';');
  14404. return id;
  14405. },
  14406. filter: function(filterName) {
  14407. if (!this.state.filters.hasOwnProperty(filterName)) {
  14408. this.state.filters[filterName] = this.nextId(true);
  14409. }
  14410. return this.state.filters[filterName];
  14411. },
  14412. ifDefined: function(id, defaultValue) {
  14413. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  14414. },
  14415. plus: function(left, right) {
  14416. return 'plus(' + left + ',' + right + ')';
  14417. },
  14418. return_: function(id) {
  14419. this.current().body.push('return ', id, ';');
  14420. },
  14421. if_: function(test, alternate, consequent) {
  14422. if (test === true) {
  14423. alternate();
  14424. } else {
  14425. var body = this.current().body;
  14426. body.push('if(', test, '){');
  14427. alternate();
  14428. body.push('}');
  14429. if (consequent) {
  14430. body.push('else{');
  14431. consequent();
  14432. body.push('}');
  14433. }
  14434. }
  14435. },
  14436. not: function(expression) {
  14437. return '!(' + expression + ')';
  14438. },
  14439. isNull: function(expression) {
  14440. return expression + '==null';
  14441. },
  14442. notNull: function(expression) {
  14443. return expression + '!=null';
  14444. },
  14445. nonComputedMember: function(left, right) {
  14446. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14447. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14448. if (SAFE_IDENTIFIER.test(right)) {
  14449. return left + '.' + right;
  14450. } else {
  14451. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14452. }
  14453. },
  14454. computedMember: function(left, right) {
  14455. return left + '[' + right + ']';
  14456. },
  14457. member: function(left, right, computed) {
  14458. if (computed) return this.computedMember(left, right);
  14459. return this.nonComputedMember(left, right);
  14460. },
  14461. getStringValue: function(item) {
  14462. this.assign(item, 'getStringValue(' + item + ')');
  14463. },
  14464. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14465. var self = this;
  14466. return function() {
  14467. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14468. };
  14469. },
  14470. lazyAssign: function(id, value) {
  14471. var self = this;
  14472. return function() {
  14473. self.assign(id, value);
  14474. };
  14475. },
  14476. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14477. stringEscapeFn: function(c) {
  14478. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14479. },
  14480. escape: function(value) {
  14481. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14482. if (isNumber(value)) return value.toString();
  14483. if (value === true) return 'true';
  14484. if (value === false) return 'false';
  14485. if (value === null) return 'null';
  14486. if (typeof value === 'undefined') return 'undefined';
  14487. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14488. },
  14489. nextId: function(skip, init) {
  14490. var id = 'v' + (this.state.nextId++);
  14491. if (!skip) {
  14492. this.current().vars.push(id + (init ? '=' + init : ''));
  14493. }
  14494. return id;
  14495. },
  14496. current: function() {
  14497. return this.state[this.state.computing];
  14498. }
  14499. };
  14500. function ASTInterpreter($filter) {
  14501. this.$filter = $filter;
  14502. }
  14503. ASTInterpreter.prototype = {
  14504. compile: function(ast) {
  14505. var self = this;
  14506. findConstantAndWatchExpressions(ast, self.$filter);
  14507. var assignable;
  14508. var assign;
  14509. if ((assignable = assignableAST(ast))) {
  14510. assign = this.recurse(assignable);
  14511. }
  14512. var toWatch = getInputs(ast.body);
  14513. var inputs;
  14514. if (toWatch) {
  14515. inputs = [];
  14516. forEach(toWatch, function(watch, key) {
  14517. var input = self.recurse(watch);
  14518. input.isPure = watch.isPure;
  14519. watch.input = input;
  14520. inputs.push(input);
  14521. watch.watchId = key;
  14522. });
  14523. }
  14524. var expressions = [];
  14525. forEach(ast.body, function(expression) {
  14526. expressions.push(self.recurse(expression.expression));
  14527. });
  14528. var fn = ast.body.length === 0 ? noop :
  14529. ast.body.length === 1 ? expressions[0] :
  14530. function(scope, locals) {
  14531. var lastValue;
  14532. forEach(expressions, function(exp) {
  14533. lastValue = exp(scope, locals);
  14534. });
  14535. return lastValue;
  14536. };
  14537. if (assign) {
  14538. fn.assign = function(scope, value, locals) {
  14539. return assign(scope, locals, value);
  14540. };
  14541. }
  14542. if (inputs) {
  14543. fn.inputs = inputs;
  14544. }
  14545. return fn;
  14546. },
  14547. recurse: function(ast, context, create) {
  14548. var left, right, self = this, args;
  14549. if (ast.input) {
  14550. return this.inputs(ast.input, ast.watchId);
  14551. }
  14552. switch (ast.type) {
  14553. case AST.Literal:
  14554. return this.value(ast.value, context);
  14555. case AST.UnaryExpression:
  14556. right = this.recurse(ast.argument);
  14557. return this['unary' + ast.operator](right, context);
  14558. case AST.BinaryExpression:
  14559. left = this.recurse(ast.left);
  14560. right = this.recurse(ast.right);
  14561. return this['binary' + ast.operator](left, right, context);
  14562. case AST.LogicalExpression:
  14563. left = this.recurse(ast.left);
  14564. right = this.recurse(ast.right);
  14565. return this['binary' + ast.operator](left, right, context);
  14566. case AST.ConditionalExpression:
  14567. return this['ternary?:'](
  14568. this.recurse(ast.test),
  14569. this.recurse(ast.alternate),
  14570. this.recurse(ast.consequent),
  14571. context
  14572. );
  14573. case AST.Identifier:
  14574. return self.identifier(ast.name, context, create);
  14575. case AST.MemberExpression:
  14576. left = this.recurse(ast.object, false, !!create);
  14577. if (!ast.computed) {
  14578. right = ast.property.name;
  14579. }
  14580. if (ast.computed) right = this.recurse(ast.property);
  14581. return ast.computed ?
  14582. this.computedMember(left, right, context, create) :
  14583. this.nonComputedMember(left, right, context, create);
  14584. case AST.CallExpression:
  14585. args = [];
  14586. forEach(ast.arguments, function(expr) {
  14587. args.push(self.recurse(expr));
  14588. });
  14589. if (ast.filter) right = this.$filter(ast.callee.name);
  14590. if (!ast.filter) right = this.recurse(ast.callee, true);
  14591. return ast.filter ?
  14592. function(scope, locals, assign, inputs) {
  14593. var values = [];
  14594. for (var i = 0; i < args.length; ++i) {
  14595. values.push(args[i](scope, locals, assign, inputs));
  14596. }
  14597. var value = right.apply(undefined, values, inputs);
  14598. return context ? {context: undefined, name: undefined, value: value} : value;
  14599. } :
  14600. function(scope, locals, assign, inputs) {
  14601. var rhs = right(scope, locals, assign, inputs);
  14602. var value;
  14603. if (rhs.value != null) {
  14604. var values = [];
  14605. for (var i = 0; i < args.length; ++i) {
  14606. values.push(args[i](scope, locals, assign, inputs));
  14607. }
  14608. value = rhs.value.apply(rhs.context, values);
  14609. }
  14610. return context ? {value: value} : value;
  14611. };
  14612. case AST.AssignmentExpression:
  14613. left = this.recurse(ast.left, true, 1);
  14614. right = this.recurse(ast.right);
  14615. return function(scope, locals, assign, inputs) {
  14616. var lhs = left(scope, locals, assign, inputs);
  14617. var rhs = right(scope, locals, assign, inputs);
  14618. lhs.context[lhs.name] = rhs;
  14619. return context ? {value: rhs} : rhs;
  14620. };
  14621. case AST.ArrayExpression:
  14622. args = [];
  14623. forEach(ast.elements, function(expr) {
  14624. args.push(self.recurse(expr));
  14625. });
  14626. return function(scope, locals, assign, inputs) {
  14627. var value = [];
  14628. for (var i = 0; i < args.length; ++i) {
  14629. value.push(args[i](scope, locals, assign, inputs));
  14630. }
  14631. return context ? {value: value} : value;
  14632. };
  14633. case AST.ObjectExpression:
  14634. args = [];
  14635. forEach(ast.properties, function(property) {
  14636. if (property.computed) {
  14637. args.push({key: self.recurse(property.key),
  14638. computed: true,
  14639. value: self.recurse(property.value)
  14640. });
  14641. } else {
  14642. args.push({key: property.key.type === AST.Identifier ?
  14643. property.key.name :
  14644. ('' + property.key.value),
  14645. computed: false,
  14646. value: self.recurse(property.value)
  14647. });
  14648. }
  14649. });
  14650. return function(scope, locals, assign, inputs) {
  14651. var value = {};
  14652. for (var i = 0; i < args.length; ++i) {
  14653. if (args[i].computed) {
  14654. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14655. } else {
  14656. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14657. }
  14658. }
  14659. return context ? {value: value} : value;
  14660. };
  14661. case AST.ThisExpression:
  14662. return function(scope) {
  14663. return context ? {value: scope} : scope;
  14664. };
  14665. case AST.LocalsExpression:
  14666. return function(scope, locals) {
  14667. return context ? {value: locals} : locals;
  14668. };
  14669. case AST.NGValueParameter:
  14670. return function(scope, locals, assign) {
  14671. return context ? {value: assign} : assign;
  14672. };
  14673. }
  14674. },
  14675. 'unary+': function(argument, context) {
  14676. return function(scope, locals, assign, inputs) {
  14677. var arg = argument(scope, locals, assign, inputs);
  14678. if (isDefined(arg)) {
  14679. arg = +arg;
  14680. } else {
  14681. arg = 0;
  14682. }
  14683. return context ? {value: arg} : arg;
  14684. };
  14685. },
  14686. 'unary-': function(argument, context) {
  14687. return function(scope, locals, assign, inputs) {
  14688. var arg = argument(scope, locals, assign, inputs);
  14689. if (isDefined(arg)) {
  14690. arg = -arg;
  14691. } else {
  14692. arg = -0;
  14693. }
  14694. return context ? {value: arg} : arg;
  14695. };
  14696. },
  14697. 'unary!': function(argument, context) {
  14698. return function(scope, locals, assign, inputs) {
  14699. var arg = !argument(scope, locals, assign, inputs);
  14700. return context ? {value: arg} : arg;
  14701. };
  14702. },
  14703. 'binary+': function(left, right, context) {
  14704. return function(scope, locals, assign, inputs) {
  14705. var lhs = left(scope, locals, assign, inputs);
  14706. var rhs = right(scope, locals, assign, inputs);
  14707. var arg = plusFn(lhs, rhs);
  14708. return context ? {value: arg} : arg;
  14709. };
  14710. },
  14711. 'binary-': function(left, right, context) {
  14712. return function(scope, locals, assign, inputs) {
  14713. var lhs = left(scope, locals, assign, inputs);
  14714. var rhs = right(scope, locals, assign, inputs);
  14715. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14716. return context ? {value: arg} : arg;
  14717. };
  14718. },
  14719. 'binary*': function(left, right, context) {
  14720. return function(scope, locals, assign, inputs) {
  14721. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14722. return context ? {value: arg} : arg;
  14723. };
  14724. },
  14725. 'binary/': function(left, right, context) {
  14726. return function(scope, locals, assign, inputs) {
  14727. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14728. return context ? {value: arg} : arg;
  14729. };
  14730. },
  14731. 'binary%': function(left, right, context) {
  14732. return function(scope, locals, assign, inputs) {
  14733. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14734. return context ? {value: arg} : arg;
  14735. };
  14736. },
  14737. 'binary===': function(left, right, context) {
  14738. return function(scope, locals, assign, inputs) {
  14739. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14740. return context ? {value: arg} : arg;
  14741. };
  14742. },
  14743. 'binary!==': function(left, right, context) {
  14744. return function(scope, locals, assign, inputs) {
  14745. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14746. return context ? {value: arg} : arg;
  14747. };
  14748. },
  14749. 'binary==': function(left, right, context) {
  14750. return function(scope, locals, assign, inputs) {
  14751. // eslint-disable-next-line eqeqeq
  14752. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14753. return context ? {value: arg} : arg;
  14754. };
  14755. },
  14756. 'binary!=': function(left, right, context) {
  14757. return function(scope, locals, assign, inputs) {
  14758. // eslint-disable-next-line eqeqeq
  14759. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14760. return context ? {value: arg} : arg;
  14761. };
  14762. },
  14763. 'binary<': function(left, right, context) {
  14764. return function(scope, locals, assign, inputs) {
  14765. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14766. return context ? {value: arg} : arg;
  14767. };
  14768. },
  14769. 'binary>': function(left, right, context) {
  14770. return function(scope, locals, assign, inputs) {
  14771. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14772. return context ? {value: arg} : arg;
  14773. };
  14774. },
  14775. 'binary<=': function(left, right, context) {
  14776. return function(scope, locals, assign, inputs) {
  14777. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14778. return context ? {value: arg} : arg;
  14779. };
  14780. },
  14781. 'binary>=': function(left, right, context) {
  14782. return function(scope, locals, assign, inputs) {
  14783. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14784. return context ? {value: arg} : arg;
  14785. };
  14786. },
  14787. 'binary&&': function(left, right, context) {
  14788. return function(scope, locals, assign, inputs) {
  14789. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14790. return context ? {value: arg} : arg;
  14791. };
  14792. },
  14793. 'binary||': function(left, right, context) {
  14794. return function(scope, locals, assign, inputs) {
  14795. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14796. return context ? {value: arg} : arg;
  14797. };
  14798. },
  14799. 'ternary?:': function(test, alternate, consequent, context) {
  14800. return function(scope, locals, assign, inputs) {
  14801. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14802. return context ? {value: arg} : arg;
  14803. };
  14804. },
  14805. value: function(value, context) {
  14806. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14807. },
  14808. identifier: function(name, context, create) {
  14809. return function(scope, locals, assign, inputs) {
  14810. var base = locals && (name in locals) ? locals : scope;
  14811. if (create && create !== 1 && base && base[name] == null) {
  14812. base[name] = {};
  14813. }
  14814. var value = base ? base[name] : undefined;
  14815. if (context) {
  14816. return {context: base, name: name, value: value};
  14817. } else {
  14818. return value;
  14819. }
  14820. };
  14821. },
  14822. computedMember: function(left, right, context, create) {
  14823. return function(scope, locals, assign, inputs) {
  14824. var lhs = left(scope, locals, assign, inputs);
  14825. var rhs;
  14826. var value;
  14827. if (lhs != null) {
  14828. rhs = right(scope, locals, assign, inputs);
  14829. rhs = getStringValue(rhs);
  14830. if (create && create !== 1) {
  14831. if (lhs && !(lhs[rhs])) {
  14832. lhs[rhs] = {};
  14833. }
  14834. }
  14835. value = lhs[rhs];
  14836. }
  14837. if (context) {
  14838. return {context: lhs, name: rhs, value: value};
  14839. } else {
  14840. return value;
  14841. }
  14842. };
  14843. },
  14844. nonComputedMember: function(left, right, context, create) {
  14845. return function(scope, locals, assign, inputs) {
  14846. var lhs = left(scope, locals, assign, inputs);
  14847. if (create && create !== 1) {
  14848. if (lhs && lhs[right] == null) {
  14849. lhs[right] = {};
  14850. }
  14851. }
  14852. var value = lhs != null ? lhs[right] : undefined;
  14853. if (context) {
  14854. return {context: lhs, name: right, value: value};
  14855. } else {
  14856. return value;
  14857. }
  14858. };
  14859. },
  14860. inputs: function(input, watchId) {
  14861. return function(scope, value, locals, inputs) {
  14862. if (inputs) return inputs[watchId];
  14863. return input(scope, value, locals);
  14864. };
  14865. }
  14866. };
  14867. /**
  14868. * @constructor
  14869. */
  14870. function Parser(lexer, $filter, options) {
  14871. this.ast = new AST(lexer, options);
  14872. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  14873. new ASTCompiler($filter);
  14874. }
  14875. Parser.prototype = {
  14876. constructor: Parser,
  14877. parse: function(text) {
  14878. var ast = this.getAst(text);
  14879. var fn = this.astCompiler.compile(ast.ast);
  14880. fn.literal = isLiteral(ast.ast);
  14881. fn.constant = isConstant(ast.ast);
  14882. fn.oneTime = ast.oneTime;
  14883. return fn;
  14884. },
  14885. getAst: function(exp) {
  14886. var oneTime = false;
  14887. exp = exp.trim();
  14888. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14889. oneTime = true;
  14890. exp = exp.substring(2);
  14891. }
  14892. return {
  14893. ast: this.ast.ast(exp),
  14894. oneTime: oneTime
  14895. };
  14896. }
  14897. };
  14898. function getValueOf(value) {
  14899. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14900. }
  14901. ///////////////////////////////////
  14902. /**
  14903. * @ngdoc service
  14904. * @name $parse
  14905. * @kind function
  14906. *
  14907. * @description
  14908. *
  14909. * Converts AngularJS {@link guide/expression expression} into a function.
  14910. *
  14911. * ```js
  14912. * var getter = $parse('user.name');
  14913. * var setter = getter.assign;
  14914. * var context = {user:{name:'AngularJS'}};
  14915. * var locals = {user:{name:'local'}};
  14916. *
  14917. * expect(getter(context)).toEqual('AngularJS');
  14918. * setter(context, 'newValue');
  14919. * expect(context.user.name).toEqual('newValue');
  14920. * expect(getter(context, locals)).toEqual('local');
  14921. * ```
  14922. *
  14923. *
  14924. * @param {string} expression String expression to compile.
  14925. * @returns {function(context, locals)} a function which represents the compiled expression:
  14926. *
  14927. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14928. * are evaluated against (typically a scope object).
  14929. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14930. * `context`.
  14931. *
  14932. * The returned function also has the following properties:
  14933. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14934. * literal.
  14935. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14936. * constant literals.
  14937. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14938. * set to a function to change its value on the given context.
  14939. *
  14940. */
  14941. /**
  14942. * @ngdoc provider
  14943. * @name $parseProvider
  14944. * @this
  14945. *
  14946. * @description
  14947. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14948. * service.
  14949. */
  14950. function $ParseProvider() {
  14951. var cache = createMap();
  14952. var literals = {
  14953. 'true': true,
  14954. 'false': false,
  14955. 'null': null,
  14956. 'undefined': undefined
  14957. };
  14958. var identStart, identContinue;
  14959. /**
  14960. * @ngdoc method
  14961. * @name $parseProvider#addLiteral
  14962. * @description
  14963. *
  14964. * Configure $parse service to add literal values that will be present as literal at expressions.
  14965. *
  14966. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14967. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14968. *
  14969. **/
  14970. this.addLiteral = function(literalName, literalValue) {
  14971. literals[literalName] = literalValue;
  14972. };
  14973. /**
  14974. * @ngdoc method
  14975. * @name $parseProvider#setIdentifierFns
  14976. *
  14977. * @description
  14978. *
  14979. * Allows defining the set of characters that are allowed in AngularJS expressions. The function
  14980. * `identifierStart` will get called to know if a given character is a valid character to be the
  14981. * first character for an identifier. The function `identifierContinue` will get called to know if
  14982. * a given character is a valid character to be a follow-up identifier character. The functions
  14983. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14984. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14985. * mind that the `string` parameter can be two characters long depending on the character
  14986. * representation. It is expected for the function to return `true` or `false`, whether that
  14987. * character is allowed or not.
  14988. *
  14989. * Since this function will be called extensively, keep the implementation of these functions fast,
  14990. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14991. *
  14992. * @param {function=} identifierStart The function that will decide whether the given character is
  14993. * a valid identifier start character.
  14994. * @param {function=} identifierContinue The function that will decide whether the given character is
  14995. * a valid identifier continue character.
  14996. */
  14997. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14998. identStart = identifierStart;
  14999. identContinue = identifierContinue;
  15000. return this;
  15001. };
  15002. this.$get = ['$filter', function($filter) {
  15003. var noUnsafeEval = csp().noUnsafeEval;
  15004. var $parseOptions = {
  15005. csp: noUnsafeEval,
  15006. literals: copy(literals),
  15007. isIdentifierStart: isFunction(identStart) && identStart,
  15008. isIdentifierContinue: isFunction(identContinue) && identContinue
  15009. };
  15010. $parse.$$getAst = $$getAst;
  15011. return $parse;
  15012. function $parse(exp, interceptorFn) {
  15013. var parsedExpression, cacheKey;
  15014. switch (typeof exp) {
  15015. case 'string':
  15016. exp = exp.trim();
  15017. cacheKey = exp;
  15018. parsedExpression = cache[cacheKey];
  15019. if (!parsedExpression) {
  15020. var lexer = new Lexer($parseOptions);
  15021. var parser = new Parser(lexer, $filter, $parseOptions);
  15022. parsedExpression = parser.parse(exp);
  15023. if (parsedExpression.constant) {
  15024. parsedExpression.$$watchDelegate = constantWatchDelegate;
  15025. } else if (parsedExpression.oneTime) {
  15026. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  15027. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  15028. } else if (parsedExpression.inputs) {
  15029. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  15030. }
  15031. cache[cacheKey] = parsedExpression;
  15032. }
  15033. return addInterceptor(parsedExpression, interceptorFn);
  15034. case 'function':
  15035. return addInterceptor(exp, interceptorFn);
  15036. default:
  15037. return addInterceptor(noop, interceptorFn);
  15038. }
  15039. }
  15040. function $$getAst(exp) {
  15041. var lexer = new Lexer($parseOptions);
  15042. var parser = new Parser(lexer, $filter, $parseOptions);
  15043. return parser.getAst(exp).ast;
  15044. }
  15045. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  15046. if (newValue == null || oldValueOfValue == null) { // null/undefined
  15047. return newValue === oldValueOfValue;
  15048. }
  15049. if (typeof newValue === 'object') {
  15050. // attempt to convert the value to a primitive type
  15051. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  15052. // be cheaply dirty-checked
  15053. newValue = getValueOf(newValue);
  15054. if (typeof newValue === 'object' && !compareObjectIdentity) {
  15055. // objects/arrays are not supported - deep-watching them would be too expensive
  15056. return false;
  15057. }
  15058. // fall-through to the primitive equality check
  15059. }
  15060. //Primitive or NaN
  15061. // eslint-disable-next-line no-self-compare
  15062. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  15063. }
  15064. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15065. var inputExpressions = parsedExpression.inputs;
  15066. var lastResult;
  15067. if (inputExpressions.length === 1) {
  15068. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15069. inputExpressions = inputExpressions[0];
  15070. return scope.$watch(function expressionInputWatch(scope) {
  15071. var newInputValue = inputExpressions(scope);
  15072. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {
  15073. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  15074. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  15075. }
  15076. return lastResult;
  15077. }, listener, objectEquality, prettyPrintExpression);
  15078. }
  15079. var oldInputValueOfValues = [];
  15080. var oldInputValues = [];
  15081. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15082. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15083. oldInputValues[i] = null;
  15084. }
  15085. return scope.$watch(function expressionInputsWatch(scope) {
  15086. var changed = false;
  15087. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15088. var newInputValue = inputExpressions[i](scope);
  15089. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {
  15090. oldInputValues[i] = newInputValue;
  15091. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  15092. }
  15093. }
  15094. if (changed) {
  15095. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  15096. }
  15097. return lastResult;
  15098. }, listener, objectEquality, prettyPrintExpression);
  15099. }
  15100. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15101. var unwatch, lastValue;
  15102. if (parsedExpression.inputs) {
  15103. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  15104. } else {
  15105. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  15106. }
  15107. return unwatch;
  15108. function oneTimeWatch(scope) {
  15109. return parsedExpression(scope);
  15110. }
  15111. function oneTimeListener(value, old, scope) {
  15112. lastValue = value;
  15113. if (isFunction(listener)) {
  15114. listener(value, old, scope);
  15115. }
  15116. if (isDefined(value)) {
  15117. scope.$$postDigest(function() {
  15118. if (isDefined(lastValue)) {
  15119. unwatch();
  15120. }
  15121. });
  15122. }
  15123. }
  15124. }
  15125. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15126. var unwatch, lastValue;
  15127. unwatch = scope.$watch(function oneTimeWatch(scope) {
  15128. return parsedExpression(scope);
  15129. }, function oneTimeListener(value, old, scope) {
  15130. lastValue = value;
  15131. if (isFunction(listener)) {
  15132. listener(value, old, scope);
  15133. }
  15134. if (isAllDefined(value)) {
  15135. scope.$$postDigest(function() {
  15136. if (isAllDefined(lastValue)) unwatch();
  15137. });
  15138. }
  15139. }, objectEquality);
  15140. return unwatch;
  15141. function isAllDefined(value) {
  15142. var allDefined = true;
  15143. forEach(value, function(val) {
  15144. if (!isDefined(val)) allDefined = false;
  15145. });
  15146. return allDefined;
  15147. }
  15148. }
  15149. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15150. var unwatch = scope.$watch(function constantWatch(scope) {
  15151. unwatch();
  15152. return parsedExpression(scope);
  15153. }, listener, objectEquality);
  15154. return unwatch;
  15155. }
  15156. function addInterceptor(parsedExpression, interceptorFn) {
  15157. if (!interceptorFn) return parsedExpression;
  15158. var watchDelegate = parsedExpression.$$watchDelegate;
  15159. var useInputs = false;
  15160. var regularWatch =
  15161. watchDelegate !== oneTimeLiteralWatchDelegate &&
  15162. watchDelegate !== oneTimeWatchDelegate;
  15163. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  15164. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  15165. return interceptorFn(value, scope, locals);
  15166. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  15167. var value = parsedExpression(scope, locals, assign, inputs);
  15168. var result = interceptorFn(value, scope, locals);
  15169. // we only return the interceptor's result if the
  15170. // initial value is defined (for bind-once)
  15171. return isDefined(value) ? result : value;
  15172. };
  15173. // Propagate $$watchDelegates other then inputsWatchDelegate
  15174. useInputs = !parsedExpression.inputs;
  15175. if (watchDelegate && watchDelegate !== inputsWatchDelegate) {
  15176. fn.$$watchDelegate = watchDelegate;
  15177. fn.inputs = parsedExpression.inputs;
  15178. } else if (!interceptorFn.$stateful) {
  15179. // Treat interceptor like filters - assume non-stateful by default and use the inputsWatchDelegate
  15180. fn.$$watchDelegate = inputsWatchDelegate;
  15181. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  15182. }
  15183. if (fn.inputs) {
  15184. fn.inputs = fn.inputs.map(function(e) {
  15185. // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a
  15186. // potentially non-pure interceptor function.
  15187. if (e.isPure === PURITY_RELATIVE) {
  15188. return function depurifier(s) { return e(s); };
  15189. }
  15190. return e;
  15191. });
  15192. }
  15193. return fn;
  15194. }
  15195. }];
  15196. }
  15197. /**
  15198. * @ngdoc service
  15199. * @name $q
  15200. * @requires $rootScope
  15201. *
  15202. * @description
  15203. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  15204. * when they are done processing.
  15205. *
  15206. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  15207. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  15208. *
  15209. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  15210. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  15211. *
  15212. * ## $q constructor
  15213. *
  15214. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  15215. * function as the first argument. This is similar to the native Promise implementation from ES6,
  15216. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  15217. *
  15218. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  15219. * available yet.
  15220. *
  15221. * It can be used like so:
  15222. *
  15223. * ```js
  15224. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15225. * // are available in the current lexical scope (they could have been injected or passed in).
  15226. *
  15227. * function asyncGreet(name) {
  15228. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  15229. * return $q(function(resolve, reject) {
  15230. * setTimeout(function() {
  15231. * if (okToGreet(name)) {
  15232. * resolve('Hello, ' + name + '!');
  15233. * } else {
  15234. * reject('Greeting ' + name + ' is not allowed.');
  15235. * }
  15236. * }, 1000);
  15237. * });
  15238. * }
  15239. *
  15240. * var promise = asyncGreet('Robin Hood');
  15241. * promise.then(function(greeting) {
  15242. * alert('Success: ' + greeting);
  15243. * }, function(reason) {
  15244. * alert('Failed: ' + reason);
  15245. * });
  15246. * ```
  15247. *
  15248. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  15249. *
  15250. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  15251. *
  15252. * However, the more traditional CommonJS-style usage is still available, and documented below.
  15253. *
  15254. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  15255. * interface for interacting with an object that represents the result of an action that is
  15256. * performed asynchronously, and may or may not be finished at any given point in time.
  15257. *
  15258. * From the perspective of dealing with error handling, deferred and promise APIs are to
  15259. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  15260. *
  15261. * ```js
  15262. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15263. * // are available in the current lexical scope (they could have been injected or passed in).
  15264. *
  15265. * function asyncGreet(name) {
  15266. * var deferred = $q.defer();
  15267. *
  15268. * setTimeout(function() {
  15269. * deferred.notify('About to greet ' + name + '.');
  15270. *
  15271. * if (okToGreet(name)) {
  15272. * deferred.resolve('Hello, ' + name + '!');
  15273. * } else {
  15274. * deferred.reject('Greeting ' + name + ' is not allowed.');
  15275. * }
  15276. * }, 1000);
  15277. *
  15278. * return deferred.promise;
  15279. * }
  15280. *
  15281. * var promise = asyncGreet('Robin Hood');
  15282. * promise.then(function(greeting) {
  15283. * alert('Success: ' + greeting);
  15284. * }, function(reason) {
  15285. * alert('Failed: ' + reason);
  15286. * }, function(update) {
  15287. * alert('Got notification: ' + update);
  15288. * });
  15289. * ```
  15290. *
  15291. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  15292. * comes in the way of guarantees that promise and deferred APIs make, see
  15293. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  15294. *
  15295. * Additionally the promise api allows for composition that is very hard to do with the
  15296. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  15297. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  15298. * section on serial or parallel joining of promises.
  15299. *
  15300. * ## The Deferred API
  15301. *
  15302. * A new instance of deferred is constructed by calling `$q.defer()`.
  15303. *
  15304. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  15305. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  15306. * of the task.
  15307. *
  15308. * **Methods**
  15309. *
  15310. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  15311. * constructed via `$q.reject`, the promise will be rejected instead.
  15312. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  15313. * resolving it with a rejection constructed via `$q.reject`.
  15314. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15315. * multiple times before the promise is either resolved or rejected.
  15316. *
  15317. * **Properties**
  15318. *
  15319. * - promise – `{Promise}` – promise object associated with this deferred.
  15320. *
  15321. *
  15322. * ## The Promise API
  15323. *
  15324. * A new promise instance is created when a deferred instance is created and can be retrieved by
  15325. * calling `deferred.promise`.
  15326. *
  15327. * The purpose of the promise object is to allow for interested parties to get access to the result
  15328. * of the deferred task when it completes.
  15329. *
  15330. * **Methods**
  15331. *
  15332. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  15333. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  15334. * as soon as the result is available. The callbacks are called with a single argument: the result
  15335. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  15336. * provide a progress indication, before the promise is resolved or rejected.
  15337. *
  15338. * This method *returns a new promise* which is resolved or rejected via the return value of the
  15339. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  15340. * with the value which is resolved in that promise using
  15341. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  15342. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  15343. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  15344. * arguments are optional.
  15345. *
  15346. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  15347. *
  15348. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  15349. * but to do so without modifying the final value. This is useful to release resources or do some
  15350. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  15351. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  15352. * more information.
  15353. *
  15354. * ## Chaining promises
  15355. *
  15356. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  15357. * possible to create a chain of promises:
  15358. *
  15359. * ```js
  15360. * promiseB = promiseA.then(function(result) {
  15361. * return result + 1;
  15362. * });
  15363. *
  15364. * // promiseB will be resolved immediately after promiseA is resolved and its value
  15365. * // will be the result of promiseA incremented by 1
  15366. * ```
  15367. *
  15368. * It is possible to create chains of any length and since a promise can be resolved with another
  15369. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  15370. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  15371. * $http's response interceptors.
  15372. *
  15373. *
  15374. * ## Differences between Kris Kowal's Q and $q
  15375. *
  15376. * There are two main differences:
  15377. *
  15378. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  15379. * mechanism in AngularJS, which means faster propagation of resolution or rejection into your
  15380. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  15381. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  15382. * all the important functionality needed for common async tasks.
  15383. *
  15384. * ## Testing
  15385. *
  15386. * ```js
  15387. * it('should simulate promise', inject(function($q, $rootScope) {
  15388. * var deferred = $q.defer();
  15389. * var promise = deferred.promise;
  15390. * var resolvedValue;
  15391. *
  15392. * promise.then(function(value) { resolvedValue = value; });
  15393. * expect(resolvedValue).toBeUndefined();
  15394. *
  15395. * // Simulate resolving of promise
  15396. * deferred.resolve(123);
  15397. * // Note that the 'then' function does not get called synchronously.
  15398. * // This is because we want the promise API to always be async, whether or not
  15399. * // it got called synchronously or asynchronously.
  15400. * expect(resolvedValue).toBeUndefined();
  15401. *
  15402. * // Propagate promise resolution to 'then' functions using $apply().
  15403. * $rootScope.$apply();
  15404. * expect(resolvedValue).toEqual(123);
  15405. * }));
  15406. * ```
  15407. *
  15408. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15409. * rejecting the newly created promise. The first parameter is a function which resolves the
  15410. * promise, the second parameter is a function which rejects the promise.
  15411. *
  15412. * @returns {Promise} The newly created promise.
  15413. */
  15414. /**
  15415. * @ngdoc provider
  15416. * @name $qProvider
  15417. * @this
  15418. *
  15419. * @description
  15420. */
  15421. function $QProvider() {
  15422. var errorOnUnhandledRejections = true;
  15423. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15424. return qFactory(function(callback) {
  15425. $rootScope.$evalAsync(callback);
  15426. }, $exceptionHandler, errorOnUnhandledRejections);
  15427. }];
  15428. /**
  15429. * @ngdoc method
  15430. * @name $qProvider#errorOnUnhandledRejections
  15431. * @kind function
  15432. *
  15433. * @description
  15434. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15435. * This feature is enabled by default.
  15436. *
  15437. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15438. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15439. * chaining otherwise.
  15440. */
  15441. this.errorOnUnhandledRejections = function(value) {
  15442. if (isDefined(value)) {
  15443. errorOnUnhandledRejections = value;
  15444. return this;
  15445. } else {
  15446. return errorOnUnhandledRejections;
  15447. }
  15448. };
  15449. }
  15450. /** @this */
  15451. function $$QProvider() {
  15452. var errorOnUnhandledRejections = true;
  15453. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15454. return qFactory(function(callback) {
  15455. $browser.defer(callback);
  15456. }, $exceptionHandler, errorOnUnhandledRejections);
  15457. }];
  15458. this.errorOnUnhandledRejections = function(value) {
  15459. if (isDefined(value)) {
  15460. errorOnUnhandledRejections = value;
  15461. return this;
  15462. } else {
  15463. return errorOnUnhandledRejections;
  15464. }
  15465. };
  15466. }
  15467. /**
  15468. * Constructs a promise manager.
  15469. *
  15470. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15471. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15472. * debugging purposes.
  15473. * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15474. * promises rejections.
  15475. * @returns {object} Promise manager.
  15476. */
  15477. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15478. var $qMinErr = minErr('$q', TypeError);
  15479. var queueSize = 0;
  15480. var checkQueue = [];
  15481. /**
  15482. * @ngdoc method
  15483. * @name ng.$q#defer
  15484. * @kind function
  15485. *
  15486. * @description
  15487. * Creates a `Deferred` object which represents a task which will finish in the future.
  15488. *
  15489. * @returns {Deferred} Returns a new instance of deferred.
  15490. */
  15491. function defer() {
  15492. return new Deferred();
  15493. }
  15494. function Deferred() {
  15495. var promise = this.promise = new Promise();
  15496. //Non prototype methods necessary to support unbound execution :/
  15497. this.resolve = function(val) { resolvePromise(promise, val); };
  15498. this.reject = function(reason) { rejectPromise(promise, reason); };
  15499. this.notify = function(progress) { notifyPromise(promise, progress); };
  15500. }
  15501. function Promise() {
  15502. this.$$state = { status: 0 };
  15503. }
  15504. extend(Promise.prototype, {
  15505. then: function(onFulfilled, onRejected, progressBack) {
  15506. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15507. return this;
  15508. }
  15509. var result = new Promise();
  15510. this.$$state.pending = this.$$state.pending || [];
  15511. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15512. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15513. return result;
  15514. },
  15515. 'catch': function(callback) {
  15516. return this.then(null, callback);
  15517. },
  15518. 'finally': function(callback, progressBack) {
  15519. return this.then(function(value) {
  15520. return handleCallback(value, resolve, callback);
  15521. }, function(error) {
  15522. return handleCallback(error, reject, callback);
  15523. }, progressBack);
  15524. }
  15525. });
  15526. function processQueue(state) {
  15527. var fn, promise, pending;
  15528. pending = state.pending;
  15529. state.processScheduled = false;
  15530. state.pending = undefined;
  15531. try {
  15532. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15533. markQStateExceptionHandled(state);
  15534. promise = pending[i][0];
  15535. fn = pending[i][state.status];
  15536. try {
  15537. if (isFunction(fn)) {
  15538. resolvePromise(promise, fn(state.value));
  15539. } else if (state.status === 1) {
  15540. resolvePromise(promise, state.value);
  15541. } else {
  15542. rejectPromise(promise, state.value);
  15543. }
  15544. } catch (e) {
  15545. rejectPromise(promise, e);
  15546. // This error is explicitly marked for being passed to the $exceptionHandler
  15547. if (e && e.$$passToExceptionHandler === true) {
  15548. exceptionHandler(e);
  15549. }
  15550. }
  15551. }
  15552. } finally {
  15553. --queueSize;
  15554. if (errorOnUnhandledRejections && queueSize === 0) {
  15555. nextTick(processChecks);
  15556. }
  15557. }
  15558. }
  15559. function processChecks() {
  15560. // eslint-disable-next-line no-unmodified-loop-condition
  15561. while (!queueSize && checkQueue.length) {
  15562. var toCheck = checkQueue.shift();
  15563. if (!isStateExceptionHandled(toCheck)) {
  15564. markQStateExceptionHandled(toCheck);
  15565. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15566. if (isError(toCheck.value)) {
  15567. exceptionHandler(toCheck.value, errorMessage);
  15568. } else {
  15569. exceptionHandler(errorMessage);
  15570. }
  15571. }
  15572. }
  15573. }
  15574. function scheduleProcessQueue(state) {
  15575. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {
  15576. if (queueSize === 0 && checkQueue.length === 0) {
  15577. nextTick(processChecks);
  15578. }
  15579. checkQueue.push(state);
  15580. }
  15581. if (state.processScheduled || !state.pending) return;
  15582. state.processScheduled = true;
  15583. ++queueSize;
  15584. nextTick(function() { processQueue(state); });
  15585. }
  15586. function resolvePromise(promise, val) {
  15587. if (promise.$$state.status) return;
  15588. if (val === promise) {
  15589. $$reject(promise, $qMinErr(
  15590. 'qcycle',
  15591. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15592. val));
  15593. } else {
  15594. $$resolve(promise, val);
  15595. }
  15596. }
  15597. function $$resolve(promise, val) {
  15598. var then;
  15599. var done = false;
  15600. try {
  15601. if (isObject(val) || isFunction(val)) then = val.then;
  15602. if (isFunction(then)) {
  15603. promise.$$state.status = -1;
  15604. then.call(val, doResolve, doReject, doNotify);
  15605. } else {
  15606. promise.$$state.value = val;
  15607. promise.$$state.status = 1;
  15608. scheduleProcessQueue(promise.$$state);
  15609. }
  15610. } catch (e) {
  15611. doReject(e);
  15612. }
  15613. function doResolve(val) {
  15614. if (done) return;
  15615. done = true;
  15616. $$resolve(promise, val);
  15617. }
  15618. function doReject(val) {
  15619. if (done) return;
  15620. done = true;
  15621. $$reject(promise, val);
  15622. }
  15623. function doNotify(progress) {
  15624. notifyPromise(promise, progress);
  15625. }
  15626. }
  15627. function rejectPromise(promise, reason) {
  15628. if (promise.$$state.status) return;
  15629. $$reject(promise, reason);
  15630. }
  15631. function $$reject(promise, reason) {
  15632. promise.$$state.value = reason;
  15633. promise.$$state.status = 2;
  15634. scheduleProcessQueue(promise.$$state);
  15635. }
  15636. function notifyPromise(promise, progress) {
  15637. var callbacks = promise.$$state.pending;
  15638. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15639. nextTick(function() {
  15640. var callback, result;
  15641. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15642. result = callbacks[i][0];
  15643. callback = callbacks[i][3];
  15644. try {
  15645. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15646. } catch (e) {
  15647. exceptionHandler(e);
  15648. }
  15649. }
  15650. });
  15651. }
  15652. }
  15653. /**
  15654. * @ngdoc method
  15655. * @name $q#reject
  15656. * @kind function
  15657. *
  15658. * @description
  15659. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15660. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15661. * a promise chain, you don't need to worry about it.
  15662. *
  15663. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15664. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15665. * a promise error callback and you want to forward the error to the promise derived from the
  15666. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15667. * `reject`.
  15668. *
  15669. * ```js
  15670. * promiseB = promiseA.then(function(result) {
  15671. * // success: do something and resolve promiseB
  15672. * // with the old or a new result
  15673. * return result;
  15674. * }, function(reason) {
  15675. * // error: handle the error if possible and
  15676. * // resolve promiseB with newPromiseOrValue,
  15677. * // otherwise forward the rejection to promiseB
  15678. * if (canHandle(reason)) {
  15679. * // handle the error and recover
  15680. * return newPromiseOrValue;
  15681. * }
  15682. * return $q.reject(reason);
  15683. * });
  15684. * ```
  15685. *
  15686. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15687. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15688. */
  15689. function reject(reason) {
  15690. var result = new Promise();
  15691. rejectPromise(result, reason);
  15692. return result;
  15693. }
  15694. function handleCallback(value, resolver, callback) {
  15695. var callbackOutput = null;
  15696. try {
  15697. if (isFunction(callback)) callbackOutput = callback();
  15698. } catch (e) {
  15699. return reject(e);
  15700. }
  15701. if (isPromiseLike(callbackOutput)) {
  15702. return callbackOutput.then(function() {
  15703. return resolver(value);
  15704. }, reject);
  15705. } else {
  15706. return resolver(value);
  15707. }
  15708. }
  15709. /**
  15710. * @ngdoc method
  15711. * @name $q#when
  15712. * @kind function
  15713. *
  15714. * @description
  15715. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15716. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15717. * the promise comes from a source that can't be trusted.
  15718. *
  15719. * @param {*} value Value or a promise
  15720. * @param {Function=} successCallback
  15721. * @param {Function=} errorCallback
  15722. * @param {Function=} progressCallback
  15723. * @returns {Promise} Returns a promise of the passed value or promise
  15724. */
  15725. function when(value, callback, errback, progressBack) {
  15726. var result = new Promise();
  15727. resolvePromise(result, value);
  15728. return result.then(callback, errback, progressBack);
  15729. }
  15730. /**
  15731. * @ngdoc method
  15732. * @name $q#resolve
  15733. * @kind function
  15734. *
  15735. * @description
  15736. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15737. *
  15738. * @param {*} value Value or a promise
  15739. * @param {Function=} successCallback
  15740. * @param {Function=} errorCallback
  15741. * @param {Function=} progressCallback
  15742. * @returns {Promise} Returns a promise of the passed value or promise
  15743. */
  15744. var resolve = when;
  15745. /**
  15746. * @ngdoc method
  15747. * @name $q#all
  15748. * @kind function
  15749. *
  15750. * @description
  15751. * Combines multiple promises into a single promise that is resolved when all of the input
  15752. * promises are resolved.
  15753. *
  15754. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15755. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15756. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15757. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15758. * with the same rejection value.
  15759. */
  15760. function all(promises) {
  15761. var result = new Promise(),
  15762. counter = 0,
  15763. results = isArray(promises) ? [] : {};
  15764. forEach(promises, function(promise, key) {
  15765. counter++;
  15766. when(promise).then(function(value) {
  15767. results[key] = value;
  15768. if (!(--counter)) resolvePromise(result, results);
  15769. }, function(reason) {
  15770. rejectPromise(result, reason);
  15771. });
  15772. });
  15773. if (counter === 0) {
  15774. resolvePromise(result, results);
  15775. }
  15776. return result;
  15777. }
  15778. /**
  15779. * @ngdoc method
  15780. * @name $q#race
  15781. * @kind function
  15782. *
  15783. * @description
  15784. * Returns a promise that resolves or rejects as soon as one of those promises
  15785. * resolves or rejects, with the value or reason from that promise.
  15786. *
  15787. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15788. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15789. * resolves or rejects, with the value or reason from that promise.
  15790. */
  15791. function race(promises) {
  15792. var deferred = defer();
  15793. forEach(promises, function(promise) {
  15794. when(promise).then(deferred.resolve, deferred.reject);
  15795. });
  15796. return deferred.promise;
  15797. }
  15798. function $Q(resolver) {
  15799. if (!isFunction(resolver)) {
  15800. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15801. }
  15802. var promise = new Promise();
  15803. function resolveFn(value) {
  15804. resolvePromise(promise, value);
  15805. }
  15806. function rejectFn(reason) {
  15807. rejectPromise(promise, reason);
  15808. }
  15809. resolver(resolveFn, rejectFn);
  15810. return promise;
  15811. }
  15812. // Let's make the instanceof operator work for promises, so that
  15813. // `new $q(fn) instanceof $q` would evaluate to true.
  15814. $Q.prototype = Promise.prototype;
  15815. $Q.defer = defer;
  15816. $Q.reject = reject;
  15817. $Q.when = when;
  15818. $Q.resolve = resolve;
  15819. $Q.all = all;
  15820. $Q.race = race;
  15821. return $Q;
  15822. }
  15823. function isStateExceptionHandled(state) {
  15824. return !!state.pur;
  15825. }
  15826. function markQStateExceptionHandled(state) {
  15827. state.pur = true;
  15828. }
  15829. function markQExceptionHandled(q) {
  15830. markQStateExceptionHandled(q.$$state);
  15831. }
  15832. /** @this */
  15833. function $$RAFProvider() { //rAF
  15834. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15835. var requestAnimationFrame = $window.requestAnimationFrame ||
  15836. $window.webkitRequestAnimationFrame;
  15837. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15838. $window.webkitCancelAnimationFrame ||
  15839. $window.webkitCancelRequestAnimationFrame;
  15840. var rafSupported = !!requestAnimationFrame;
  15841. var raf = rafSupported
  15842. ? function(fn) {
  15843. var id = requestAnimationFrame(fn);
  15844. return function() {
  15845. cancelAnimationFrame(id);
  15846. };
  15847. }
  15848. : function(fn) {
  15849. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15850. return function() {
  15851. $timeout.cancel(timer);
  15852. };
  15853. };
  15854. raf.supported = rafSupported;
  15855. return raf;
  15856. }];
  15857. }
  15858. /**
  15859. * DESIGN NOTES
  15860. *
  15861. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15862. *
  15863. * The typical use of scope is to watch the expressions, which most of the time return the same
  15864. * value as last time so we optimize the operation.
  15865. *
  15866. * Closures construction is expensive in terms of speed as well as memory:
  15867. * - No closures, instead use prototypical inheritance for API
  15868. * - Internal state needs to be stored on scope directly, which means that private state is
  15869. * exposed as $$____ properties
  15870. *
  15871. * Loop operations are optimized by using while(count--) { ... }
  15872. * - This means that in order to keep the same order of execution as addition we have to add
  15873. * items to the array at the beginning (unshift) instead of at the end (push)
  15874. *
  15875. * Child scopes are created and removed often
  15876. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15877. *
  15878. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15879. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15880. * to construct.
  15881. */
  15882. /**
  15883. * @ngdoc provider
  15884. * @name $rootScopeProvider
  15885. * @description
  15886. *
  15887. * Provider for the $rootScope service.
  15888. */
  15889. /**
  15890. * @ngdoc method
  15891. * @name $rootScopeProvider#digestTtl
  15892. * @description
  15893. *
  15894. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15895. * assuming that the model is unstable.
  15896. *
  15897. * The current default is 10 iterations.
  15898. *
  15899. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15900. * several digest iterations. However if an application needs more than the default 10 digest
  15901. * iterations for its model to stabilize then you should investigate what is causing the model to
  15902. * continuously change during the digest.
  15903. *
  15904. * Increasing the TTL could have performance implications, so you should not change it without
  15905. * proper justification.
  15906. *
  15907. * @param {number} limit The number of digest iterations.
  15908. */
  15909. /**
  15910. * @ngdoc service
  15911. * @name $rootScope
  15912. * @this
  15913. *
  15914. * @description
  15915. *
  15916. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15917. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15918. * between the model and the view, via a mechanism for watching the model for changes.
  15919. * They also provide event emission/broadcast and subscription facility. See the
  15920. * {@link guide/scope developer guide on scopes}.
  15921. */
  15922. function $RootScopeProvider() {
  15923. var TTL = 10;
  15924. var $rootScopeMinErr = minErr('$rootScope');
  15925. var lastDirtyWatch = null;
  15926. var applyAsyncId = null;
  15927. this.digestTtl = function(value) {
  15928. if (arguments.length) {
  15929. TTL = value;
  15930. }
  15931. return TTL;
  15932. };
  15933. function createChildScopeClass(parent) {
  15934. function ChildScope() {
  15935. this.$$watchers = this.$$nextSibling =
  15936. this.$$childHead = this.$$childTail = null;
  15937. this.$$listeners = {};
  15938. this.$$listenerCount = {};
  15939. this.$$watchersCount = 0;
  15940. this.$id = nextUid();
  15941. this.$$ChildScope = null;
  15942. }
  15943. ChildScope.prototype = parent;
  15944. return ChildScope;
  15945. }
  15946. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15947. function($exceptionHandler, $parse, $browser) {
  15948. function destroyChildScope($event) {
  15949. $event.currentScope.$$destroyed = true;
  15950. }
  15951. function cleanUpScope($scope) {
  15952. // Support: IE 9 only
  15953. if (msie === 9) {
  15954. // There is a memory leak in IE9 if all child scopes are not disconnected
  15955. // completely when a scope is destroyed. So this code will recurse up through
  15956. // all this scopes children
  15957. //
  15958. // See issue https://github.com/angular/angular.js/issues/10706
  15959. if ($scope.$$childHead) {
  15960. cleanUpScope($scope.$$childHead);
  15961. }
  15962. if ($scope.$$nextSibling) {
  15963. cleanUpScope($scope.$$nextSibling);
  15964. }
  15965. }
  15966. // The code below works around IE9 and V8's memory leaks
  15967. //
  15968. // See:
  15969. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15970. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15971. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15972. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15973. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15974. }
  15975. /**
  15976. * @ngdoc type
  15977. * @name $rootScope.Scope
  15978. *
  15979. * @description
  15980. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15981. * {@link auto.$injector $injector}. Child scopes are created using the
  15982. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15983. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15984. * an in-depth introduction and usage examples.
  15985. *
  15986. *
  15987. * ## Inheritance
  15988. * A scope can inherit from a parent scope, as in this example:
  15989. * ```js
  15990. var parent = $rootScope;
  15991. var child = parent.$new();
  15992. parent.salutation = "Hello";
  15993. expect(child.salutation).toEqual('Hello');
  15994. child.salutation = "Welcome";
  15995. expect(child.salutation).toEqual('Welcome');
  15996. expect(parent.salutation).toEqual('Hello');
  15997. * ```
  15998. *
  15999. * When interacting with `Scope` in tests, additional helper methods are available on the
  16000. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  16001. * details.
  16002. *
  16003. *
  16004. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  16005. * provided for the current scope. Defaults to {@link ng}.
  16006. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  16007. * append/override services provided by `providers`. This is handy
  16008. * when unit-testing and having the need to override a default
  16009. * service.
  16010. * @returns {Object} Newly created scope.
  16011. *
  16012. */
  16013. function Scope() {
  16014. this.$id = nextUid();
  16015. this.$$phase = this.$parent = this.$$watchers =
  16016. this.$$nextSibling = this.$$prevSibling =
  16017. this.$$childHead = this.$$childTail = null;
  16018. this.$root = this;
  16019. this.$$destroyed = false;
  16020. this.$$listeners = {};
  16021. this.$$listenerCount = {};
  16022. this.$$watchersCount = 0;
  16023. this.$$isolateBindings = null;
  16024. }
  16025. /**
  16026. * @ngdoc property
  16027. * @name $rootScope.Scope#$id
  16028. *
  16029. * @description
  16030. * Unique scope ID (monotonically increasing) useful for debugging.
  16031. */
  16032. /**
  16033. * @ngdoc property
  16034. * @name $rootScope.Scope#$parent
  16035. *
  16036. * @description
  16037. * Reference to the parent scope.
  16038. */
  16039. /**
  16040. * @ngdoc property
  16041. * @name $rootScope.Scope#$root
  16042. *
  16043. * @description
  16044. * Reference to the root scope.
  16045. */
  16046. Scope.prototype = {
  16047. constructor: Scope,
  16048. /**
  16049. * @ngdoc method
  16050. * @name $rootScope.Scope#$new
  16051. * @kind function
  16052. *
  16053. * @description
  16054. * Creates a new child {@link ng.$rootScope.Scope scope}.
  16055. *
  16056. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  16057. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  16058. *
  16059. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  16060. * desired for the scope and its child scopes to be permanently detached from the parent and
  16061. * thus stop participating in model change detection and listener notification by invoking.
  16062. *
  16063. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  16064. * parent scope. The scope is isolated, as it can not see parent scope properties.
  16065. * When creating widgets, it is useful for the widget to not accidentally read parent
  16066. * state.
  16067. *
  16068. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  16069. * of the newly created scope. Defaults to `this` scope if not provided.
  16070. * This is used when creating a transclude scope to correctly place it
  16071. * in the scope hierarchy while maintaining the correct prototypical
  16072. * inheritance.
  16073. *
  16074. * @returns {Object} The newly created child scope.
  16075. *
  16076. */
  16077. $new: function(isolate, parent) {
  16078. var child;
  16079. parent = parent || this;
  16080. if (isolate) {
  16081. child = new Scope();
  16082. child.$root = this.$root;
  16083. } else {
  16084. // Only create a child scope class if somebody asks for one,
  16085. // but cache it to allow the VM to optimize lookups.
  16086. if (!this.$$ChildScope) {
  16087. this.$$ChildScope = createChildScopeClass(this);
  16088. }
  16089. child = new this.$$ChildScope();
  16090. }
  16091. child.$parent = parent;
  16092. child.$$prevSibling = parent.$$childTail;
  16093. if (parent.$$childHead) {
  16094. parent.$$childTail.$$nextSibling = child;
  16095. parent.$$childTail = child;
  16096. } else {
  16097. parent.$$childHead = parent.$$childTail = child;
  16098. }
  16099. // When the new scope is not isolated or we inherit from `this`, and
  16100. // the parent scope is destroyed, the property `$$destroyed` is inherited
  16101. // prototypically. In all other cases, this property needs to be set
  16102. // when the parent scope is destroyed.
  16103. // The listener needs to be added after the parent is set
  16104. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  16105. return child;
  16106. },
  16107. /**
  16108. * @ngdoc method
  16109. * @name $rootScope.Scope#$watch
  16110. * @kind function
  16111. *
  16112. * @description
  16113. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  16114. *
  16115. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  16116. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  16117. * its value when executed multiple times with the same input because it may be executed multiple
  16118. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  16119. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  16120. * - The `listener` is called only when the value from the current `watchExpression` and the
  16121. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  16122. * see below). Inequality is determined according to reference inequality,
  16123. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  16124. * via the `!==` Javascript operator, unless `objectEquality == true`
  16125. * (see next point)
  16126. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  16127. * according to the {@link angular.equals} function. To save the value of the object for
  16128. * later comparison, the {@link angular.copy} function is used. This therefore means that
  16129. * watching complex objects will have adverse memory and performance implications.
  16130. * - This should not be used to watch for changes in objects that are
  16131. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  16132. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  16133. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  16134. * iteration limit is 10 to prevent an infinite loop deadlock.
  16135. *
  16136. *
  16137. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  16138. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  16139. * multiple calls to your `watchExpression` because it will execute multiple times in a
  16140. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  16141. *
  16142. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  16143. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  16144. * watcher. In rare cases, this is undesirable because the listener is called when the result
  16145. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  16146. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  16147. * listener was called due to initialization.
  16148. *
  16149. *
  16150. *
  16151. * @example
  16152. * ```js
  16153. // let's assume that scope was dependency injected as the $rootScope
  16154. var scope = $rootScope;
  16155. scope.name = 'misko';
  16156. scope.counter = 0;
  16157. expect(scope.counter).toEqual(0);
  16158. scope.$watch('name', function(newValue, oldValue) {
  16159. scope.counter = scope.counter + 1;
  16160. });
  16161. expect(scope.counter).toEqual(0);
  16162. scope.$digest();
  16163. // the listener is always called during the first $digest loop after it was registered
  16164. expect(scope.counter).toEqual(1);
  16165. scope.$digest();
  16166. // but now it will not be called unless the value changes
  16167. expect(scope.counter).toEqual(1);
  16168. scope.name = 'adam';
  16169. scope.$digest();
  16170. expect(scope.counter).toEqual(2);
  16171. // Using a function as a watchExpression
  16172. var food;
  16173. scope.foodCounter = 0;
  16174. expect(scope.foodCounter).toEqual(0);
  16175. scope.$watch(
  16176. // This function returns the value being watched. It is called for each turn of the $digest loop
  16177. function() { return food; },
  16178. // This is the change listener, called when the value returned from the above function changes
  16179. function(newValue, oldValue) {
  16180. if ( newValue !== oldValue ) {
  16181. // Only increment the counter if the value changed
  16182. scope.foodCounter = scope.foodCounter + 1;
  16183. }
  16184. }
  16185. );
  16186. // No digest has been run so the counter will be zero
  16187. expect(scope.foodCounter).toEqual(0);
  16188. // Run the digest but since food has not changed count will still be zero
  16189. scope.$digest();
  16190. expect(scope.foodCounter).toEqual(0);
  16191. // Update food and run digest. Now the counter will increment
  16192. food = 'cheeseburger';
  16193. scope.$digest();
  16194. expect(scope.foodCounter).toEqual(1);
  16195. * ```
  16196. *
  16197. *
  16198. *
  16199. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  16200. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  16201. * a call to the `listener`.
  16202. *
  16203. * - `string`: Evaluated as {@link guide/expression expression}
  16204. * - `function(scope)`: called with current `scope` as a parameter.
  16205. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  16206. * of `watchExpression` changes.
  16207. *
  16208. * - `newVal` contains the current value of the `watchExpression`
  16209. * - `oldVal` contains the previous value of the `watchExpression`
  16210. * - `scope` refers to the current scope
  16211. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  16212. * comparing for reference equality.
  16213. * @returns {function()} Returns a deregistration function for this listener.
  16214. */
  16215. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  16216. var get = $parse(watchExp);
  16217. var fn = isFunction(listener) ? listener : noop;
  16218. if (get.$$watchDelegate) {
  16219. return get.$$watchDelegate(this, fn, objectEquality, get, watchExp);
  16220. }
  16221. var scope = this,
  16222. array = scope.$$watchers,
  16223. watcher = {
  16224. fn: fn,
  16225. last: initWatchVal,
  16226. get: get,
  16227. exp: prettyPrintExpression || watchExp,
  16228. eq: !!objectEquality
  16229. };
  16230. lastDirtyWatch = null;
  16231. if (!array) {
  16232. array = scope.$$watchers = [];
  16233. array.$$digestWatchIndex = -1;
  16234. }
  16235. // we use unshift since we use a while loop in $digest for speed.
  16236. // the while loop reads in reverse order.
  16237. array.unshift(watcher);
  16238. array.$$digestWatchIndex++;
  16239. incrementWatchersCount(this, 1);
  16240. return function deregisterWatch() {
  16241. var index = arrayRemove(array, watcher);
  16242. if (index >= 0) {
  16243. incrementWatchersCount(scope, -1);
  16244. if (index < array.$$digestWatchIndex) {
  16245. array.$$digestWatchIndex--;
  16246. }
  16247. }
  16248. lastDirtyWatch = null;
  16249. };
  16250. },
  16251. /**
  16252. * @ngdoc method
  16253. * @name $rootScope.Scope#$watchGroup
  16254. * @kind function
  16255. *
  16256. * @description
  16257. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  16258. * If any one expression in the collection changes the `listener` is executed.
  16259. *
  16260. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  16261. * values are examined for changes on every call to `$digest`.
  16262. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  16263. *
  16264. * `$watchGroup` is more performant than watching each expression individually, and should be
  16265. * used when the listener does not need to know which expression has changed.
  16266. * If the listener needs to know which expression has changed,
  16267. * {@link ng.$rootScope.Scope#$watch $watch()} or
  16268. * {@link ng.$rootScope.Scope#$watchCollection $watchCollection()} should be used.
  16269. *
  16270. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  16271. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  16272. *
  16273. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  16274. * expression in `watchExpressions` changes
  16275. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  16276. * those of `watchExpression`
  16277. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  16278. * those of `watchExpression`.
  16279. *
  16280. * Note that `newValues` and `oldValues` reflect the differences in each **individual**
  16281. * expression, and not the difference of the values between each call of the listener.
  16282. * That means the difference between `newValues` and `oldValues` cannot be used to determine
  16283. * which expression has changed / remained stable:
  16284. *
  16285. * ```js
  16286. *
  16287. * $scope.$watchGroup(['v1', 'v2'], function(newValues, oldValues) {
  16288. * console.log(newValues, oldValues);
  16289. * });
  16290. *
  16291. * // newValues, oldValues initially
  16292. * // [undefined, undefined], [undefined, undefined]
  16293. *
  16294. * $scope.v1 = 'a';
  16295. * $scope.v2 = 'a';
  16296. *
  16297. * // ['a', 'a'], [undefined, undefined]
  16298. *
  16299. * $scope.v2 = 'b'
  16300. *
  16301. * // v1 hasn't changed since it became `'a'`, therefore its oldValue is still `undefined`
  16302. * // ['a', 'b'], [undefined, 'a']
  16303. *
  16304. * ```
  16305. *
  16306. * The `scope` refers to the current scope.
  16307. * @returns {function()} Returns a de-registration function for all listeners.
  16308. */
  16309. $watchGroup: function(watchExpressions, listener) {
  16310. var oldValues = new Array(watchExpressions.length);
  16311. var newValues = new Array(watchExpressions.length);
  16312. var deregisterFns = [];
  16313. var self = this;
  16314. var changeReactionScheduled = false;
  16315. var firstRun = true;
  16316. if (!watchExpressions.length) {
  16317. // No expressions means we call the listener ASAP
  16318. var shouldCall = true;
  16319. self.$evalAsync(function() {
  16320. if (shouldCall) listener(newValues, newValues, self);
  16321. });
  16322. return function deregisterWatchGroup() {
  16323. shouldCall = false;
  16324. };
  16325. }
  16326. if (watchExpressions.length === 1) {
  16327. // Special case size of one
  16328. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  16329. newValues[0] = value;
  16330. oldValues[0] = oldValue;
  16331. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  16332. });
  16333. }
  16334. forEach(watchExpressions, function(expr, i) {
  16335. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  16336. newValues[i] = value;
  16337. oldValues[i] = oldValue;
  16338. if (!changeReactionScheduled) {
  16339. changeReactionScheduled = true;
  16340. self.$evalAsync(watchGroupAction);
  16341. }
  16342. });
  16343. deregisterFns.push(unwatchFn);
  16344. });
  16345. function watchGroupAction() {
  16346. changeReactionScheduled = false;
  16347. if (firstRun) {
  16348. firstRun = false;
  16349. listener(newValues, newValues, self);
  16350. } else {
  16351. listener(newValues, oldValues, self);
  16352. }
  16353. }
  16354. return function deregisterWatchGroup() {
  16355. while (deregisterFns.length) {
  16356. deregisterFns.shift()();
  16357. }
  16358. };
  16359. },
  16360. /**
  16361. * @ngdoc method
  16362. * @name $rootScope.Scope#$watchCollection
  16363. * @kind function
  16364. *
  16365. * @description
  16366. * Shallow watches the properties of an object and fires whenever any of the properties change
  16367. * (for arrays, this implies watching the array items; for object maps, this implies watching
  16368. * the properties). If a change is detected, the `listener` callback is fired.
  16369. *
  16370. * - The `obj` collection is observed via standard $watch operation and is examined on every
  16371. * call to $digest() to see if any items have been added, removed, or moved.
  16372. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  16373. * adding, removing, and moving items belonging to an object or array.
  16374. *
  16375. *
  16376. * @example
  16377. * ```js
  16378. $scope.names = ['igor', 'matias', 'misko', 'james'];
  16379. $scope.dataCount = 4;
  16380. $scope.$watchCollection('names', function(newNames, oldNames) {
  16381. $scope.dataCount = newNames.length;
  16382. });
  16383. expect($scope.dataCount).toEqual(4);
  16384. $scope.$digest();
  16385. //still at 4 ... no changes
  16386. expect($scope.dataCount).toEqual(4);
  16387. $scope.names.pop();
  16388. $scope.$digest();
  16389. //now there's been a change
  16390. expect($scope.dataCount).toEqual(3);
  16391. * ```
  16392. *
  16393. *
  16394. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  16395. * expression value should evaluate to an object or an array which is observed on each
  16396. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  16397. * collection will trigger a call to the `listener`.
  16398. *
  16399. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  16400. * when a change is detected.
  16401. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  16402. * - The `oldCollection` object is a copy of the former collection data.
  16403. * Due to performance considerations, the`oldCollection` value is computed only if the
  16404. * `listener` function declares two or more arguments.
  16405. * - The `scope` argument refers to the current scope.
  16406. *
  16407. * @returns {function()} Returns a de-registration function for this listener. When the
  16408. * de-registration function is executed, the internal watch operation is terminated.
  16409. */
  16410. $watchCollection: function(obj, listener) {
  16411. $watchCollectionInterceptor.$stateful = true;
  16412. var self = this;
  16413. // the current value, updated on each dirty-check run
  16414. var newValue;
  16415. // a shallow copy of the newValue from the last dirty-check run,
  16416. // updated to match newValue during dirty-check run
  16417. var oldValue;
  16418. // a shallow copy of the newValue from when the last change happened
  16419. var veryOldValue;
  16420. // only track veryOldValue if the listener is asking for it
  16421. var trackVeryOldValue = (listener.length > 1);
  16422. var changeDetected = 0;
  16423. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  16424. var internalArray = [];
  16425. var internalObject = {};
  16426. var initRun = true;
  16427. var oldLength = 0;
  16428. function $watchCollectionInterceptor(_value) {
  16429. newValue = _value;
  16430. var newLength, key, bothNaN, newItem, oldItem;
  16431. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  16432. if (isUndefined(newValue)) return;
  16433. if (!isObject(newValue)) { // if primitive
  16434. if (oldValue !== newValue) {
  16435. oldValue = newValue;
  16436. changeDetected++;
  16437. }
  16438. } else if (isArrayLike(newValue)) {
  16439. if (oldValue !== internalArray) {
  16440. // we are transitioning from something which was not an array into array.
  16441. oldValue = internalArray;
  16442. oldLength = oldValue.length = 0;
  16443. changeDetected++;
  16444. }
  16445. newLength = newValue.length;
  16446. if (oldLength !== newLength) {
  16447. // if lengths do not match we need to trigger change notification
  16448. changeDetected++;
  16449. oldValue.length = oldLength = newLength;
  16450. }
  16451. // copy the items to oldValue and look for changes.
  16452. for (var i = 0; i < newLength; i++) {
  16453. oldItem = oldValue[i];
  16454. newItem = newValue[i];
  16455. // eslint-disable-next-line no-self-compare
  16456. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16457. if (!bothNaN && (oldItem !== newItem)) {
  16458. changeDetected++;
  16459. oldValue[i] = newItem;
  16460. }
  16461. }
  16462. } else {
  16463. if (oldValue !== internalObject) {
  16464. // we are transitioning from something which was not an object into object.
  16465. oldValue = internalObject = {};
  16466. oldLength = 0;
  16467. changeDetected++;
  16468. }
  16469. // copy the items to oldValue and look for changes.
  16470. newLength = 0;
  16471. for (key in newValue) {
  16472. if (hasOwnProperty.call(newValue, key)) {
  16473. newLength++;
  16474. newItem = newValue[key];
  16475. oldItem = oldValue[key];
  16476. if (key in oldValue) {
  16477. // eslint-disable-next-line no-self-compare
  16478. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16479. if (!bothNaN && (oldItem !== newItem)) {
  16480. changeDetected++;
  16481. oldValue[key] = newItem;
  16482. }
  16483. } else {
  16484. oldLength++;
  16485. oldValue[key] = newItem;
  16486. changeDetected++;
  16487. }
  16488. }
  16489. }
  16490. if (oldLength > newLength) {
  16491. // we used to have more keys, need to find them and destroy them.
  16492. changeDetected++;
  16493. for (key in oldValue) {
  16494. if (!hasOwnProperty.call(newValue, key)) {
  16495. oldLength--;
  16496. delete oldValue[key];
  16497. }
  16498. }
  16499. }
  16500. }
  16501. return changeDetected;
  16502. }
  16503. function $watchCollectionAction() {
  16504. if (initRun) {
  16505. initRun = false;
  16506. listener(newValue, newValue, self);
  16507. } else {
  16508. listener(newValue, veryOldValue, self);
  16509. }
  16510. // make a copy for the next time a collection is changed
  16511. if (trackVeryOldValue) {
  16512. if (!isObject(newValue)) {
  16513. //primitive
  16514. veryOldValue = newValue;
  16515. } else if (isArrayLike(newValue)) {
  16516. veryOldValue = new Array(newValue.length);
  16517. for (var i = 0; i < newValue.length; i++) {
  16518. veryOldValue[i] = newValue[i];
  16519. }
  16520. } else { // if object
  16521. veryOldValue = {};
  16522. for (var key in newValue) {
  16523. if (hasOwnProperty.call(newValue, key)) {
  16524. veryOldValue[key] = newValue[key];
  16525. }
  16526. }
  16527. }
  16528. }
  16529. }
  16530. return this.$watch(changeDetector, $watchCollectionAction);
  16531. },
  16532. /**
  16533. * @ngdoc method
  16534. * @name $rootScope.Scope#$digest
  16535. * @kind function
  16536. *
  16537. * @description
  16538. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16539. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16540. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16541. * until no more listeners are firing. This means that it is possible to get into an infinite
  16542. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16543. * iterations exceeds 10.
  16544. *
  16545. * Usually, you don't call `$digest()` directly in
  16546. * {@link ng.directive:ngController controllers} or in
  16547. * {@link ng.$compileProvider#directive directives}.
  16548. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16549. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16550. *
  16551. * If you want to be notified whenever `$digest()` is called,
  16552. * you can register a `watchExpression` function with
  16553. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16554. *
  16555. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16556. *
  16557. * @example
  16558. * ```js
  16559. var scope = ...;
  16560. scope.name = 'misko';
  16561. scope.counter = 0;
  16562. expect(scope.counter).toEqual(0);
  16563. scope.$watch('name', function(newValue, oldValue) {
  16564. scope.counter = scope.counter + 1;
  16565. });
  16566. expect(scope.counter).toEqual(0);
  16567. scope.$digest();
  16568. // the listener is always called during the first $digest loop after it was registered
  16569. expect(scope.counter).toEqual(1);
  16570. scope.$digest();
  16571. // but now it will not be called unless the value changes
  16572. expect(scope.counter).toEqual(1);
  16573. scope.name = 'adam';
  16574. scope.$digest();
  16575. expect(scope.counter).toEqual(2);
  16576. * ```
  16577. *
  16578. */
  16579. $digest: function() {
  16580. var watch, value, last, fn, get,
  16581. watchers,
  16582. dirty, ttl = TTL,
  16583. next, current, target = this,
  16584. watchLog = [],
  16585. logIdx, asyncTask;
  16586. beginPhase('$digest');
  16587. // Check for changes to browser url that happened in sync before the call to $digest
  16588. $browser.$$checkUrlChange();
  16589. if (this === $rootScope && applyAsyncId !== null) {
  16590. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16591. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16592. $browser.defer.cancel(applyAsyncId);
  16593. flushApplyAsync();
  16594. }
  16595. lastDirtyWatch = null;
  16596. do { // "while dirty" loop
  16597. dirty = false;
  16598. current = target;
  16599. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16600. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  16601. // lead to a '$digest already in progress' error.
  16602. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16603. try {
  16604. asyncTask = asyncQueue[asyncQueuePosition];
  16605. fn = asyncTask.fn;
  16606. fn(asyncTask.scope, asyncTask.locals);
  16607. } catch (e) {
  16608. $exceptionHandler(e);
  16609. }
  16610. lastDirtyWatch = null;
  16611. }
  16612. asyncQueue.length = 0;
  16613. traverseScopesLoop:
  16614. do { // "traverse the scopes" loop
  16615. if ((watchers = current.$$watchers)) {
  16616. // process our watches
  16617. watchers.$$digestWatchIndex = watchers.length;
  16618. while (watchers.$$digestWatchIndex--) {
  16619. try {
  16620. watch = watchers[watchers.$$digestWatchIndex];
  16621. // Most common watches are on primitives, in which case we can short
  16622. // circuit it with === operator, only when === fails do we use .equals
  16623. if (watch) {
  16624. get = watch.get;
  16625. if ((value = get(current)) !== (last = watch.last) &&
  16626. !(watch.eq
  16627. ? equals(value, last)
  16628. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16629. dirty = true;
  16630. lastDirtyWatch = watch;
  16631. watch.last = watch.eq ? copy(value, null) : value;
  16632. fn = watch.fn;
  16633. fn(value, ((last === initWatchVal) ? value : last), current);
  16634. if (ttl < 5) {
  16635. logIdx = 4 - ttl;
  16636. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16637. watchLog[logIdx].push({
  16638. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16639. newVal: value,
  16640. oldVal: last
  16641. });
  16642. }
  16643. } else if (watch === lastDirtyWatch) {
  16644. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16645. // have already been tested.
  16646. dirty = false;
  16647. break traverseScopesLoop;
  16648. }
  16649. }
  16650. } catch (e) {
  16651. $exceptionHandler(e);
  16652. }
  16653. }
  16654. }
  16655. // Insanity Warning: scope depth-first traversal
  16656. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16657. // this piece should be kept in sync with the traversal in $broadcast
  16658. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16659. (current !== target && current.$$nextSibling)))) {
  16660. while (current !== target && !(next = current.$$nextSibling)) {
  16661. current = current.$parent;
  16662. }
  16663. }
  16664. } while ((current = next));
  16665. // `break traverseScopesLoop;` takes us to here
  16666. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16667. clearPhase();
  16668. throw $rootScopeMinErr('infdig',
  16669. '{0} $digest() iterations reached. Aborting!\n' +
  16670. 'Watchers fired in the last 5 iterations: {1}',
  16671. TTL, watchLog);
  16672. }
  16673. } while (dirty || asyncQueue.length);
  16674. clearPhase();
  16675. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16676. while (postDigestQueuePosition < postDigestQueue.length) {
  16677. try {
  16678. postDigestQueue[postDigestQueuePosition++]();
  16679. } catch (e) {
  16680. $exceptionHandler(e);
  16681. }
  16682. }
  16683. postDigestQueue.length = postDigestQueuePosition = 0;
  16684. // Check for changes to browser url that happened during the $digest
  16685. // (for which no event is fired; e.g. via `history.pushState()`)
  16686. $browser.$$checkUrlChange();
  16687. },
  16688. /**
  16689. * @ngdoc event
  16690. * @name $rootScope.Scope#$destroy
  16691. * @eventType broadcast on scope being destroyed
  16692. *
  16693. * @description
  16694. * Broadcasted when a scope and its children are being destroyed.
  16695. *
  16696. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16697. * clean up DOM bindings before an element is removed from the DOM.
  16698. */
  16699. /**
  16700. * @ngdoc method
  16701. * @name $rootScope.Scope#$destroy
  16702. * @kind function
  16703. *
  16704. * @description
  16705. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16706. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16707. * propagate to the current scope and its children. Removal also implies that the current
  16708. * scope is eligible for garbage collection.
  16709. *
  16710. * The `$destroy()` is usually used by directives such as
  16711. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16712. * unrolling of the loop.
  16713. *
  16714. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16715. * Application code can register a `$destroy` event handler that will give it a chance to
  16716. * perform any necessary cleanup.
  16717. *
  16718. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16719. * clean up DOM bindings before an element is removed from the DOM.
  16720. */
  16721. $destroy: function() {
  16722. // We can't destroy a scope that has been already destroyed.
  16723. if (this.$$destroyed) return;
  16724. var parent = this.$parent;
  16725. this.$broadcast('$destroy');
  16726. this.$$destroyed = true;
  16727. if (this === $rootScope) {
  16728. //Remove handlers attached to window when $rootScope is removed
  16729. $browser.$$applicationDestroyed();
  16730. }
  16731. incrementWatchersCount(this, -this.$$watchersCount);
  16732. for (var eventName in this.$$listenerCount) {
  16733. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16734. }
  16735. // sever all the references to parent scopes (after this cleanup, the current scope should
  16736. // not be retained by any of our references and should be eligible for garbage collection)
  16737. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16738. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16739. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16740. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16741. // Disable listeners, watchers and apply/digest methods
  16742. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16743. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16744. this.$$listeners = {};
  16745. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16746. this.$$nextSibling = null;
  16747. cleanUpScope(this);
  16748. },
  16749. /**
  16750. * @ngdoc method
  16751. * @name $rootScope.Scope#$eval
  16752. * @kind function
  16753. *
  16754. * @description
  16755. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16756. * the expression are propagated (uncaught). This is useful when evaluating AngularJS
  16757. * expressions.
  16758. *
  16759. * @example
  16760. * ```js
  16761. var scope = ng.$rootScope.Scope();
  16762. scope.a = 1;
  16763. scope.b = 2;
  16764. expect(scope.$eval('a+b')).toEqual(3);
  16765. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16766. * ```
  16767. *
  16768. * @param {(string|function())=} expression An AngularJS expression to be executed.
  16769. *
  16770. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16771. * - `function(scope)`: execute the function with the current `scope` parameter.
  16772. *
  16773. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16774. * @returns {*} The result of evaluating the expression.
  16775. */
  16776. $eval: function(expr, locals) {
  16777. return $parse(expr)(this, locals);
  16778. },
  16779. /**
  16780. * @ngdoc method
  16781. * @name $rootScope.Scope#$evalAsync
  16782. * @kind function
  16783. *
  16784. * @description
  16785. * Executes the expression on the current scope at a later point in time.
  16786. *
  16787. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16788. * that:
  16789. *
  16790. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16791. * rendering).
  16792. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16793. * `expression` execution.
  16794. *
  16795. * Any exceptions from the execution of the expression are forwarded to the
  16796. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16797. *
  16798. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16799. * will be scheduled. However, it is encouraged to always call code that changes the model
  16800. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16801. *
  16802. * @param {(string|function())=} expression An AngularJS expression to be executed.
  16803. *
  16804. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16805. * - `function(scope)`: execute the function with the current `scope` parameter.
  16806. *
  16807. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16808. */
  16809. $evalAsync: function(expr, locals) {
  16810. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16811. // task also schedule async auto-flush
  16812. if (!$rootScope.$$phase && !asyncQueue.length) {
  16813. $browser.defer(function() {
  16814. if (asyncQueue.length) {
  16815. $rootScope.$digest();
  16816. }
  16817. });
  16818. }
  16819. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  16820. },
  16821. $$postDigest: function(fn) {
  16822. postDigestQueue.push(fn);
  16823. },
  16824. /**
  16825. * @ngdoc method
  16826. * @name $rootScope.Scope#$apply
  16827. * @kind function
  16828. *
  16829. * @description
  16830. * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS
  16831. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16832. * Because we are calling into the AngularJS framework we need to perform proper scope life
  16833. * cycle of {@link ng.$exceptionHandler exception handling},
  16834. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16835. *
  16836. * **Life cycle: Pseudo-Code of `$apply()`**
  16837. *
  16838. * ```js
  16839. function $apply(expr) {
  16840. try {
  16841. return $eval(expr);
  16842. } catch (e) {
  16843. $exceptionHandler(e);
  16844. } finally {
  16845. $root.$digest();
  16846. }
  16847. }
  16848. * ```
  16849. *
  16850. *
  16851. * Scope's `$apply()` method transitions through the following stages:
  16852. *
  16853. * 1. The {@link guide/expression expression} is executed using the
  16854. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16855. * 2. Any exceptions from the execution of the expression are forwarded to the
  16856. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16857. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16858. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16859. *
  16860. *
  16861. * @param {(string|function())=} exp An AngularJS expression to be executed.
  16862. *
  16863. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16864. * - `function(scope)`: execute the function with current `scope` parameter.
  16865. *
  16866. * @returns {*} The result of evaluating the expression.
  16867. */
  16868. $apply: function(expr) {
  16869. try {
  16870. beginPhase('$apply');
  16871. try {
  16872. return this.$eval(expr);
  16873. } finally {
  16874. clearPhase();
  16875. }
  16876. } catch (e) {
  16877. $exceptionHandler(e);
  16878. } finally {
  16879. try {
  16880. $rootScope.$digest();
  16881. } catch (e) {
  16882. $exceptionHandler(e);
  16883. // eslint-disable-next-line no-unsafe-finally
  16884. throw e;
  16885. }
  16886. }
  16887. },
  16888. /**
  16889. * @ngdoc method
  16890. * @name $rootScope.Scope#$applyAsync
  16891. * @kind function
  16892. *
  16893. * @description
  16894. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16895. * varies across browsers, but is typically around ~10 milliseconds.
  16896. *
  16897. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16898. * digest.
  16899. *
  16900. * @param {(string|function())=} exp An AngularJS expression to be executed.
  16901. *
  16902. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16903. * - `function(scope)`: execute the function with current `scope` parameter.
  16904. */
  16905. $applyAsync: function(expr) {
  16906. var scope = this;
  16907. if (expr) {
  16908. applyAsyncQueue.push($applyAsyncExpression);
  16909. }
  16910. expr = $parse(expr);
  16911. scheduleApplyAsync();
  16912. function $applyAsyncExpression() {
  16913. scope.$eval(expr);
  16914. }
  16915. },
  16916. /**
  16917. * @ngdoc method
  16918. * @name $rootScope.Scope#$on
  16919. * @kind function
  16920. *
  16921. * @description
  16922. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16923. * discussion of event life cycle.
  16924. *
  16925. * The event listener function format is: `function(event, args...)`. The `event` object
  16926. * passed into the listener has the following attributes:
  16927. *
  16928. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16929. * `$broadcast`-ed.
  16930. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16931. * event propagates through the scope hierarchy, this property is set to null.
  16932. * - `name` - `{string}`: name of the event.
  16933. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16934. * further event propagation (available only for events that were `$emit`-ed).
  16935. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16936. * to true.
  16937. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16938. *
  16939. * @param {string} name Event name to listen on.
  16940. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16941. * @returns {function()} Returns a deregistration function for this listener.
  16942. */
  16943. $on: function(name, listener) {
  16944. var namedListeners = this.$$listeners[name];
  16945. if (!namedListeners) {
  16946. this.$$listeners[name] = namedListeners = [];
  16947. }
  16948. namedListeners.push(listener);
  16949. var current = this;
  16950. do {
  16951. if (!current.$$listenerCount[name]) {
  16952. current.$$listenerCount[name] = 0;
  16953. }
  16954. current.$$listenerCount[name]++;
  16955. } while ((current = current.$parent));
  16956. var self = this;
  16957. return function() {
  16958. var indexOfListener = namedListeners.indexOf(listener);
  16959. if (indexOfListener !== -1) {
  16960. // Use delete in the hope of the browser deallocating the memory for the array entry,
  16961. // while not shifting the array indexes of other listeners.
  16962. // See issue https://github.com/angular/angular.js/issues/16135
  16963. delete namedListeners[indexOfListener];
  16964. decrementListenerCount(self, 1, name);
  16965. }
  16966. };
  16967. },
  16968. /**
  16969. * @ngdoc method
  16970. * @name $rootScope.Scope#$emit
  16971. * @kind function
  16972. *
  16973. * @description
  16974. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16975. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16976. *
  16977. * The event life cycle starts at the scope on which `$emit` was called. All
  16978. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16979. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16980. * registered listeners along the way. The event will stop propagating if one of the listeners
  16981. * cancels it.
  16982. *
  16983. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16984. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16985. *
  16986. * @param {string} name Event name to emit.
  16987. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16988. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16989. */
  16990. $emit: function(name, args) {
  16991. var empty = [],
  16992. namedListeners,
  16993. scope = this,
  16994. stopPropagation = false,
  16995. event = {
  16996. name: name,
  16997. targetScope: scope,
  16998. stopPropagation: function() {stopPropagation = true;},
  16999. preventDefault: function() {
  17000. event.defaultPrevented = true;
  17001. },
  17002. defaultPrevented: false
  17003. },
  17004. listenerArgs = concat([event], arguments, 1),
  17005. i, length;
  17006. do {
  17007. namedListeners = scope.$$listeners[name] || empty;
  17008. event.currentScope = scope;
  17009. for (i = 0, length = namedListeners.length; i < length; i++) {
  17010. // if listeners were deregistered, defragment the array
  17011. if (!namedListeners[i]) {
  17012. namedListeners.splice(i, 1);
  17013. i--;
  17014. length--;
  17015. continue;
  17016. }
  17017. try {
  17018. //allow all listeners attached to the current scope to run
  17019. namedListeners[i].apply(null, listenerArgs);
  17020. } catch (e) {
  17021. $exceptionHandler(e);
  17022. }
  17023. }
  17024. //if any listener on the current scope stops propagation, prevent bubbling
  17025. if (stopPropagation) {
  17026. break;
  17027. }
  17028. //traverse upwards
  17029. scope = scope.$parent;
  17030. } while (scope);
  17031. event.currentScope = null;
  17032. return event;
  17033. },
  17034. /**
  17035. * @ngdoc method
  17036. * @name $rootScope.Scope#$broadcast
  17037. * @kind function
  17038. *
  17039. * @description
  17040. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  17041. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17042. *
  17043. * The event life cycle starts at the scope on which `$broadcast` was called. All
  17044. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17045. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  17046. * scope and calls all registered listeners along the way. The event cannot be canceled.
  17047. *
  17048. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17049. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17050. *
  17051. * @param {string} name Event name to broadcast.
  17052. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17053. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  17054. */
  17055. $broadcast: function(name, args) {
  17056. var target = this,
  17057. current = target,
  17058. next = target,
  17059. event = {
  17060. name: name,
  17061. targetScope: target,
  17062. preventDefault: function() {
  17063. event.defaultPrevented = true;
  17064. },
  17065. defaultPrevented: false
  17066. };
  17067. if (!target.$$listenerCount[name]) return event;
  17068. var listenerArgs = concat([event], arguments, 1),
  17069. listeners, i, length;
  17070. //down while you can, then up and next sibling or up and next sibling until back at root
  17071. while ((current = next)) {
  17072. event.currentScope = current;
  17073. listeners = current.$$listeners[name] || [];
  17074. for (i = 0, length = listeners.length; i < length; i++) {
  17075. // if listeners were deregistered, defragment the array
  17076. if (!listeners[i]) {
  17077. listeners.splice(i, 1);
  17078. i--;
  17079. length--;
  17080. continue;
  17081. }
  17082. try {
  17083. listeners[i].apply(null, listenerArgs);
  17084. } catch (e) {
  17085. $exceptionHandler(e);
  17086. }
  17087. }
  17088. // Insanity Warning: scope depth-first traversal
  17089. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17090. // this piece should be kept in sync with the traversal in $digest
  17091. // (though it differs due to having the extra check for $$listenerCount)
  17092. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  17093. (current !== target && current.$$nextSibling)))) {
  17094. while (current !== target && !(next = current.$$nextSibling)) {
  17095. current = current.$parent;
  17096. }
  17097. }
  17098. }
  17099. event.currentScope = null;
  17100. return event;
  17101. }
  17102. };
  17103. var $rootScope = new Scope();
  17104. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  17105. var asyncQueue = $rootScope.$$asyncQueue = [];
  17106. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  17107. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  17108. var postDigestQueuePosition = 0;
  17109. return $rootScope;
  17110. function beginPhase(phase) {
  17111. if ($rootScope.$$phase) {
  17112. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  17113. }
  17114. $rootScope.$$phase = phase;
  17115. }
  17116. function clearPhase() {
  17117. $rootScope.$$phase = null;
  17118. }
  17119. function incrementWatchersCount(current, count) {
  17120. do {
  17121. current.$$watchersCount += count;
  17122. } while ((current = current.$parent));
  17123. }
  17124. function decrementListenerCount(current, count, name) {
  17125. do {
  17126. current.$$listenerCount[name] -= count;
  17127. if (current.$$listenerCount[name] === 0) {
  17128. delete current.$$listenerCount[name];
  17129. }
  17130. } while ((current = current.$parent));
  17131. }
  17132. /**
  17133. * function used as an initial value for watchers.
  17134. * because it's unique we can easily tell it apart from other values
  17135. */
  17136. function initWatchVal() {}
  17137. function flushApplyAsync() {
  17138. while (applyAsyncQueue.length) {
  17139. try {
  17140. applyAsyncQueue.shift()();
  17141. } catch (e) {
  17142. $exceptionHandler(e);
  17143. }
  17144. }
  17145. applyAsyncId = null;
  17146. }
  17147. function scheduleApplyAsync() {
  17148. if (applyAsyncId === null) {
  17149. applyAsyncId = $browser.defer(function() {
  17150. $rootScope.$apply(flushApplyAsync);
  17151. });
  17152. }
  17153. }
  17154. }];
  17155. }
  17156. /**
  17157. * @ngdoc service
  17158. * @name $rootElement
  17159. *
  17160. * @description
  17161. * The root element of AngularJS application. This is either the element where {@link
  17162. * ng.directive:ngApp ngApp} was declared or the element passed into
  17163. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  17164. * location where the application's {@link auto.$injector $injector} service gets
  17165. * published, and can be retrieved using `$rootElement.injector()`.
  17166. */
  17167. // the implementation is in angular.bootstrap
  17168. /**
  17169. * @this
  17170. * @description
  17171. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  17172. */
  17173. function $$SanitizeUriProvider() {
  17174. var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/,
  17175. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  17176. /**
  17177. * @description
  17178. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17179. * urls during a[href] sanitization.
  17180. *
  17181. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17182. *
  17183. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  17184. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  17185. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17186. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17187. *
  17188. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17189. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17190. * chaining otherwise.
  17191. */
  17192. this.aHrefSanitizationWhitelist = function(regexp) {
  17193. if (isDefined(regexp)) {
  17194. aHrefSanitizationWhitelist = regexp;
  17195. return this;
  17196. }
  17197. return aHrefSanitizationWhitelist;
  17198. };
  17199. /**
  17200. * @description
  17201. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17202. * urls during img[src] sanitization.
  17203. *
  17204. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17205. *
  17206. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  17207. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  17208. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17209. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17210. *
  17211. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17212. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17213. * chaining otherwise.
  17214. */
  17215. this.imgSrcSanitizationWhitelist = function(regexp) {
  17216. if (isDefined(regexp)) {
  17217. imgSrcSanitizationWhitelist = regexp;
  17218. return this;
  17219. }
  17220. return imgSrcSanitizationWhitelist;
  17221. };
  17222. this.$get = function() {
  17223. return function sanitizeUri(uri, isImage) {
  17224. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  17225. var normalizedVal;
  17226. normalizedVal = urlResolve(uri && uri.trim()).href;
  17227. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  17228. return 'unsafe:' + normalizedVal;
  17229. }
  17230. return uri;
  17231. };
  17232. };
  17233. }
  17234. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17235. * Any commits to this file should be reviewed with security in mind. *
  17236. * Changes to this file can potentially create security vulnerabilities. *
  17237. * An approval from 2 Core members with history of modifying *
  17238. * this file is required. *
  17239. * *
  17240. * Does the change somehow allow for arbitrary javascript to be executed? *
  17241. * Or allows for someone to change the prototype of built-in objects? *
  17242. * Or gives undesired access to variables likes document or window? *
  17243. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17244. /* exported $SceProvider, $SceDelegateProvider */
  17245. var $sceMinErr = minErr('$sce');
  17246. var SCE_CONTEXTS = {
  17247. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  17248. HTML: 'html',
  17249. // Style statements or stylesheets. Currently unused in AngularJS.
  17250. CSS: 'css',
  17251. // An URL used in a context where it does not refer to a resource that loads code. Currently
  17252. // unused in AngularJS.
  17253. URL: 'url',
  17254. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  17255. // code. (e.g. ng-include, script src binding, templateUrl)
  17256. RESOURCE_URL: 'resourceUrl',
  17257. // Script. Currently unused in AngularJS.
  17258. JS: 'js'
  17259. };
  17260. // Helper functions follow.
  17261. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  17262. function snakeToCamel(name) {
  17263. return name
  17264. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  17265. }
  17266. function adjustMatcher(matcher) {
  17267. if (matcher === 'self') {
  17268. return matcher;
  17269. } else if (isString(matcher)) {
  17270. // Strings match exactly except for 2 wildcards - '*' and '**'.
  17271. // '*' matches any character except those from the set ':/.?&'.
  17272. // '**' matches any character (like .* in a RegExp).
  17273. // More than 2 *'s raises an error as it's ill defined.
  17274. if (matcher.indexOf('***') > -1) {
  17275. throw $sceMinErr('iwcard',
  17276. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  17277. }
  17278. matcher = escapeForRegexp(matcher).
  17279. replace(/\\\*\\\*/g, '.*').
  17280. replace(/\\\*/g, '[^:/.?&;]*');
  17281. return new RegExp('^' + matcher + '$');
  17282. } else if (isRegExp(matcher)) {
  17283. // The only other type of matcher allowed is a Regexp.
  17284. // Match entire URL / disallow partial matches.
  17285. // Flags are reset (i.e. no global, ignoreCase or multiline)
  17286. return new RegExp('^' + matcher.source + '$');
  17287. } else {
  17288. throw $sceMinErr('imatcher',
  17289. 'Matchers may only be "self", string patterns or RegExp objects');
  17290. }
  17291. }
  17292. function adjustMatchers(matchers) {
  17293. var adjustedMatchers = [];
  17294. if (isDefined(matchers)) {
  17295. forEach(matchers, function(matcher) {
  17296. adjustedMatchers.push(adjustMatcher(matcher));
  17297. });
  17298. }
  17299. return adjustedMatchers;
  17300. }
  17301. /**
  17302. * @ngdoc service
  17303. * @name $sceDelegate
  17304. * @kind function
  17305. *
  17306. * @description
  17307. *
  17308. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  17309. * Contextual Escaping (SCE)} services to AngularJS.
  17310. *
  17311. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  17312. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  17313. * SCE works in their application, which shouldn't be needed in most cases.
  17314. *
  17315. * <div class="alert alert-danger">
  17316. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  17317. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  17318. * changes to this service will also influence users, so be extra careful and document your changes.
  17319. * </div>
  17320. *
  17321. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  17322. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  17323. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  17324. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  17325. * work because `$sce` delegates to `$sceDelegate` for these operations.
  17326. *
  17327. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  17328. *
  17329. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  17330. * can override it completely to change the behavior of `$sce`, the common case would
  17331. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  17332. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  17333. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  17334. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  17335. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  17336. */
  17337. /**
  17338. * @ngdoc provider
  17339. * @name $sceDelegateProvider
  17340. * @this
  17341. *
  17342. * @description
  17343. *
  17344. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  17345. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17346. *
  17347. * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure
  17348. * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all
  17349. * places that use the `$sce.RESOURCE_URL` context). See
  17350. * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}
  17351. * and
  17352. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},
  17353. *
  17354. * For the general details about this service in AngularJS, read the main page for {@link ng.$sce
  17355. * Strict Contextual Escaping (SCE)}.
  17356. *
  17357. * **Example**: Consider the following case. <a name="example"></a>
  17358. *
  17359. * - your app is hosted at url `http://myapp.example.com/`
  17360. * - but some of your templates are hosted on other domains you control such as
  17361. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  17362. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  17363. *
  17364. * Here is what a secure configuration for this scenario might look like:
  17365. *
  17366. * ```
  17367. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  17368. * $sceDelegateProvider.resourceUrlWhitelist([
  17369. * // Allow same origin resource loads.
  17370. * 'self',
  17371. * // Allow loading from our assets domain. Notice the difference between * and **.
  17372. * 'http://srv*.assets.example.com/**'
  17373. * ]);
  17374. *
  17375. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  17376. * $sceDelegateProvider.resourceUrlBlacklist([
  17377. * 'http://myapp.example.com/clickThru**'
  17378. * ]);
  17379. * });
  17380. * ```
  17381. * Note that an empty whitelist will block every resource URL from being loaded, and will require
  17382. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  17383. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  17384. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  17385. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  17386. * from that whitelist. This helps to mitigate the security impact of certain types of issues, like
  17387. * for instance attacker-controlled `ng-includes`.
  17388. */
  17389. function $SceDelegateProvider() {
  17390. this.SCE_CONTEXTS = SCE_CONTEXTS;
  17391. // Resource URLs can also be trusted by policy.
  17392. var resourceUrlWhitelist = ['self'],
  17393. resourceUrlBlacklist = [];
  17394. /**
  17395. * @ngdoc method
  17396. * @name $sceDelegateProvider#resourceUrlWhitelist
  17397. * @kind function
  17398. *
  17399. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  17400. * provided. This must be an array or null. A snapshot of this array is used so further
  17401. * changes to the array are ignored.
  17402. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17403. * allowed in this array.
  17404. *
  17405. * @return {Array} The currently set whitelist array.
  17406. *
  17407. * @description
  17408. * Sets/Gets the whitelist of trusted resource URLs.
  17409. *
  17410. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  17411. * same origin resource requests.
  17412. *
  17413. * <div class="alert alert-warning">
  17414. * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin
  17415. * with other apps! It is a good idea to limit it to only your application's directory.
  17416. * </div>
  17417. */
  17418. this.resourceUrlWhitelist = function(value) {
  17419. if (arguments.length) {
  17420. resourceUrlWhitelist = adjustMatchers(value);
  17421. }
  17422. return resourceUrlWhitelist;
  17423. };
  17424. /**
  17425. * @ngdoc method
  17426. * @name $sceDelegateProvider#resourceUrlBlacklist
  17427. * @kind function
  17428. *
  17429. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  17430. * provided. This must be an array or null. A snapshot of this array is used so further
  17431. * changes to the array are ignored.</p><p>
  17432. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17433. * allowed in this array.</p><p>
  17434. * The typical usage for the blacklist is to **block
  17435. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  17436. * these would otherwise be trusted but actually return content from the redirected domain.
  17437. * </p><p>
  17438. * Finally, **the blacklist overrides the whitelist** and has the final say.
  17439. *
  17440. * @return {Array} The currently set blacklist array.
  17441. *
  17442. * @description
  17443. * Sets/Gets the blacklist of trusted resource URLs.
  17444. *
  17445. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  17446. * is no blacklist.)
  17447. */
  17448. this.resourceUrlBlacklist = function(value) {
  17449. if (arguments.length) {
  17450. resourceUrlBlacklist = adjustMatchers(value);
  17451. }
  17452. return resourceUrlBlacklist;
  17453. };
  17454. this.$get = ['$injector', function($injector) {
  17455. var htmlSanitizer = function htmlSanitizer(html) {
  17456. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17457. };
  17458. if ($injector.has('$sanitize')) {
  17459. htmlSanitizer = $injector.get('$sanitize');
  17460. }
  17461. function matchUrl(matcher, parsedUrl) {
  17462. if (matcher === 'self') {
  17463. return urlIsSameOrigin(parsedUrl);
  17464. } else {
  17465. // definitely a regex. See adjustMatchers()
  17466. return !!matcher.exec(parsedUrl.href);
  17467. }
  17468. }
  17469. function isResourceUrlAllowedByPolicy(url) {
  17470. var parsedUrl = urlResolve(url.toString());
  17471. var i, n, allowed = false;
  17472. // Ensure that at least one item from the whitelist allows this url.
  17473. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17474. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17475. allowed = true;
  17476. break;
  17477. }
  17478. }
  17479. if (allowed) {
  17480. // Ensure that no item from the blacklist blocked this url.
  17481. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17482. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17483. allowed = false;
  17484. break;
  17485. }
  17486. }
  17487. }
  17488. return allowed;
  17489. }
  17490. function generateHolderType(Base) {
  17491. var holderType = function TrustedValueHolderType(trustedValue) {
  17492. this.$$unwrapTrustedValue = function() {
  17493. return trustedValue;
  17494. };
  17495. };
  17496. if (Base) {
  17497. holderType.prototype = new Base();
  17498. }
  17499. holderType.prototype.valueOf = function sceValueOf() {
  17500. return this.$$unwrapTrustedValue();
  17501. };
  17502. holderType.prototype.toString = function sceToString() {
  17503. return this.$$unwrapTrustedValue().toString();
  17504. };
  17505. return holderType;
  17506. }
  17507. var trustedValueHolderBase = generateHolderType(),
  17508. byType = {};
  17509. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17510. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17511. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17512. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17513. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17514. /**
  17515. * @ngdoc method
  17516. * @name $sceDelegate#trustAs
  17517. *
  17518. * @description
  17519. * Returns a trusted representation of the parameter for the specified context. This trusted
  17520. * object will later on be used as-is, without any security check, by bindings or directives
  17521. * that require this security context.
  17522. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  17523. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  17524. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  17525. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  17526. * security risk.
  17527. *
  17528. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  17529. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  17530. * escaping.
  17531. *
  17532. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17533. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17534. *
  17535. * @param {*} value The value that should be considered trusted.
  17536. * @return {*} A trusted representation of value, that can be used in the given context.
  17537. */
  17538. function trustAs(type, trustedValue) {
  17539. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17540. if (!Constructor) {
  17541. throw $sceMinErr('icontext',
  17542. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17543. type, trustedValue);
  17544. }
  17545. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17546. return trustedValue;
  17547. }
  17548. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17549. // mutable objects, we ensure here that the value passed in is actually a string.
  17550. if (typeof trustedValue !== 'string') {
  17551. throw $sceMinErr('itype',
  17552. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17553. type);
  17554. }
  17555. return new Constructor(trustedValue);
  17556. }
  17557. /**
  17558. * @ngdoc method
  17559. * @name $sceDelegate#valueOf
  17560. *
  17561. * @description
  17562. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17563. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17564. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17565. *
  17566. * If the passed parameter is not a value that had been returned by {@link
  17567. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  17568. *
  17569. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17570. * call or anything else.
  17571. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17572. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17573. * `value` unchanged.
  17574. */
  17575. function valueOf(maybeTrusted) {
  17576. if (maybeTrusted instanceof trustedValueHolderBase) {
  17577. return maybeTrusted.$$unwrapTrustedValue();
  17578. } else {
  17579. return maybeTrusted;
  17580. }
  17581. }
  17582. /**
  17583. * @ngdoc method
  17584. * @name $sceDelegate#getTrusted
  17585. *
  17586. * @description
  17587. * Takes any input, and either returns a value that's safe to use in the specified context, or
  17588. * throws an exception.
  17589. *
  17590. * In practice, there are several cases. When given a string, this function runs checks
  17591. * and sanitization to make it safe without prior assumptions. When given the result of a {@link
  17592. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied
  17593. * value if that value's context is valid for this call's context. Finally, this function can
  17594. * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization
  17595. * is available or possible.)
  17596. *
  17597. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  17598. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17599. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  17600. * @return {*} A version of the value that's safe to use in the given context, or throws an
  17601. * exception if this is impossible.
  17602. */
  17603. function getTrusted(type, maybeTrusted) {
  17604. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17605. return maybeTrusted;
  17606. }
  17607. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17608. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  17609. // as-is.
  17610. if (constructor && maybeTrusted instanceof constructor) {
  17611. return maybeTrusted.$$unwrapTrustedValue();
  17612. }
  17613. // Otherwise, if we get here, then we may either make it safe, or throw an exception. This
  17614. // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL),
  17615. // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS
  17616. // has no corresponding sinks.
  17617. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17618. // RESOURCE_URL uses a whitelist.
  17619. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17620. return maybeTrusted;
  17621. } else {
  17622. throw $sceMinErr('insecurl',
  17623. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17624. maybeTrusted.toString());
  17625. }
  17626. } else if (type === SCE_CONTEXTS.HTML) {
  17627. // htmlSanitizer throws its own error when no sanitizer is available.
  17628. return htmlSanitizer(maybeTrusted);
  17629. }
  17630. // Default error when the $sce service has no way to make the input safe.
  17631. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17632. }
  17633. return { trustAs: trustAs,
  17634. getTrusted: getTrusted,
  17635. valueOf: valueOf };
  17636. }];
  17637. }
  17638. /**
  17639. * @ngdoc provider
  17640. * @name $sceProvider
  17641. * @this
  17642. *
  17643. * @description
  17644. *
  17645. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17646. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17647. * - override the default implementation with a custom delegate
  17648. *
  17649. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17650. */
  17651. /**
  17652. * @ngdoc service
  17653. * @name $sce
  17654. * @kind function
  17655. *
  17656. * @description
  17657. *
  17658. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17659. *
  17660. * ## Strict Contextual Escaping
  17661. *
  17662. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  17663. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  17664. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17665. *
  17666. * ### Overview
  17667. *
  17668. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  17669. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  17670. * run security checks on them (sanitizations, whitelists, depending on context), or throw when it
  17671. * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML
  17672. * can be sanitized, but template URLs cannot, for instance.
  17673. *
  17674. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  17675. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  17676. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  17677. * render the input as-is, you will need to mark it as trusted for that context before attempting
  17678. * to bind it.
  17679. *
  17680. * As of version 1.2, AngularJS ships with SCE enabled by default.
  17681. *
  17682. * ### In practice
  17683. *
  17684. * Here's an example of a binding in a privileged context:
  17685. *
  17686. * ```
  17687. * <input ng-model="userHtml" aria-label="User input">
  17688. * <div ng-bind-html="userHtml"></div>
  17689. * ```
  17690. *
  17691. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17692. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  17693. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  17694. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  17695. * controlled input creates security vulnerabilities.)
  17696. *
  17697. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17698. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17699. *
  17700. * How would you ensure that every place that used these types of bindings was bound to a value that
  17701. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17702. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17703. * properties/fields and forgot to update the binding to the sanitized value?
  17704. *
  17705. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  17706. * any similar validation process, unless there's a good reason to trust the given value in this
  17707. * context. That trust is formalized with a function call. This means that as a developer, you
  17708. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  17709. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  17710. * received from your server, sanitized by your library, etc. You can organize your codebase to
  17711. * help with this - perhaps allowing only the files in a specific directory to do this.
  17712. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  17713. * becomes a more manageable task.
  17714. *
  17715. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17716. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17717. * build the trusted versions of your values.
  17718. *
  17719. * ### How does it work?
  17720. *
  17721. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17722. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  17723. * a way to enforce the required security context in your data sink. Directives use {@link
  17724. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  17725. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  17726. * when binding without directives, AngularJS will understand the context of your bindings
  17727. * automatically.
  17728. *
  17729. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17730. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17731. * simplified):
  17732. *
  17733. * ```
  17734. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17735. * return function(scope, element, attr) {
  17736. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17737. * element.html(value || '');
  17738. * });
  17739. * };
  17740. * }];
  17741. * ```
  17742. *
  17743. * ### Impact on loading templates
  17744. *
  17745. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17746. * `templateUrl`'s specified by {@link guide/directive directives}.
  17747. *
  17748. * By default, AngularJS only loads templates from the same domain and protocol as the application
  17749. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17750. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17751. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17752. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17753. *
  17754. * *Please note*:
  17755. * The browser's
  17756. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17757. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17758. * policy apply in addition to this and may further restrict whether the template is successfully
  17759. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17760. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17761. * browsers.
  17762. *
  17763. * ### This feels like too much overhead
  17764. *
  17765. * It's important to remember that SCE only applies to interpolation expressions.
  17766. *
  17767. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17768. * call `$sce.trustAs` on them (e.g.
  17769. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. The `$sceDelegate` will
  17770. * also use the `$sanitize` service if it is available when binding untrusted values to
  17771. * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you
  17772. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  17773. * your application.
  17774. *
  17775. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17776. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17777. * It blocks loading templates from other domains or loading templates over http from an https
  17778. * served document. You can change these by setting your own custom {@link
  17779. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17780. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17781. *
  17782. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17783. * application that's secure and can be audited to verify that with much more ease than bolting
  17784. * security onto an application later.
  17785. *
  17786. * <a name="contexts"></a>
  17787. * ### What trusted context types are supported?
  17788. *
  17789. * | Context | Notes |
  17790. * |---------------------|----------------|
  17791. * | `$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 $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. |
  17792. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17793. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=`, `<img src=`, and some others sanitize their urls and don't constitute an SCE context.) |
  17794. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17795. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17796. *
  17797. *
  17798. * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17799. * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings
  17800. * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This
  17801. * might evolve.
  17802. *
  17803. * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17804. *
  17805. * Each element in these arrays must be one of the following:
  17806. *
  17807. * - **'self'**
  17808. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17809. * domain** as the application document using the **same protocol**.
  17810. * - **String** (except the special value `'self'`)
  17811. * - The string is matched against the full *normalized / absolute URL* of the resource
  17812. * being tested (substring matches are not good enough.)
  17813. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17814. * match themselves.
  17815. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17816. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17817. * in a whitelist.
  17818. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17819. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17820. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17821. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17822. * http://foo.example.com/templates/**).
  17823. * - **RegExp** (*see caveat below*)
  17824. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17825. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17826. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17827. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17828. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17829. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17830. * is highly recommended to use the string patterns and only fall back to regular expressions
  17831. * as a last resort.
  17832. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17833. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17834. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17835. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17836. * - If you are generating your JavaScript from some other templating engine (not
  17837. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17838. * remember to escape your regular expression (and be aware that you might need more than
  17839. * one level of escaping depending on your templating engine and the way you interpolated
  17840. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17841. * enough before coding your own. E.g. Ruby has
  17842. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17843. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17844. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17845. * Closure library's [goog.string.regExpEscape(s)](
  17846. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17847. *
  17848. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17849. *
  17850. * ### Show me an example using SCE.
  17851. *
  17852. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17853. * <file name="index.html">
  17854. * <div ng-controller="AppController as myCtrl">
  17855. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17856. * <b>User comments</b><br>
  17857. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17858. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17859. * exploit.
  17860. * <div class="well">
  17861. * <div ng-repeat="userComment in myCtrl.userComments">
  17862. * <b>{{userComment.name}}</b>:
  17863. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17864. * <br>
  17865. * </div>
  17866. * </div>
  17867. * </div>
  17868. * </file>
  17869. *
  17870. * <file name="script.js">
  17871. * angular.module('mySceApp', ['ngSanitize'])
  17872. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17873. * function AppController($http, $templateCache, $sce) {
  17874. * var self = this;
  17875. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17876. * self.userComments = response.data;
  17877. * });
  17878. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17879. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17880. * 'sanitization.&quot;">Hover over this text.</span>');
  17881. * }]);
  17882. * </file>
  17883. *
  17884. * <file name="test_data.json">
  17885. * [
  17886. * { "name": "Alice",
  17887. * "htmlComment":
  17888. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17889. * },
  17890. * { "name": "Bob",
  17891. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17892. * }
  17893. * ]
  17894. * </file>
  17895. *
  17896. * <file name="protractor.js" type="protractor">
  17897. * describe('SCE doc demo', function() {
  17898. * it('should sanitize untrusted values', function() {
  17899. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17900. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17901. * });
  17902. *
  17903. * it('should NOT sanitize explicitly trusted values', function() {
  17904. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17905. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17906. * 'sanitization.&quot;">Hover over this text.</span>');
  17907. * });
  17908. * });
  17909. * </file>
  17910. * </example>
  17911. *
  17912. *
  17913. *
  17914. * ## Can I disable SCE completely?
  17915. *
  17916. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17917. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17918. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17919. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17920. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  17921. * you are writing a library, you will cause security bugs applications using it.
  17922. *
  17923. * That said, here's how you can completely disable SCE:
  17924. *
  17925. * ```
  17926. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17927. * // Completely disable SCE. For demonstration purposes only!
  17928. * // Do not use in new projects or libraries.
  17929. * $sceProvider.enabled(false);
  17930. * });
  17931. * ```
  17932. *
  17933. */
  17934. function $SceProvider() {
  17935. var enabled = true;
  17936. /**
  17937. * @ngdoc method
  17938. * @name $sceProvider#enabled
  17939. * @kind function
  17940. *
  17941. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  17942. * @return {boolean} True if SCE is enabled, false otherwise.
  17943. *
  17944. * @description
  17945. * Enables/disables SCE and returns the current value.
  17946. */
  17947. this.enabled = function(value) {
  17948. if (arguments.length) {
  17949. enabled = !!value;
  17950. }
  17951. return enabled;
  17952. };
  17953. /* Design notes on the default implementation for SCE.
  17954. *
  17955. * The API contract for the SCE delegate
  17956. * -------------------------------------
  17957. * The SCE delegate object must provide the following 3 methods:
  17958. *
  17959. * - trustAs(contextEnum, value)
  17960. * This method is used to tell the SCE service that the provided value is OK to use in the
  17961. * contexts specified by contextEnum. It must return an object that will be accepted by
  17962. * getTrusted() for a compatible contextEnum and return this value.
  17963. *
  17964. * - valueOf(value)
  17965. * For values that were not produced by trustAs(), return them as is. For values that were
  17966. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17967. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17968. * such a value.
  17969. *
  17970. * - getTrusted(contextEnum, value)
  17971. * This function should return the a value that is safe to use in the context specified by
  17972. * contextEnum or throw and exception otherwise.
  17973. *
  17974. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17975. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17976. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17977. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17978. * return the same object passed in if it was found in the registry under a compatible context or
  17979. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17980. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17981. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17982. *
  17983. *
  17984. * A note on the inheritance model for SCE contexts
  17985. * ------------------------------------------------
  17986. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17987. * is purely an implementation details.
  17988. *
  17989. * The contract is simply this:
  17990. *
  17991. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17992. * will also succeed.
  17993. *
  17994. * Inheritance happens to capture this in a natural way. In some future, we may not use
  17995. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  17996. * be aware of this detail.
  17997. */
  17998. this.$get = ['$parse', '$sceDelegate', function(
  17999. $parse, $sceDelegate) {
  18000. // Support: IE 9-11 only
  18001. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  18002. // the "expression(javascript expression)" syntax which is insecure.
  18003. if (enabled && msie < 8) {
  18004. throw $sceMinErr('iequirks',
  18005. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  18006. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  18007. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  18008. }
  18009. var sce = shallowCopy(SCE_CONTEXTS);
  18010. /**
  18011. * @ngdoc method
  18012. * @name $sce#isEnabled
  18013. * @kind function
  18014. *
  18015. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  18016. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  18017. *
  18018. * @description
  18019. * Returns a boolean indicating if SCE is enabled.
  18020. */
  18021. sce.isEnabled = function() {
  18022. return enabled;
  18023. };
  18024. sce.trustAs = $sceDelegate.trustAs;
  18025. sce.getTrusted = $sceDelegate.getTrusted;
  18026. sce.valueOf = $sceDelegate.valueOf;
  18027. if (!enabled) {
  18028. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  18029. sce.valueOf = identity;
  18030. }
  18031. /**
  18032. * @ngdoc method
  18033. * @name $sce#parseAs
  18034. *
  18035. * @description
  18036. * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link
  18037. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  18038. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  18039. * *result*)}
  18040. *
  18041. * @param {string} type The SCE context in which this result will be used.
  18042. * @param {string} expression String expression to compile.
  18043. * @return {function(context, locals)} A function which represents the compiled expression:
  18044. *
  18045. * * `context` – `{object}` – an object against which any expressions embedded in the
  18046. * strings are evaluated against (typically a scope object).
  18047. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18048. * in `context`.
  18049. */
  18050. sce.parseAs = function sceParseAs(type, expr) {
  18051. var parsed = $parse(expr);
  18052. if (parsed.literal && parsed.constant) {
  18053. return parsed;
  18054. } else {
  18055. return $parse(expr, function(value) {
  18056. return sce.getTrusted(type, value);
  18057. });
  18058. }
  18059. };
  18060. /**
  18061. * @ngdoc method
  18062. * @name $sce#trustAs
  18063. *
  18064. * @description
  18065. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  18066. * wrapped object that represents your value, and the trust you have in its safety for the given
  18067. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  18068. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  18069. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  18070. *
  18071. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  18072. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  18073. *
  18074. * @param {*} value The value that that should be considered trusted.
  18075. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18076. * in the context you specified.
  18077. */
  18078. /**
  18079. * @ngdoc method
  18080. * @name $sce#trustAsHtml
  18081. *
  18082. * @description
  18083. * Shorthand method. `$sce.trustAsHtml(value)` →
  18084. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  18085. *
  18086. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  18087. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18088. * in `$sce.HTML` context (like `ng-bind-html`).
  18089. */
  18090. /**
  18091. * @ngdoc method
  18092. * @name $sce#trustAsCss
  18093. *
  18094. * @description
  18095. * Shorthand method. `$sce.trustAsCss(value)` →
  18096. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  18097. *
  18098. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  18099. * @return {*} A wrapped version of value that can be used as a trusted variant
  18100. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  18101. * almost no reasons to use this function so far.
  18102. */
  18103. /**
  18104. * @ngdoc method
  18105. * @name $sce#trustAsUrl
  18106. *
  18107. * @description
  18108. * Shorthand method. `$sce.trustAsUrl(value)` →
  18109. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  18110. *
  18111. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  18112. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18113. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  18114. * to use this function so far.
  18115. */
  18116. /**
  18117. * @ngdoc method
  18118. * @name $sce#trustAsResourceUrl
  18119. *
  18120. * @description
  18121. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  18122. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  18123. *
  18124. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  18125. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18126. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  18127. * bindings, ...)
  18128. */
  18129. /**
  18130. * @ngdoc method
  18131. * @name $sce#trustAsJs
  18132. *
  18133. * @description
  18134. * Shorthand method. `$sce.trustAsJs(value)` →
  18135. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  18136. *
  18137. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  18138. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18139. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  18140. * use this function so far.
  18141. */
  18142. /**
  18143. * @ngdoc method
  18144. * @name $sce#getTrusted
  18145. *
  18146. * @description
  18147. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  18148. * takes any input, and either returns a value that's safe to use in the specified context,
  18149. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  18150. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  18151. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  18152. * safe value (e.g., no sanitization is available or possible.)
  18153. *
  18154. * @param {string} type The context in which this value is to be used.
  18155. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  18156. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  18157. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18158. * exception if this is impossible.
  18159. */
  18160. /**
  18161. * @ngdoc method
  18162. * @name $sce#getTrustedHtml
  18163. *
  18164. * @description
  18165. * Shorthand method. `$sce.getTrustedHtml(value)` →
  18166. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  18167. *
  18168. * @param {*} value The value to pass to `$sce.getTrusted`.
  18169. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  18170. */
  18171. /**
  18172. * @ngdoc method
  18173. * @name $sce#getTrustedCss
  18174. *
  18175. * @description
  18176. * Shorthand method. `$sce.getTrustedCss(value)` →
  18177. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  18178. *
  18179. * @param {*} value The value to pass to `$sce.getTrusted`.
  18180. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  18181. */
  18182. /**
  18183. * @ngdoc method
  18184. * @name $sce#getTrustedUrl
  18185. *
  18186. * @description
  18187. * Shorthand method. `$sce.getTrustedUrl(value)` →
  18188. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  18189. *
  18190. * @param {*} value The value to pass to `$sce.getTrusted`.
  18191. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  18192. */
  18193. /**
  18194. * @ngdoc method
  18195. * @name $sce#getTrustedResourceUrl
  18196. *
  18197. * @description
  18198. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  18199. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  18200. *
  18201. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  18202. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  18203. */
  18204. /**
  18205. * @ngdoc method
  18206. * @name $sce#getTrustedJs
  18207. *
  18208. * @description
  18209. * Shorthand method. `$sce.getTrustedJs(value)` →
  18210. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  18211. *
  18212. * @param {*} value The value to pass to `$sce.getTrusted`.
  18213. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  18214. */
  18215. /**
  18216. * @ngdoc method
  18217. * @name $sce#parseAsHtml
  18218. *
  18219. * @description
  18220. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  18221. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  18222. *
  18223. * @param {string} expression String expression to compile.
  18224. * @return {function(context, locals)} A function which represents the compiled expression:
  18225. *
  18226. * * `context` – `{object}` – an object against which any expressions embedded in the
  18227. * strings are evaluated against (typically a scope object).
  18228. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18229. * in `context`.
  18230. */
  18231. /**
  18232. * @ngdoc method
  18233. * @name $sce#parseAsCss
  18234. *
  18235. * @description
  18236. * Shorthand method. `$sce.parseAsCss(value)` →
  18237. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  18238. *
  18239. * @param {string} expression String expression to compile.
  18240. * @return {function(context, locals)} A function which represents the compiled expression:
  18241. *
  18242. * * `context` – `{object}` – an object against which any expressions embedded in the
  18243. * strings are evaluated against (typically a scope object).
  18244. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18245. * in `context`.
  18246. */
  18247. /**
  18248. * @ngdoc method
  18249. * @name $sce#parseAsUrl
  18250. *
  18251. * @description
  18252. * Shorthand method. `$sce.parseAsUrl(value)` →
  18253. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  18254. *
  18255. * @param {string} expression String expression to compile.
  18256. * @return {function(context, locals)} A function which represents the compiled expression:
  18257. *
  18258. * * `context` – `{object}` – an object against which any expressions embedded in the
  18259. * strings are evaluated against (typically a scope object).
  18260. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18261. * in `context`.
  18262. */
  18263. /**
  18264. * @ngdoc method
  18265. * @name $sce#parseAsResourceUrl
  18266. *
  18267. * @description
  18268. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  18269. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  18270. *
  18271. * @param {string} expression String expression to compile.
  18272. * @return {function(context, locals)} A function which represents the compiled expression:
  18273. *
  18274. * * `context` – `{object}` – an object against which any expressions embedded in the
  18275. * strings are evaluated against (typically a scope object).
  18276. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18277. * in `context`.
  18278. */
  18279. /**
  18280. * @ngdoc method
  18281. * @name $sce#parseAsJs
  18282. *
  18283. * @description
  18284. * Shorthand method. `$sce.parseAsJs(value)` →
  18285. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  18286. *
  18287. * @param {string} expression String expression to compile.
  18288. * @return {function(context, locals)} A function which represents the compiled expression:
  18289. *
  18290. * * `context` – `{object}` – an object against which any expressions embedded in the
  18291. * strings are evaluated against (typically a scope object).
  18292. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18293. * in `context`.
  18294. */
  18295. // Shorthand delegations.
  18296. var parse = sce.parseAs,
  18297. getTrusted = sce.getTrusted,
  18298. trustAs = sce.trustAs;
  18299. forEach(SCE_CONTEXTS, function(enumValue, name) {
  18300. var lName = lowercase(name);
  18301. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  18302. return parse(enumValue, expr);
  18303. };
  18304. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  18305. return getTrusted(enumValue, value);
  18306. };
  18307. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  18308. return trustAs(enumValue, value);
  18309. };
  18310. });
  18311. return sce;
  18312. }];
  18313. }
  18314. /* exported $SnifferProvider */
  18315. /**
  18316. * !!! This is an undocumented "private" service !!!
  18317. *
  18318. * @name $sniffer
  18319. * @requires $window
  18320. * @requires $document
  18321. * @this
  18322. *
  18323. * @property {boolean} history Does the browser support html5 history api ?
  18324. * @property {boolean} transitions Does the browser support CSS transition events ?
  18325. * @property {boolean} animations Does the browser support CSS animation events ?
  18326. *
  18327. * @description
  18328. * This is very simple implementation of testing browser's features.
  18329. */
  18330. function $SnifferProvider() {
  18331. this.$get = ['$window', '$document', function($window, $document) {
  18332. var eventSupport = {},
  18333. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  18334. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  18335. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  18336. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  18337. // (see https://developer.chrome.com/apps/manifest/sandbox).
  18338. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  18339. isNw = $window.nw && $window.nw.process,
  18340. isChromePackagedApp =
  18341. !isNw &&
  18342. $window.chrome &&
  18343. ($window.chrome.app && $window.chrome.app.runtime ||
  18344. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  18345. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  18346. android =
  18347. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  18348. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  18349. document = $document[0] || {},
  18350. bodyStyle = document.body && document.body.style,
  18351. transitions = false,
  18352. animations = false;
  18353. if (bodyStyle) {
  18354. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  18355. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  18356. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  18357. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  18358. }
  18359. return {
  18360. // Android has history.pushState, but it does not update location correctly
  18361. // so let's not use the history API at all.
  18362. // http://code.google.com/p/android/issues/detail?id=17471
  18363. // https://github.com/angular/angular.js/issues/904
  18364. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  18365. // so let's not use the history API also
  18366. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  18367. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  18368. hasEvent: function(event) {
  18369. // Support: IE 9-11 only
  18370. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  18371. // it. In particular the event is not fired when backspace or delete key are pressed or
  18372. // when cut operation is performed.
  18373. // IE10+ implements 'input' event but it erroneously fires under various situations,
  18374. // e.g. when placeholder changes, or a form is focused.
  18375. if (event === 'input' && msie) return false;
  18376. if (isUndefined(eventSupport[event])) {
  18377. var divElm = document.createElement('div');
  18378. eventSupport[event] = 'on' + event in divElm;
  18379. }
  18380. return eventSupport[event];
  18381. },
  18382. csp: csp(),
  18383. transitions: transitions,
  18384. animations: animations,
  18385. android: android
  18386. };
  18387. }];
  18388. }
  18389. var $templateRequestMinErr = minErr('$compile');
  18390. /**
  18391. * @ngdoc provider
  18392. * @name $templateRequestProvider
  18393. * @this
  18394. *
  18395. * @description
  18396. * Used to configure the options passed to the {@link $http} service when making a template request.
  18397. *
  18398. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  18399. * requesting a template.
  18400. */
  18401. function $TemplateRequestProvider() {
  18402. var httpOptions;
  18403. /**
  18404. * @ngdoc method
  18405. * @name $templateRequestProvider#httpOptions
  18406. * @description
  18407. * The options to be passed to the {@link $http} service when making the request.
  18408. * You can use this to override options such as the "Accept" header for template requests.
  18409. *
  18410. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  18411. * options if not overridden here.
  18412. *
  18413. * @param {string=} value new value for the {@link $http} options.
  18414. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  18415. */
  18416. this.httpOptions = function(val) {
  18417. if (val) {
  18418. httpOptions = val;
  18419. return this;
  18420. }
  18421. return httpOptions;
  18422. };
  18423. /**
  18424. * @ngdoc service
  18425. * @name $templateRequest
  18426. *
  18427. * @description
  18428. * The `$templateRequest` service runs security checks then downloads the provided template using
  18429. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  18430. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  18431. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  18432. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  18433. * when `tpl` is of type string and `$templateCache` has the matching entry.
  18434. *
  18435. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  18436. * can configure this via {@link $templateRequestProvider#httpOptions}.
  18437. *
  18438. * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such
  18439. * as {@link ngInclude} to download and cache templates.
  18440. *
  18441. * 3rd party modules should use `$templateRequest` if their services or directives are loading
  18442. * templates.
  18443. *
  18444. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  18445. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  18446. *
  18447. * @return {Promise} a promise for the HTTP response data of the given URL.
  18448. *
  18449. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  18450. */
  18451. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  18452. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  18453. function handleRequestFn(tpl, ignoreRequestError) {
  18454. handleRequestFn.totalPendingRequests++;
  18455. // We consider the template cache holds only trusted templates, so
  18456. // there's no need to go through whitelisting again for keys that already
  18457. // are included in there. This also makes AngularJS accept any script
  18458. // directive, no matter its name. However, we still need to unwrap trusted
  18459. // types.
  18460. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  18461. tpl = $sce.getTrustedResourceUrl(tpl);
  18462. }
  18463. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  18464. if (isArray(transformResponse)) {
  18465. transformResponse = transformResponse.filter(function(transformer) {
  18466. return transformer !== defaultHttpResponseTransform;
  18467. });
  18468. } else if (transformResponse === defaultHttpResponseTransform) {
  18469. transformResponse = null;
  18470. }
  18471. return $http.get(tpl, extend({
  18472. cache: $templateCache,
  18473. transformResponse: transformResponse
  18474. }, httpOptions))
  18475. .finally(function() {
  18476. handleRequestFn.totalPendingRequests--;
  18477. })
  18478. .then(function(response) {
  18479. $templateCache.put(tpl, response.data);
  18480. return response.data;
  18481. }, handleError);
  18482. function handleError(resp) {
  18483. if (!ignoreRequestError) {
  18484. resp = $templateRequestMinErr('tpload',
  18485. 'Failed to load template: {0} (HTTP status: {1} {2})',
  18486. tpl, resp.status, resp.statusText);
  18487. $exceptionHandler(resp);
  18488. }
  18489. return $q.reject(resp);
  18490. }
  18491. }
  18492. handleRequestFn.totalPendingRequests = 0;
  18493. return handleRequestFn;
  18494. }
  18495. ];
  18496. }
  18497. /** @this */
  18498. function $$TestabilityProvider() {
  18499. this.$get = ['$rootScope', '$browser', '$location',
  18500. function($rootScope, $browser, $location) {
  18501. /**
  18502. * @name $testability
  18503. *
  18504. * @description
  18505. * The private $$testability service provides a collection of methods for use when debugging
  18506. * or by automated test and debugging tools.
  18507. */
  18508. var testability = {};
  18509. /**
  18510. * @name $$testability#findBindings
  18511. *
  18512. * @description
  18513. * Returns an array of elements that are bound (via ng-bind or {{}})
  18514. * to expressions matching the input.
  18515. *
  18516. * @param {Element} element The element root to search from.
  18517. * @param {string} expression The binding expression to match.
  18518. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18519. * for the expression. Filters and whitespace are ignored.
  18520. */
  18521. testability.findBindings = function(element, expression, opt_exactMatch) {
  18522. var bindings = element.getElementsByClassName('ng-binding');
  18523. var matches = [];
  18524. forEach(bindings, function(binding) {
  18525. var dataBinding = angular.element(binding).data('$binding');
  18526. if (dataBinding) {
  18527. forEach(dataBinding, function(bindingName) {
  18528. if (opt_exactMatch) {
  18529. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18530. if (matcher.test(bindingName)) {
  18531. matches.push(binding);
  18532. }
  18533. } else {
  18534. if (bindingName.indexOf(expression) !== -1) {
  18535. matches.push(binding);
  18536. }
  18537. }
  18538. });
  18539. }
  18540. });
  18541. return matches;
  18542. };
  18543. /**
  18544. * @name $$testability#findModels
  18545. *
  18546. * @description
  18547. * Returns an array of elements that are two-way found via ng-model to
  18548. * expressions matching the input.
  18549. *
  18550. * @param {Element} element The element root to search from.
  18551. * @param {string} expression The model expression to match.
  18552. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18553. * for the expression.
  18554. */
  18555. testability.findModels = function(element, expression, opt_exactMatch) {
  18556. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18557. for (var p = 0; p < prefixes.length; ++p) {
  18558. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18559. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18560. var elements = element.querySelectorAll(selector);
  18561. if (elements.length) {
  18562. return elements;
  18563. }
  18564. }
  18565. };
  18566. /**
  18567. * @name $$testability#getLocation
  18568. *
  18569. * @description
  18570. * Shortcut for getting the location in a browser agnostic way. Returns
  18571. * the path, search, and hash. (e.g. /path?a=b#hash)
  18572. */
  18573. testability.getLocation = function() {
  18574. return $location.url();
  18575. };
  18576. /**
  18577. * @name $$testability#setLocation
  18578. *
  18579. * @description
  18580. * Shortcut for navigating to a location without doing a full page reload.
  18581. *
  18582. * @param {string} url The location url (path, search and hash,
  18583. * e.g. /path?a=b#hash) to go to.
  18584. */
  18585. testability.setLocation = function(url) {
  18586. if (url !== $location.url()) {
  18587. $location.url(url);
  18588. $rootScope.$digest();
  18589. }
  18590. };
  18591. /**
  18592. * @name $$testability#whenStable
  18593. *
  18594. * @description
  18595. * Calls the callback when $timeout and $http requests are completed.
  18596. *
  18597. * @param {function} callback
  18598. */
  18599. testability.whenStable = function(callback) {
  18600. $browser.notifyWhenNoOutstandingRequests(callback);
  18601. };
  18602. return testability;
  18603. }];
  18604. }
  18605. /** @this */
  18606. function $TimeoutProvider() {
  18607. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18608. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18609. var deferreds = {};
  18610. /**
  18611. * @ngdoc service
  18612. * @name $timeout
  18613. *
  18614. * @description
  18615. * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18616. * block and delegates any exceptions to
  18617. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18618. *
  18619. * The return value of calling `$timeout` is a promise, which will be resolved when
  18620. * the delay has passed and the timeout function, if provided, is executed.
  18621. *
  18622. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18623. *
  18624. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18625. * synchronously flush the queue of deferred functions.
  18626. *
  18627. * If you only want a promise that will be resolved after some specified delay
  18628. * then you can call `$timeout` without the `fn` function.
  18629. *
  18630. * @param {function()=} fn A function, whose execution should be delayed.
  18631. * @param {number=} [delay=0] Delay in milliseconds.
  18632. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18633. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18634. * @param {...*=} Pass additional parameters to the executed function.
  18635. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18636. * will be resolved with the return value of the `fn` function.
  18637. *
  18638. */
  18639. function timeout(fn, delay, invokeApply) {
  18640. if (!isFunction(fn)) {
  18641. invokeApply = delay;
  18642. delay = fn;
  18643. fn = noop;
  18644. }
  18645. var args = sliceArgs(arguments, 3),
  18646. skipApply = (isDefined(invokeApply) && !invokeApply),
  18647. deferred = (skipApply ? $$q : $q).defer(),
  18648. promise = deferred.promise,
  18649. timeoutId;
  18650. timeoutId = $browser.defer(function() {
  18651. try {
  18652. deferred.resolve(fn.apply(null, args));
  18653. } catch (e) {
  18654. deferred.reject(e);
  18655. $exceptionHandler(e);
  18656. } finally {
  18657. delete deferreds[promise.$$timeoutId];
  18658. }
  18659. if (!skipApply) $rootScope.$apply();
  18660. }, delay);
  18661. promise.$$timeoutId = timeoutId;
  18662. deferreds[timeoutId] = deferred;
  18663. return promise;
  18664. }
  18665. /**
  18666. * @ngdoc method
  18667. * @name $timeout#cancel
  18668. *
  18669. * @description
  18670. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18671. * resolved with a rejection.
  18672. *
  18673. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18674. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18675. * canceled.
  18676. */
  18677. timeout.cancel = function(promise) {
  18678. if (promise && promise.$$timeoutId in deferreds) {
  18679. // Timeout cancels should not report an unhandled promise.
  18680. markQExceptionHandled(deferreds[promise.$$timeoutId].promise);
  18681. deferreds[promise.$$timeoutId].reject('canceled');
  18682. delete deferreds[promise.$$timeoutId];
  18683. return $browser.defer.cancel(promise.$$timeoutId);
  18684. }
  18685. return false;
  18686. };
  18687. return timeout;
  18688. }];
  18689. }
  18690. // NOTE: The usage of window and document instead of $window and $document here is
  18691. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18692. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18693. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18694. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18695. // exactly the behavior needed here. There is little value is mocking these out for this
  18696. // service.
  18697. var urlParsingNode = window.document.createElement('a');
  18698. var originUrl = urlResolve(window.location.href);
  18699. /**
  18700. *
  18701. * Implementation Notes for non-IE browsers
  18702. * ----------------------------------------
  18703. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18704. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18705. * URL will be resolved into an absolute URL in the context of the application document.
  18706. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18707. * properties are all populated to reflect the normalized URL. This approach has wide
  18708. * compatibility - Safari 1+, Mozilla 1+ etc. See
  18709. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18710. *
  18711. * Implementation Notes for IE
  18712. * ---------------------------
  18713. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18714. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18715. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18716. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18717. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18718. * properties such as protocol, hostname, port, etc.
  18719. *
  18720. * References:
  18721. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18722. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18723. * http://url.spec.whatwg.org/#urlutils
  18724. * https://github.com/angular/angular.js/pull/2902
  18725. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18726. *
  18727. * @kind function
  18728. * @param {string} url The URL to be parsed.
  18729. * @description Normalizes and parses a URL.
  18730. * @returns {object} Returns the normalized URL as a dictionary.
  18731. *
  18732. * | member name | Description |
  18733. * |---------------|----------------|
  18734. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18735. * | protocol | The protocol including the trailing colon |
  18736. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18737. * | search | The search params, minus the question mark |
  18738. * | hash | The hash string, minus the hash symbol
  18739. * | hostname | The hostname
  18740. * | port | The port, without ":"
  18741. * | pathname | The pathname, beginning with "/"
  18742. *
  18743. */
  18744. function urlResolve(url) {
  18745. var href = url;
  18746. // Support: IE 9-11 only
  18747. if (msie) {
  18748. // Normalize before parse. Refer Implementation Notes on why this is
  18749. // done in two steps on IE.
  18750. urlParsingNode.setAttribute('href', href);
  18751. href = urlParsingNode.href;
  18752. }
  18753. urlParsingNode.setAttribute('href', href);
  18754. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18755. return {
  18756. href: urlParsingNode.href,
  18757. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18758. host: urlParsingNode.host,
  18759. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18760. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18761. hostname: urlParsingNode.hostname,
  18762. port: urlParsingNode.port,
  18763. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18764. ? urlParsingNode.pathname
  18765. : '/' + urlParsingNode.pathname
  18766. };
  18767. }
  18768. /**
  18769. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18770. *
  18771. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18772. * or a parsed URL object.
  18773. * @returns {boolean} Whether the request is for the same origin as the application document.
  18774. */
  18775. function urlIsSameOrigin(requestUrl) {
  18776. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18777. return (parsed.protocol === originUrl.protocol &&
  18778. parsed.host === originUrl.host);
  18779. }
  18780. /**
  18781. * @ngdoc service
  18782. * @name $window
  18783. * @this
  18784. *
  18785. * @description
  18786. * A reference to the browser's `window` object. While `window`
  18787. * is globally available in JavaScript, it causes testability problems, because
  18788. * it is a global variable. In AngularJS we always refer to it through the
  18789. * `$window` service, so it may be overridden, removed or mocked for testing.
  18790. *
  18791. * Expressions, like the one defined for the `ngClick` directive in the example
  18792. * below, are evaluated with respect to the current scope. Therefore, there is
  18793. * no risk of inadvertently coding in a dependency on a global value in such an
  18794. * expression.
  18795. *
  18796. * @example
  18797. <example module="windowExample" name="window-service">
  18798. <file name="index.html">
  18799. <script>
  18800. angular.module('windowExample', [])
  18801. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18802. $scope.greeting = 'Hello, World!';
  18803. $scope.doGreeting = function(greeting) {
  18804. $window.alert(greeting);
  18805. };
  18806. }]);
  18807. </script>
  18808. <div ng-controller="ExampleController">
  18809. <input type="text" ng-model="greeting" aria-label="greeting" />
  18810. <button ng-click="doGreeting(greeting)">ALERT</button>
  18811. </div>
  18812. </file>
  18813. <file name="protractor.js" type="protractor">
  18814. it('should display the greeting in the input box', function() {
  18815. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18816. // If we click the button it will block the test runner
  18817. // element(':button').click();
  18818. });
  18819. </file>
  18820. </example>
  18821. */
  18822. function $WindowProvider() {
  18823. this.$get = valueFn(window);
  18824. }
  18825. /**
  18826. * @name $$cookieReader
  18827. * @requires $document
  18828. *
  18829. * @description
  18830. * This is a private service for reading cookies used by $http and ngCookies
  18831. *
  18832. * @return {Object} a key/value map of the current cookies
  18833. */
  18834. function $$CookieReader($document) {
  18835. var rawDocument = $document[0] || {};
  18836. var lastCookies = {};
  18837. var lastCookieString = '';
  18838. function safeGetCookie(rawDocument) {
  18839. try {
  18840. return rawDocument.cookie || '';
  18841. } catch (e) {
  18842. return '';
  18843. }
  18844. }
  18845. function safeDecodeURIComponent(str) {
  18846. try {
  18847. return decodeURIComponent(str);
  18848. } catch (e) {
  18849. return str;
  18850. }
  18851. }
  18852. return function() {
  18853. var cookieArray, cookie, i, index, name;
  18854. var currentCookieString = safeGetCookie(rawDocument);
  18855. if (currentCookieString !== lastCookieString) {
  18856. lastCookieString = currentCookieString;
  18857. cookieArray = lastCookieString.split('; ');
  18858. lastCookies = {};
  18859. for (i = 0; i < cookieArray.length; i++) {
  18860. cookie = cookieArray[i];
  18861. index = cookie.indexOf('=');
  18862. if (index > 0) { //ignore nameless cookies
  18863. name = safeDecodeURIComponent(cookie.substring(0, index));
  18864. // the first value that is seen for a cookie is the most
  18865. // specific one. values for the same cookie name that
  18866. // follow are for less specific paths.
  18867. if (isUndefined(lastCookies[name])) {
  18868. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18869. }
  18870. }
  18871. }
  18872. }
  18873. return lastCookies;
  18874. };
  18875. }
  18876. $$CookieReader.$inject = ['$document'];
  18877. /** @this */
  18878. function $$CookieReaderProvider() {
  18879. this.$get = $$CookieReader;
  18880. }
  18881. /* global currencyFilter: true,
  18882. dateFilter: true,
  18883. filterFilter: true,
  18884. jsonFilter: true,
  18885. limitToFilter: true,
  18886. lowercaseFilter: true,
  18887. numberFilter: true,
  18888. orderByFilter: true,
  18889. uppercaseFilter: true,
  18890. */
  18891. /**
  18892. * @ngdoc provider
  18893. * @name $filterProvider
  18894. * @description
  18895. *
  18896. * Filters are just functions which transform input to an output. However filters need to be
  18897. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18898. * annotated with dependencies and is responsible for creating a filter function.
  18899. *
  18900. * <div class="alert alert-warning">
  18901. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18902. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18903. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18904. * (`myapp_subsection_filterx`).
  18905. * </div>
  18906. *
  18907. * ```js
  18908. * // Filter registration
  18909. * function MyModule($provide, $filterProvider) {
  18910. * // create a service to demonstrate injection (not always needed)
  18911. * $provide.value('greet', function(name){
  18912. * return 'Hello ' + name + '!';
  18913. * });
  18914. *
  18915. * // register a filter factory which uses the
  18916. * // greet service to demonstrate DI.
  18917. * $filterProvider.register('greet', function(greet){
  18918. * // return the filter function which uses the greet service
  18919. * // to generate salutation
  18920. * return function(text) {
  18921. * // filters need to be forgiving so check input validity
  18922. * return text && greet(text) || text;
  18923. * };
  18924. * });
  18925. * }
  18926. * ```
  18927. *
  18928. * The filter function is registered with the `$injector` under the filter name suffix with
  18929. * `Filter`.
  18930. *
  18931. * ```js
  18932. * it('should be the same instance', inject(
  18933. * function($filterProvider) {
  18934. * $filterProvider.register('reverse', function(){
  18935. * return ...;
  18936. * });
  18937. * },
  18938. * function($filter, reverseFilter) {
  18939. * expect($filter('reverse')).toBe(reverseFilter);
  18940. * });
  18941. * ```
  18942. *
  18943. *
  18944. * For more information about how AngularJS filters work, and how to create your own filters, see
  18945. * {@link guide/filter Filters} in the AngularJS Developer Guide.
  18946. */
  18947. /**
  18948. * @ngdoc service
  18949. * @name $filter
  18950. * @kind function
  18951. * @description
  18952. * Filters are used for formatting data displayed to the user.
  18953. *
  18954. * They can be used in view templates, controllers or services. AngularJS comes
  18955. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18956. * define your own as well.
  18957. *
  18958. * The general syntax in templates is as follows:
  18959. *
  18960. * ```html
  18961. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18962. * ```
  18963. *
  18964. * @param {String} name Name of the filter function to retrieve
  18965. * @return {Function} the filter function
  18966. * @example
  18967. <example name="$filter" module="filterExample">
  18968. <file name="index.html">
  18969. <div ng-controller="MainCtrl">
  18970. <h3>{{ originalText }}</h3>
  18971. <h3>{{ filteredText }}</h3>
  18972. </div>
  18973. </file>
  18974. <file name="script.js">
  18975. angular.module('filterExample', [])
  18976. .controller('MainCtrl', function($scope, $filter) {
  18977. $scope.originalText = 'hello';
  18978. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18979. });
  18980. </file>
  18981. </example>
  18982. */
  18983. $FilterProvider.$inject = ['$provide'];
  18984. /** @this */
  18985. function $FilterProvider($provide) {
  18986. var suffix = 'Filter';
  18987. /**
  18988. * @ngdoc method
  18989. * @name $filterProvider#register
  18990. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18991. * the keys are the filter names and the values are the filter factories.
  18992. *
  18993. * <div class="alert alert-warning">
  18994. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18995. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18996. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18997. * (`myapp_subsection_filterx`).
  18998. * </div>
  18999. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  19000. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  19001. * of the registered filter instances.
  19002. */
  19003. function register(name, factory) {
  19004. if (isObject(name)) {
  19005. var filters = {};
  19006. forEach(name, function(filter, key) {
  19007. filters[key] = register(key, filter);
  19008. });
  19009. return filters;
  19010. } else {
  19011. return $provide.factory(name + suffix, factory);
  19012. }
  19013. }
  19014. this.register = register;
  19015. this.$get = ['$injector', function($injector) {
  19016. return function(name) {
  19017. return $injector.get(name + suffix);
  19018. };
  19019. }];
  19020. ////////////////////////////////////////
  19021. /* global
  19022. currencyFilter: false,
  19023. dateFilter: false,
  19024. filterFilter: false,
  19025. jsonFilter: false,
  19026. limitToFilter: false,
  19027. lowercaseFilter: false,
  19028. numberFilter: false,
  19029. orderByFilter: false,
  19030. uppercaseFilter: false
  19031. */
  19032. register('currency', currencyFilter);
  19033. register('date', dateFilter);
  19034. register('filter', filterFilter);
  19035. register('json', jsonFilter);
  19036. register('limitTo', limitToFilter);
  19037. register('lowercase', lowercaseFilter);
  19038. register('number', numberFilter);
  19039. register('orderBy', orderByFilter);
  19040. register('uppercase', uppercaseFilter);
  19041. }
  19042. /**
  19043. * @ngdoc filter
  19044. * @name filter
  19045. * @kind function
  19046. *
  19047. * @description
  19048. * Selects a subset of items from `array` and returns it as a new array.
  19049. *
  19050. * @param {Array} array The source array.
  19051. * <div class="alert alert-info">
  19052. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  19053. * </div>
  19054. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  19055. * `array`.
  19056. *
  19057. * Can be one of:
  19058. *
  19059. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  19060. * objects with string properties in `array` that match this string will be returned. This also
  19061. * applies to nested object properties.
  19062. * The predicate can be negated by prefixing the string with `!`.
  19063. *
  19064. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  19065. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  19066. * which have property `name` containing "M" and property `phone` containing "1". A special
  19067. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  19068. * against any property of the object or its nested object properties. That's equivalent to the
  19069. * simple substring match with a `string` as described above. The special property name can be
  19070. * overwritten, using the `anyPropertyKey` parameter.
  19071. * The predicate can be negated by prefixing the string with `!`.
  19072. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  19073. * not containing "M".
  19074. *
  19075. * Note that a named property will match properties on the same level only, while the special
  19076. * `$` property will match properties on the same level or deeper. E.g. an array item like
  19077. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  19078. * **will** be matched by `{$: 'John'}`.
  19079. *
  19080. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  19081. * The function is called for each element of the array, with the element, its index, and
  19082. * the entire array itself as arguments.
  19083. *
  19084. * The final result is an array of those elements that the predicate returned true for.
  19085. *
  19086. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  19087. * determining if values retrieved using `expression` (when it is not a function) should be
  19088. * considered a match based on the expected value (from the filter expression) and actual
  19089. * value (from the object in the array).
  19090. *
  19091. * Can be one of:
  19092. *
  19093. * - `function(actual, expected)`:
  19094. * The function will be given the object value and the predicate value to compare and
  19095. * should return true if both values should be considered equal.
  19096. *
  19097. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  19098. * This is essentially strict comparison of expected and actual.
  19099. *
  19100. * - `false`: A short hand for a function which will look for a substring match in a case
  19101. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  19102. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  19103. *
  19104. *
  19105. * Defaults to `false`.
  19106. *
  19107. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  19108. * By default `$`.
  19109. *
  19110. * @example
  19111. <example name="filter-filter">
  19112. <file name="index.html">
  19113. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  19114. {name:'Mary', phone:'800-BIG-MARY'},
  19115. {name:'Mike', phone:'555-4321'},
  19116. {name:'Adam', phone:'555-5678'},
  19117. {name:'Julie', phone:'555-8765'},
  19118. {name:'Juliette', phone:'555-5678'}]"></div>
  19119. <label>Search: <input ng-model="searchText"></label>
  19120. <table id="searchTextResults">
  19121. <tr><th>Name</th><th>Phone</th></tr>
  19122. <tr ng-repeat="friend in friends | filter:searchText">
  19123. <td>{{friend.name}}</td>
  19124. <td>{{friend.phone}}</td>
  19125. </tr>
  19126. </table>
  19127. <hr>
  19128. <label>Any: <input ng-model="search.$"></label> <br>
  19129. <label>Name only <input ng-model="search.name"></label><br>
  19130. <label>Phone only <input ng-model="search.phone"></label><br>
  19131. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  19132. <table id="searchObjResults">
  19133. <tr><th>Name</th><th>Phone</th></tr>
  19134. <tr ng-repeat="friendObj in friends | filter:search:strict">
  19135. <td>{{friendObj.name}}</td>
  19136. <td>{{friendObj.phone}}</td>
  19137. </tr>
  19138. </table>
  19139. </file>
  19140. <file name="protractor.js" type="protractor">
  19141. var expectFriendNames = function(expectedNames, key) {
  19142. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  19143. arr.forEach(function(wd, i) {
  19144. expect(wd.getText()).toMatch(expectedNames[i]);
  19145. });
  19146. });
  19147. };
  19148. it('should search across all fields when filtering with a string', function() {
  19149. var searchText = element(by.model('searchText'));
  19150. searchText.clear();
  19151. searchText.sendKeys('m');
  19152. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  19153. searchText.clear();
  19154. searchText.sendKeys('76');
  19155. expectFriendNames(['John', 'Julie'], 'friend');
  19156. });
  19157. it('should search in specific fields when filtering with a predicate object', function() {
  19158. var searchAny = element(by.model('search.$'));
  19159. searchAny.clear();
  19160. searchAny.sendKeys('i');
  19161. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  19162. });
  19163. it('should use a equal comparison when comparator is true', function() {
  19164. var searchName = element(by.model('search.name'));
  19165. var strict = element(by.model('strict'));
  19166. searchName.clear();
  19167. searchName.sendKeys('Julie');
  19168. strict.click();
  19169. expectFriendNames(['Julie'], 'friendObj');
  19170. });
  19171. </file>
  19172. </example>
  19173. */
  19174. function filterFilter() {
  19175. return function(array, expression, comparator, anyPropertyKey) {
  19176. if (!isArrayLike(array)) {
  19177. if (array == null) {
  19178. return array;
  19179. } else {
  19180. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  19181. }
  19182. }
  19183. anyPropertyKey = anyPropertyKey || '$';
  19184. var expressionType = getTypeForFilter(expression);
  19185. var predicateFn;
  19186. var matchAgainstAnyProp;
  19187. switch (expressionType) {
  19188. case 'function':
  19189. predicateFn = expression;
  19190. break;
  19191. case 'boolean':
  19192. case 'null':
  19193. case 'number':
  19194. case 'string':
  19195. matchAgainstAnyProp = true;
  19196. // falls through
  19197. case 'object':
  19198. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19199. break;
  19200. default:
  19201. return array;
  19202. }
  19203. return Array.prototype.filter.call(array, predicateFn);
  19204. };
  19205. }
  19206. // Helper functions for `filterFilter`
  19207. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  19208. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  19209. var predicateFn;
  19210. if (comparator === true) {
  19211. comparator = equals;
  19212. } else if (!isFunction(comparator)) {
  19213. comparator = function(actual, expected) {
  19214. if (isUndefined(actual)) {
  19215. // No substring matching against `undefined`
  19216. return false;
  19217. }
  19218. if ((actual === null) || (expected === null)) {
  19219. // No substring matching against `null`; only match against `null`
  19220. return actual === expected;
  19221. }
  19222. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  19223. // Should not compare primitives against objects, unless they have custom `toString` method
  19224. return false;
  19225. }
  19226. actual = lowercase('' + actual);
  19227. expected = lowercase('' + expected);
  19228. return actual.indexOf(expected) !== -1;
  19229. };
  19230. }
  19231. predicateFn = function(item) {
  19232. if (shouldMatchPrimitives && !isObject(item)) {
  19233. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  19234. }
  19235. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19236. };
  19237. return predicateFn;
  19238. }
  19239. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  19240. var actualType = getTypeForFilter(actual);
  19241. var expectedType = getTypeForFilter(expected);
  19242. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  19243. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  19244. } else if (isArray(actual)) {
  19245. // In case `actual` is an array, consider it a match
  19246. // if ANY of it's items matches `expected`
  19247. return actual.some(function(item) {
  19248. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  19249. });
  19250. }
  19251. switch (actualType) {
  19252. case 'object':
  19253. var key;
  19254. if (matchAgainstAnyProp) {
  19255. for (key in actual) {
  19256. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  19257. // See: https://github.com/angular/angular.js/issues/15644
  19258. if (key.charAt && (key.charAt(0) !== '$') &&
  19259. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  19260. return true;
  19261. }
  19262. }
  19263. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  19264. } else if (expectedType === 'object') {
  19265. for (key in expected) {
  19266. var expectedVal = expected[key];
  19267. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  19268. continue;
  19269. }
  19270. var matchAnyProperty = key === anyPropertyKey;
  19271. var actualVal = matchAnyProperty ? actual : actual[key];
  19272. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  19273. return false;
  19274. }
  19275. }
  19276. return true;
  19277. } else {
  19278. return comparator(actual, expected);
  19279. }
  19280. case 'function':
  19281. return false;
  19282. default:
  19283. return comparator(actual, expected);
  19284. }
  19285. }
  19286. // Used for easily differentiating between `null` and actual `object`
  19287. function getTypeForFilter(val) {
  19288. return (val === null) ? 'null' : typeof val;
  19289. }
  19290. var MAX_DIGITS = 22;
  19291. var DECIMAL_SEP = '.';
  19292. var ZERO_CHAR = '0';
  19293. /**
  19294. * @ngdoc filter
  19295. * @name currency
  19296. * @kind function
  19297. *
  19298. * @description
  19299. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  19300. * symbol for current locale is used.
  19301. *
  19302. * @param {number} amount Input to filter.
  19303. * @param {string=} symbol Currency symbol or identifier to be displayed.
  19304. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  19305. * @returns {string} Formatted number.
  19306. *
  19307. *
  19308. * @example
  19309. <example module="currencyExample" name="currency-filter">
  19310. <file name="index.html">
  19311. <script>
  19312. angular.module('currencyExample', [])
  19313. .controller('ExampleController', ['$scope', function($scope) {
  19314. $scope.amount = 1234.56;
  19315. }]);
  19316. </script>
  19317. <div ng-controller="ExampleController">
  19318. <input type="number" ng-model="amount" aria-label="amount"> <br>
  19319. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  19320. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  19321. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  19322. </div>
  19323. </file>
  19324. <file name="protractor.js" type="protractor">
  19325. it('should init with 1234.56', function() {
  19326. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  19327. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  19328. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  19329. });
  19330. it('should update', function() {
  19331. if (browser.params.browser === 'safari') {
  19332. // Safari does not understand the minus key. See
  19333. // https://github.com/angular/protractor/issues/481
  19334. return;
  19335. }
  19336. element(by.model('amount')).clear();
  19337. element(by.model('amount')).sendKeys('-1234');
  19338. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  19339. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  19340. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  19341. });
  19342. </file>
  19343. </example>
  19344. */
  19345. currencyFilter.$inject = ['$locale'];
  19346. function currencyFilter($locale) {
  19347. var formats = $locale.NUMBER_FORMATS;
  19348. return function(amount, currencySymbol, fractionSize) {
  19349. if (isUndefined(currencySymbol)) {
  19350. currencySymbol = formats.CURRENCY_SYM;
  19351. }
  19352. if (isUndefined(fractionSize)) {
  19353. fractionSize = formats.PATTERNS[1].maxFrac;
  19354. }
  19355. // If the currency symbol is empty, trim whitespace around the symbol
  19356. var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g;
  19357. // if null or undefined pass it through
  19358. return (amount == null)
  19359. ? amount
  19360. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  19361. replace(currencySymbolRe, currencySymbol);
  19362. };
  19363. }
  19364. /**
  19365. * @ngdoc filter
  19366. * @name number
  19367. * @kind function
  19368. *
  19369. * @description
  19370. * Formats a number as text.
  19371. *
  19372. * If the input is null or undefined, it will just be returned.
  19373. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  19374. * If the input is not a number an empty string is returned.
  19375. *
  19376. *
  19377. * @param {number|string} number Number to format.
  19378. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  19379. * If this is not provided then the fraction size is computed from the current locale's number
  19380. * formatting pattern. In the case of the default locale, it will be 3.
  19381. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  19382. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  19383. * include "," group separators after each third digit).
  19384. *
  19385. * @example
  19386. <example module="numberFilterExample" name="number-filter">
  19387. <file name="index.html">
  19388. <script>
  19389. angular.module('numberFilterExample', [])
  19390. .controller('ExampleController', ['$scope', function($scope) {
  19391. $scope.val = 1234.56789;
  19392. }]);
  19393. </script>
  19394. <div ng-controller="ExampleController">
  19395. <label>Enter number: <input ng-model='val'></label><br>
  19396. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  19397. No fractions: <span>{{val | number:0}}</span><br>
  19398. Negative number: <span>{{-val | number:4}}</span>
  19399. </div>
  19400. </file>
  19401. <file name="protractor.js" type="protractor">
  19402. it('should format numbers', function() {
  19403. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  19404. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  19405. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  19406. });
  19407. it('should update', function() {
  19408. element(by.model('val')).clear();
  19409. element(by.model('val')).sendKeys('3374.333');
  19410. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  19411. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  19412. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  19413. });
  19414. </file>
  19415. </example>
  19416. */
  19417. numberFilter.$inject = ['$locale'];
  19418. function numberFilter($locale) {
  19419. var formats = $locale.NUMBER_FORMATS;
  19420. return function(number, fractionSize) {
  19421. // if null or undefined pass it through
  19422. return (number == null)
  19423. ? number
  19424. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  19425. fractionSize);
  19426. };
  19427. }
  19428. /**
  19429. * Parse a number (as a string) into three components that can be used
  19430. * for formatting the number.
  19431. *
  19432. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  19433. *
  19434. * @param {string} numStr The number to parse
  19435. * @return {object} An object describing this number, containing the following keys:
  19436. * - d : an array of digits containing leading zeros as necessary
  19437. * - i : the number of the digits in `d` that are to the left of the decimal point
  19438. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  19439. *
  19440. */
  19441. function parse(numStr) {
  19442. var exponent = 0, digits, numberOfIntegerDigits;
  19443. var i, j, zeros;
  19444. // Decimal point?
  19445. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  19446. numStr = numStr.replace(DECIMAL_SEP, '');
  19447. }
  19448. // Exponential form?
  19449. if ((i = numStr.search(/e/i)) > 0) {
  19450. // Work out the exponent.
  19451. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  19452. numberOfIntegerDigits += +numStr.slice(i + 1);
  19453. numStr = numStr.substring(0, i);
  19454. } else if (numberOfIntegerDigits < 0) {
  19455. // There was no decimal point or exponent so it is an integer.
  19456. numberOfIntegerDigits = numStr.length;
  19457. }
  19458. // Count the number of leading zeros.
  19459. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  19460. if (i === (zeros = numStr.length)) {
  19461. // The digits are all zero.
  19462. digits = [0];
  19463. numberOfIntegerDigits = 1;
  19464. } else {
  19465. // Count the number of trailing zeros
  19466. zeros--;
  19467. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  19468. // Trailing zeros are insignificant so ignore them
  19469. numberOfIntegerDigits -= i;
  19470. digits = [];
  19471. // Convert string to array of digits without leading/trailing zeros.
  19472. for (j = 0; i <= zeros; i++, j++) {
  19473. digits[j] = +numStr.charAt(i);
  19474. }
  19475. }
  19476. // If the number overflows the maximum allowed digits then use an exponent.
  19477. if (numberOfIntegerDigits > MAX_DIGITS) {
  19478. digits = digits.splice(0, MAX_DIGITS - 1);
  19479. exponent = numberOfIntegerDigits - 1;
  19480. numberOfIntegerDigits = 1;
  19481. }
  19482. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  19483. }
  19484. /**
  19485. * Round the parsed number to the specified number of decimal places
  19486. * This function changed the parsedNumber in-place
  19487. */
  19488. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  19489. var digits = parsedNumber.d;
  19490. var fractionLen = digits.length - parsedNumber.i;
  19491. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  19492. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  19493. // The index of the digit to where rounding is to occur
  19494. var roundAt = fractionSize + parsedNumber.i;
  19495. var digit = digits[roundAt];
  19496. if (roundAt > 0) {
  19497. // Drop fractional digits beyond `roundAt`
  19498. digits.splice(Math.max(parsedNumber.i, roundAt));
  19499. // Set non-fractional digits beyond `roundAt` to 0
  19500. for (var j = roundAt; j < digits.length; j++) {
  19501. digits[j] = 0;
  19502. }
  19503. } else {
  19504. // We rounded to zero so reset the parsedNumber
  19505. fractionLen = Math.max(0, fractionLen);
  19506. parsedNumber.i = 1;
  19507. digits.length = Math.max(1, roundAt = fractionSize + 1);
  19508. digits[0] = 0;
  19509. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  19510. }
  19511. if (digit >= 5) {
  19512. if (roundAt - 1 < 0) {
  19513. for (var k = 0; k > roundAt; k--) {
  19514. digits.unshift(0);
  19515. parsedNumber.i++;
  19516. }
  19517. digits.unshift(1);
  19518. parsedNumber.i++;
  19519. } else {
  19520. digits[roundAt - 1]++;
  19521. }
  19522. }
  19523. // Pad out with zeros to get the required fraction length
  19524. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  19525. // Do any carrying, e.g. a digit was rounded up to 10
  19526. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19527. d = d + carry;
  19528. digits[i] = d % 10;
  19529. return Math.floor(d / 10);
  19530. }, 0);
  19531. if (carry) {
  19532. digits.unshift(carry);
  19533. parsedNumber.i++;
  19534. }
  19535. }
  19536. /**
  19537. * Format a number into a string
  19538. * @param {number} number The number to format
  19539. * @param {{
  19540. * minFrac, // the minimum number of digits required in the fraction part of the number
  19541. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19542. * gSize, // number of digits in each group of separated digits
  19543. * lgSize, // number of digits in the last group of digits before the decimal separator
  19544. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19545. * posPre, // the string to go in front of a positive number
  19546. * negSuf, // the string to go after a negative number (e.g. `)`)
  19547. * posSuf // the string to go after a positive number
  19548. * }} pattern
  19549. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19550. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19551. * @param {[type]} fractionSize The size of the fractional part of the number
  19552. * @return {string} The number formatted as a string
  19553. */
  19554. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19555. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19556. var isInfinity = !isFinite(number);
  19557. var isZero = false;
  19558. var numStr = Math.abs(number) + '',
  19559. formattedText = '',
  19560. parsedNumber;
  19561. if (isInfinity) {
  19562. formattedText = '\u221e';
  19563. } else {
  19564. parsedNumber = parse(numStr);
  19565. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19566. var digits = parsedNumber.d;
  19567. var integerLen = parsedNumber.i;
  19568. var exponent = parsedNumber.e;
  19569. var decimals = [];
  19570. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19571. // pad zeros for small numbers
  19572. while (integerLen < 0) {
  19573. digits.unshift(0);
  19574. integerLen++;
  19575. }
  19576. // extract decimals digits
  19577. if (integerLen > 0) {
  19578. decimals = digits.splice(integerLen, digits.length);
  19579. } else {
  19580. decimals = digits;
  19581. digits = [0];
  19582. }
  19583. // format the integer digits with grouping separators
  19584. var groups = [];
  19585. if (digits.length >= pattern.lgSize) {
  19586. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19587. }
  19588. while (digits.length > pattern.gSize) {
  19589. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19590. }
  19591. if (digits.length) {
  19592. groups.unshift(digits.join(''));
  19593. }
  19594. formattedText = groups.join(groupSep);
  19595. // append the decimal digits
  19596. if (decimals.length) {
  19597. formattedText += decimalSep + decimals.join('');
  19598. }
  19599. if (exponent) {
  19600. formattedText += 'e+' + exponent;
  19601. }
  19602. }
  19603. if (number < 0 && !isZero) {
  19604. return pattern.negPre + formattedText + pattern.negSuf;
  19605. } else {
  19606. return pattern.posPre + formattedText + pattern.posSuf;
  19607. }
  19608. }
  19609. function padNumber(num, digits, trim, negWrap) {
  19610. var neg = '';
  19611. if (num < 0 || (negWrap && num <= 0)) {
  19612. if (negWrap) {
  19613. num = -num + 1;
  19614. } else {
  19615. num = -num;
  19616. neg = '-';
  19617. }
  19618. }
  19619. num = '' + num;
  19620. while (num.length < digits) num = ZERO_CHAR + num;
  19621. if (trim) {
  19622. num = num.substr(num.length - digits);
  19623. }
  19624. return neg + num;
  19625. }
  19626. function dateGetter(name, size, offset, trim, negWrap) {
  19627. offset = offset || 0;
  19628. return function(date) {
  19629. var value = date['get' + name]();
  19630. if (offset > 0 || value > -offset) {
  19631. value += offset;
  19632. }
  19633. if (value === 0 && offset === -12) value = 12;
  19634. return padNumber(value, size, trim, negWrap);
  19635. };
  19636. }
  19637. function dateStrGetter(name, shortForm, standAlone) {
  19638. return function(date, formats) {
  19639. var value = date['get' + name]();
  19640. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19641. var get = uppercase(propPrefix + name);
  19642. return formats[get][value];
  19643. };
  19644. }
  19645. function timeZoneGetter(date, formats, offset) {
  19646. var zone = -1 * offset;
  19647. var paddedZone = (zone >= 0) ? '+' : '';
  19648. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19649. padNumber(Math.abs(zone % 60), 2);
  19650. return paddedZone;
  19651. }
  19652. function getFirstThursdayOfYear(year) {
  19653. // 0 = index of January
  19654. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19655. // 4 = index of Thursday (+1 to account for 1st = 5)
  19656. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19657. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19658. }
  19659. function getThursdayThisWeek(datetime) {
  19660. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19661. // 4 = index of Thursday
  19662. datetime.getDate() + (4 - datetime.getDay()));
  19663. }
  19664. function weekGetter(size) {
  19665. return function(date) {
  19666. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19667. thisThurs = getThursdayThisWeek(date);
  19668. var diff = +thisThurs - +firstThurs,
  19669. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19670. return padNumber(result, size);
  19671. };
  19672. }
  19673. function ampmGetter(date, formats) {
  19674. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19675. }
  19676. function eraGetter(date, formats) {
  19677. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19678. }
  19679. function longEraGetter(date, formats) {
  19680. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19681. }
  19682. var DATE_FORMATS = {
  19683. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19684. yy: dateGetter('FullYear', 2, 0, true, true),
  19685. y: dateGetter('FullYear', 1, 0, false, true),
  19686. MMMM: dateStrGetter('Month'),
  19687. MMM: dateStrGetter('Month', true),
  19688. MM: dateGetter('Month', 2, 1),
  19689. M: dateGetter('Month', 1, 1),
  19690. LLLL: dateStrGetter('Month', false, true),
  19691. dd: dateGetter('Date', 2),
  19692. d: dateGetter('Date', 1),
  19693. HH: dateGetter('Hours', 2),
  19694. H: dateGetter('Hours', 1),
  19695. hh: dateGetter('Hours', 2, -12),
  19696. h: dateGetter('Hours', 1, -12),
  19697. mm: dateGetter('Minutes', 2),
  19698. m: dateGetter('Minutes', 1),
  19699. ss: dateGetter('Seconds', 2),
  19700. s: dateGetter('Seconds', 1),
  19701. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19702. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19703. sss: dateGetter('Milliseconds', 3),
  19704. EEEE: dateStrGetter('Day'),
  19705. EEE: dateStrGetter('Day', true),
  19706. a: ampmGetter,
  19707. Z: timeZoneGetter,
  19708. ww: weekGetter(2),
  19709. w: weekGetter(1),
  19710. G: eraGetter,
  19711. GG: eraGetter,
  19712. GGG: eraGetter,
  19713. GGGG: longEraGetter
  19714. };
  19715. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  19716. NUMBER_STRING = /^-?\d+$/;
  19717. /**
  19718. * @ngdoc filter
  19719. * @name date
  19720. * @kind function
  19721. *
  19722. * @description
  19723. * Formats `date` to a string based on the requested `format`.
  19724. *
  19725. * `format` string can be composed of the following elements:
  19726. *
  19727. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19728. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19729. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19730. * * `'MMMM'`: Month in year (January-December)
  19731. * * `'MMM'`: Month in year (Jan-Dec)
  19732. * * `'MM'`: Month in year, padded (01-12)
  19733. * * `'M'`: Month in year (1-12)
  19734. * * `'LLLL'`: Stand-alone month in year (January-December)
  19735. * * `'dd'`: Day in month, padded (01-31)
  19736. * * `'d'`: Day in month (1-31)
  19737. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19738. * * `'EEE'`: Day in Week, (Sun-Sat)
  19739. * * `'HH'`: Hour in day, padded (00-23)
  19740. * * `'H'`: Hour in day (0-23)
  19741. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19742. * * `'h'`: Hour in AM/PM, (1-12)
  19743. * * `'mm'`: Minute in hour, padded (00-59)
  19744. * * `'m'`: Minute in hour (0-59)
  19745. * * `'ss'`: Second in minute, padded (00-59)
  19746. * * `'s'`: Second in minute (0-59)
  19747. * * `'sss'`: Millisecond in second, padded (000-999)
  19748. * * `'a'`: AM/PM marker
  19749. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19750. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19751. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19752. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19753. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19754. *
  19755. * `format` string can also be one of the following predefined
  19756. * {@link guide/i18n localizable formats}:
  19757. *
  19758. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19759. * (e.g. Sep 3, 2010 12:05:08 PM)
  19760. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19761. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19762. * (e.g. Friday, September 3, 2010)
  19763. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19764. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19765. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19766. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19767. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19768. *
  19769. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19770. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19771. * (e.g. `"h 'o''clock'"`).
  19772. *
  19773. * Any other characters in the `format` string will be output as-is.
  19774. *
  19775. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19776. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19777. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19778. * specified in the string input, the time is considered to be in the local timezone.
  19779. * @param {string=} format Formatting rules (see Description). If not specified,
  19780. * `mediumDate` is used.
  19781. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19782. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19783. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19784. * If not specified, the timezone of the browser will be used.
  19785. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19786. *
  19787. * @example
  19788. <example name="filter-date">
  19789. <file name="index.html">
  19790. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19791. <span>{{1288323623006 | date:'medium'}}</span><br>
  19792. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19793. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19794. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19795. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19796. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19797. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19798. </file>
  19799. <file name="protractor.js" type="protractor">
  19800. it('should format date', function() {
  19801. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19802. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19803. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19804. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19805. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19806. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19807. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19808. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19809. });
  19810. </file>
  19811. </example>
  19812. */
  19813. dateFilter.$inject = ['$locale'];
  19814. function dateFilter($locale) {
  19815. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19816. // 1 2 3 4 5 6 7 8 9 10 11
  19817. function jsonStringToDate(string) {
  19818. var match;
  19819. if ((match = string.match(R_ISO8601_STR))) {
  19820. var date = new Date(0),
  19821. tzHour = 0,
  19822. tzMin = 0,
  19823. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19824. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19825. if (match[9]) {
  19826. tzHour = toInt(match[9] + match[10]);
  19827. tzMin = toInt(match[9] + match[11]);
  19828. }
  19829. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19830. var h = toInt(match[4] || 0) - tzHour;
  19831. var m = toInt(match[5] || 0) - tzMin;
  19832. var s = toInt(match[6] || 0);
  19833. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19834. timeSetter.call(date, h, m, s, ms);
  19835. return date;
  19836. }
  19837. return string;
  19838. }
  19839. return function(date, format, timezone) {
  19840. var text = '',
  19841. parts = [],
  19842. fn, match;
  19843. format = format || 'mediumDate';
  19844. format = $locale.DATETIME_FORMATS[format] || format;
  19845. if (isString(date)) {
  19846. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19847. }
  19848. if (isNumber(date)) {
  19849. date = new Date(date);
  19850. }
  19851. if (!isDate(date) || !isFinite(date.getTime())) {
  19852. return date;
  19853. }
  19854. while (format) {
  19855. match = DATE_FORMATS_SPLIT.exec(format);
  19856. if (match) {
  19857. parts = concat(parts, match, 1);
  19858. format = parts.pop();
  19859. } else {
  19860. parts.push(format);
  19861. format = null;
  19862. }
  19863. }
  19864. var dateTimezoneOffset = date.getTimezoneOffset();
  19865. if (timezone) {
  19866. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19867. date = convertTimezoneToLocal(date, timezone, true);
  19868. }
  19869. forEach(parts, function(value) {
  19870. fn = DATE_FORMATS[value];
  19871. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19872. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19873. });
  19874. return text;
  19875. };
  19876. }
  19877. /**
  19878. * @ngdoc filter
  19879. * @name json
  19880. * @kind function
  19881. *
  19882. * @description
  19883. * Allows you to convert a JavaScript object into JSON string.
  19884. *
  19885. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19886. * the binding is automatically converted to JSON.
  19887. *
  19888. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19889. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19890. * @returns {string} JSON string.
  19891. *
  19892. *
  19893. * @example
  19894. <example name="filter-json">
  19895. <file name="index.html">
  19896. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19897. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19898. </file>
  19899. <file name="protractor.js" type="protractor">
  19900. it('should jsonify filtered objects', function() {
  19901. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19902. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19903. });
  19904. </file>
  19905. </example>
  19906. *
  19907. */
  19908. function jsonFilter() {
  19909. return function(object, spacing) {
  19910. if (isUndefined(spacing)) {
  19911. spacing = 2;
  19912. }
  19913. return toJson(object, spacing);
  19914. };
  19915. }
  19916. /**
  19917. * @ngdoc filter
  19918. * @name lowercase
  19919. * @kind function
  19920. * @description
  19921. * Converts string to lowercase.
  19922. *
  19923. * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.
  19924. *
  19925. * @see angular.lowercase
  19926. */
  19927. var lowercaseFilter = valueFn(lowercase);
  19928. /**
  19929. * @ngdoc filter
  19930. * @name uppercase
  19931. * @kind function
  19932. * @description
  19933. * Converts string to uppercase.
  19934. * @example
  19935. <example module="uppercaseFilterExample" name="filter-uppercase">
  19936. <file name="index.html">
  19937. <script>
  19938. angular.module('uppercaseFilterExample', [])
  19939. .controller('ExampleController', ['$scope', function($scope) {
  19940. $scope.title = 'This is a title';
  19941. }]);
  19942. </script>
  19943. <div ng-controller="ExampleController">
  19944. <!-- This title should be formatted normally -->
  19945. <h1>{{title}}</h1>
  19946. <!-- This title should be capitalized -->
  19947. <h1>{{title | uppercase}}</h1>
  19948. </div>
  19949. </file>
  19950. </example>
  19951. */
  19952. var uppercaseFilter = valueFn(uppercase);
  19953. /**
  19954. * @ngdoc filter
  19955. * @name limitTo
  19956. * @kind function
  19957. *
  19958. * @description
  19959. * Creates a new array or string containing only a specified number of elements. The elements are
  19960. * taken from either the beginning or the end of the source array, string or number, as specified by
  19961. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19962. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19963. * it is converted to a string.
  19964. *
  19965. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19966. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19967. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19968. * If the number is negative, `limit` number of items from the end of the source array/string
  19969. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19970. * the input will be returned unchanged.
  19971. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19972. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19973. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19974. * less than `limit` elements.
  19975. *
  19976. * @example
  19977. <example module="limitToExample" name="limit-to-filter">
  19978. <file name="index.html">
  19979. <script>
  19980. angular.module('limitToExample', [])
  19981. .controller('ExampleController', ['$scope', function($scope) {
  19982. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19983. $scope.letters = "abcdefghi";
  19984. $scope.longNumber = 2345432342;
  19985. $scope.numLimit = 3;
  19986. $scope.letterLimit = 3;
  19987. $scope.longNumberLimit = 3;
  19988. }]);
  19989. </script>
  19990. <div ng-controller="ExampleController">
  19991. <label>
  19992. Limit {{numbers}} to:
  19993. <input type="number" step="1" ng-model="numLimit">
  19994. </label>
  19995. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19996. <label>
  19997. Limit {{letters}} to:
  19998. <input type="number" step="1" ng-model="letterLimit">
  19999. </label>
  20000. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  20001. <label>
  20002. Limit {{longNumber}} to:
  20003. <input type="number" step="1" ng-model="longNumberLimit">
  20004. </label>
  20005. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  20006. </div>
  20007. </file>
  20008. <file name="protractor.js" type="protractor">
  20009. var numLimitInput = element(by.model('numLimit'));
  20010. var letterLimitInput = element(by.model('letterLimit'));
  20011. var longNumberLimitInput = element(by.model('longNumberLimit'));
  20012. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  20013. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  20014. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  20015. it('should limit the number array to first three items', function() {
  20016. expect(numLimitInput.getAttribute('value')).toBe('3');
  20017. expect(letterLimitInput.getAttribute('value')).toBe('3');
  20018. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  20019. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  20020. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  20021. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  20022. });
  20023. // There is a bug in safari and protractor that doesn't like the minus key
  20024. // it('should update the output when -3 is entered', function() {
  20025. // numLimitInput.clear();
  20026. // numLimitInput.sendKeys('-3');
  20027. // letterLimitInput.clear();
  20028. // letterLimitInput.sendKeys('-3');
  20029. // longNumberLimitInput.clear();
  20030. // longNumberLimitInput.sendKeys('-3');
  20031. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  20032. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  20033. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  20034. // });
  20035. it('should not exceed the maximum size of input array', function() {
  20036. numLimitInput.clear();
  20037. numLimitInput.sendKeys('100');
  20038. letterLimitInput.clear();
  20039. letterLimitInput.sendKeys('100');
  20040. longNumberLimitInput.clear();
  20041. longNumberLimitInput.sendKeys('100');
  20042. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  20043. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  20044. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  20045. });
  20046. </file>
  20047. </example>
  20048. */
  20049. function limitToFilter() {
  20050. return function(input, limit, begin) {
  20051. if (Math.abs(Number(limit)) === Infinity) {
  20052. limit = Number(limit);
  20053. } else {
  20054. limit = toInt(limit);
  20055. }
  20056. if (isNumberNaN(limit)) return input;
  20057. if (isNumber(input)) input = input.toString();
  20058. if (!isArrayLike(input)) return input;
  20059. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  20060. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  20061. if (limit >= 0) {
  20062. return sliceFn(input, begin, begin + limit);
  20063. } else {
  20064. if (begin === 0) {
  20065. return sliceFn(input, limit, input.length);
  20066. } else {
  20067. return sliceFn(input, Math.max(0, begin + limit), begin);
  20068. }
  20069. }
  20070. };
  20071. }
  20072. function sliceFn(input, begin, end) {
  20073. if (isString(input)) return input.slice(begin, end);
  20074. return slice.call(input, begin, end);
  20075. }
  20076. /**
  20077. * @ngdoc filter
  20078. * @name orderBy
  20079. * @kind function
  20080. *
  20081. * @description
  20082. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  20083. * function based on the values computed using the `expression` predicate.
  20084. *
  20085. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  20086. * `[{id: 'bar'}, {id: 'foo'}]`.
  20087. *
  20088. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  20089. * String, etc).
  20090. *
  20091. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  20092. * for the preceding one. The `expression` is evaluated against each item and the output is used
  20093. * for comparing with other items.
  20094. *
  20095. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  20096. * ascending order.
  20097. *
  20098. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  20099. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  20100. * strings alphabetically).
  20101. *
  20102. * ### Under the hood
  20103. *
  20104. * Ordering the specified `collection` happens in two phases:
  20105. *
  20106. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  20107. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  20108. * through a predicate that extracts the value of the `label` property, would be transformed to:
  20109. * ```
  20110. * {
  20111. * value: 'foo',
  20112. * type: 'string',
  20113. * index: ...
  20114. * }
  20115. * ```
  20116. * 2. The comparator function is used to sort the items, based on the derived values, types and
  20117. * indices.
  20118. *
  20119. * If you use a custom comparator, it will be called with pairs of objects of the form
  20120. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  20121. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  20122. * second, or `1` otherwise.
  20123. *
  20124. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  20125. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  20126. * dummy predicate that returns the item's index as `value`.
  20127. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  20128. *
  20129. * If a custom comparator still can't distinguish between two items, then they will be sorted based
  20130. * on their index using the built-in comparator.
  20131. *
  20132. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  20133. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  20134. * it to the comparator. The following rules govern the conversion:
  20135. *
  20136. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  20137. * used instead.<br />
  20138. * (If the object has a `valueOf()` method that returns another object, then the returned object
  20139. * will be used in subsequent steps.)
  20140. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  20141. * returns a primitive, its return value will be used instead.<br />
  20142. * (If the object has a `toString()` method that returns another object, then the returned object
  20143. * will be used in subsequent steps.)
  20144. * 3. No conversion; the object itself is used.
  20145. *
  20146. * ### The default comparator
  20147. *
  20148. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  20149. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  20150. * using their index in the original collection, and sorts values of different types by type.
  20151. *
  20152. * More specifically, it follows these steps to determine the relative order of items:
  20153. *
  20154. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  20155. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  20156. * locale-insensitive way.
  20157. * 3. If both values are objects, compare their indices instead.
  20158. * 4. Otherwise, return:
  20159. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  20160. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  20161. * - `1`, otherwise.
  20162. *
  20163. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  20164. * saved as numbers and not strings.
  20165. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  20166. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  20167. * other values.
  20168. *
  20169. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  20170. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  20171. * predicates) to be used by the comparator to determine the order of elements.
  20172. *
  20173. * Can be one of:
  20174. *
  20175. * - `Function`: A getter function. This function will be called with each item as argument and
  20176. * the return value will be used for sorting.
  20177. * - `string`: An AngularJS expression. This expression will be evaluated against each item and the
  20178. * result will be used for sorting. For example, use `'label'` to sort by a property called
  20179. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  20180. * property.<br />
  20181. * (The result of a constant expression is interpreted as a property name to be used for
  20182. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  20183. * property called `special name`.)<br />
  20184. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  20185. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  20186. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  20187. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  20188. * relative order of two items, the next predicate is used as a tie-breaker.
  20189. *
  20190. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  20191. *
  20192. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  20193. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  20194. * value pairs. If omitted, the built-in comparator will be used.
  20195. *
  20196. * @returns {Array} - The sorted array.
  20197. *
  20198. *
  20199. * @example
  20200. * ### Ordering a table with `ngRepeat`
  20201. *
  20202. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  20203. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  20204. * it defaults to the built-in comparator.
  20205. *
  20206. <example name="orderBy-static" module="orderByExample1">
  20207. <file name="index.html">
  20208. <div ng-controller="ExampleController">
  20209. <table class="friends">
  20210. <tr>
  20211. <th>Name</th>
  20212. <th>Phone Number</th>
  20213. <th>Age</th>
  20214. </tr>
  20215. <tr ng-repeat="friend in friends | orderBy:'-age'">
  20216. <td>{{friend.name}}</td>
  20217. <td>{{friend.phone}}</td>
  20218. <td>{{friend.age}}</td>
  20219. </tr>
  20220. </table>
  20221. </div>
  20222. </file>
  20223. <file name="script.js">
  20224. angular.module('orderByExample1', [])
  20225. .controller('ExampleController', ['$scope', function($scope) {
  20226. $scope.friends = [
  20227. {name: 'John', phone: '555-1212', age: 10},
  20228. {name: 'Mary', phone: '555-9876', age: 19},
  20229. {name: 'Mike', phone: '555-4321', age: 21},
  20230. {name: 'Adam', phone: '555-5678', age: 35},
  20231. {name: 'Julie', phone: '555-8765', age: 29}
  20232. ];
  20233. }]);
  20234. </file>
  20235. <file name="style.css">
  20236. .friends {
  20237. border-collapse: collapse;
  20238. }
  20239. .friends th {
  20240. border-bottom: 1px solid;
  20241. }
  20242. .friends td, .friends th {
  20243. border-left: 1px solid;
  20244. padding: 5px 10px;
  20245. }
  20246. .friends td:first-child, .friends th:first-child {
  20247. border-left: none;
  20248. }
  20249. </file>
  20250. <file name="protractor.js" type="protractor">
  20251. // Element locators
  20252. var names = element.all(by.repeater('friends').column('friend.name'));
  20253. it('should sort friends by age in reverse order', function() {
  20254. expect(names.get(0).getText()).toBe('Adam');
  20255. expect(names.get(1).getText()).toBe('Julie');
  20256. expect(names.get(2).getText()).toBe('Mike');
  20257. expect(names.get(3).getText()).toBe('Mary');
  20258. expect(names.get(4).getText()).toBe('John');
  20259. });
  20260. </file>
  20261. </example>
  20262. * <hr />
  20263. *
  20264. * @example
  20265. * ### Changing parameters dynamically
  20266. *
  20267. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  20268. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  20269. *
  20270. <example name="orderBy-dynamic" module="orderByExample2">
  20271. <file name="index.html">
  20272. <div ng-controller="ExampleController">
  20273. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20274. <hr/>
  20275. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  20276. <hr/>
  20277. <table class="friends">
  20278. <tr>
  20279. <th>
  20280. <button ng-click="sortBy('name')">Name</button>
  20281. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20282. </th>
  20283. <th>
  20284. <button ng-click="sortBy('phone')">Phone Number</button>
  20285. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20286. </th>
  20287. <th>
  20288. <button ng-click="sortBy('age')">Age</button>
  20289. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20290. </th>
  20291. </tr>
  20292. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  20293. <td>{{friend.name}}</td>
  20294. <td>{{friend.phone}}</td>
  20295. <td>{{friend.age}}</td>
  20296. </tr>
  20297. </table>
  20298. </div>
  20299. </file>
  20300. <file name="script.js">
  20301. angular.module('orderByExample2', [])
  20302. .controller('ExampleController', ['$scope', function($scope) {
  20303. var friends = [
  20304. {name: 'John', phone: '555-1212', age: 10},
  20305. {name: 'Mary', phone: '555-9876', age: 19},
  20306. {name: 'Mike', phone: '555-4321', age: 21},
  20307. {name: 'Adam', phone: '555-5678', age: 35},
  20308. {name: 'Julie', phone: '555-8765', age: 29}
  20309. ];
  20310. $scope.propertyName = 'age';
  20311. $scope.reverse = true;
  20312. $scope.friends = friends;
  20313. $scope.sortBy = function(propertyName) {
  20314. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  20315. $scope.propertyName = propertyName;
  20316. };
  20317. }]);
  20318. </file>
  20319. <file name="style.css">
  20320. .friends {
  20321. border-collapse: collapse;
  20322. }
  20323. .friends th {
  20324. border-bottom: 1px solid;
  20325. }
  20326. .friends td, .friends th {
  20327. border-left: 1px solid;
  20328. padding: 5px 10px;
  20329. }
  20330. .friends td:first-child, .friends th:first-child {
  20331. border-left: none;
  20332. }
  20333. .sortorder:after {
  20334. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20335. }
  20336. .sortorder.reverse:after {
  20337. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20338. }
  20339. </file>
  20340. <file name="protractor.js" type="protractor">
  20341. // Element locators
  20342. var unsortButton = element(by.partialButtonText('unsorted'));
  20343. var nameHeader = element(by.partialButtonText('Name'));
  20344. var phoneHeader = element(by.partialButtonText('Phone'));
  20345. var ageHeader = element(by.partialButtonText('Age'));
  20346. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20347. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20348. it('should sort friends by some property, when clicking on the column header', function() {
  20349. expect(firstName.getText()).toBe('Adam');
  20350. expect(lastName.getText()).toBe('John');
  20351. phoneHeader.click();
  20352. expect(firstName.getText()).toBe('John');
  20353. expect(lastName.getText()).toBe('Mary');
  20354. nameHeader.click();
  20355. expect(firstName.getText()).toBe('Adam');
  20356. expect(lastName.getText()).toBe('Mike');
  20357. ageHeader.click();
  20358. expect(firstName.getText()).toBe('John');
  20359. expect(lastName.getText()).toBe('Adam');
  20360. });
  20361. it('should sort friends in reverse order, when clicking on the same column', function() {
  20362. expect(firstName.getText()).toBe('Adam');
  20363. expect(lastName.getText()).toBe('John');
  20364. ageHeader.click();
  20365. expect(firstName.getText()).toBe('John');
  20366. expect(lastName.getText()).toBe('Adam');
  20367. ageHeader.click();
  20368. expect(firstName.getText()).toBe('Adam');
  20369. expect(lastName.getText()).toBe('John');
  20370. });
  20371. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20372. expect(firstName.getText()).toBe('Adam');
  20373. expect(lastName.getText()).toBe('John');
  20374. unsortButton.click();
  20375. expect(firstName.getText()).toBe('John');
  20376. expect(lastName.getText()).toBe('Julie');
  20377. });
  20378. </file>
  20379. </example>
  20380. * <hr />
  20381. *
  20382. * @example
  20383. * ### Using `orderBy` inside a controller
  20384. *
  20385. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  20386. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  20387. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  20388. *
  20389. <example name="orderBy-call-manually" module="orderByExample3">
  20390. <file name="index.html">
  20391. <div ng-controller="ExampleController">
  20392. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20393. <hr/>
  20394. <button ng-click="sortBy(null)">Set to unsorted</button>
  20395. <hr/>
  20396. <table class="friends">
  20397. <tr>
  20398. <th>
  20399. <button ng-click="sortBy('name')">Name</button>
  20400. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20401. </th>
  20402. <th>
  20403. <button ng-click="sortBy('phone')">Phone Number</button>
  20404. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20405. </th>
  20406. <th>
  20407. <button ng-click="sortBy('age')">Age</button>
  20408. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20409. </th>
  20410. </tr>
  20411. <tr ng-repeat="friend in friends">
  20412. <td>{{friend.name}}</td>
  20413. <td>{{friend.phone}}</td>
  20414. <td>{{friend.age}}</td>
  20415. </tr>
  20416. </table>
  20417. </div>
  20418. </file>
  20419. <file name="script.js">
  20420. angular.module('orderByExample3', [])
  20421. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  20422. var friends = [
  20423. {name: 'John', phone: '555-1212', age: 10},
  20424. {name: 'Mary', phone: '555-9876', age: 19},
  20425. {name: 'Mike', phone: '555-4321', age: 21},
  20426. {name: 'Adam', phone: '555-5678', age: 35},
  20427. {name: 'Julie', phone: '555-8765', age: 29}
  20428. ];
  20429. $scope.propertyName = 'age';
  20430. $scope.reverse = true;
  20431. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20432. $scope.sortBy = function(propertyName) {
  20433. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  20434. ? !$scope.reverse : false;
  20435. $scope.propertyName = propertyName;
  20436. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20437. };
  20438. }]);
  20439. </file>
  20440. <file name="style.css">
  20441. .friends {
  20442. border-collapse: collapse;
  20443. }
  20444. .friends th {
  20445. border-bottom: 1px solid;
  20446. }
  20447. .friends td, .friends th {
  20448. border-left: 1px solid;
  20449. padding: 5px 10px;
  20450. }
  20451. .friends td:first-child, .friends th:first-child {
  20452. border-left: none;
  20453. }
  20454. .sortorder:after {
  20455. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20456. }
  20457. .sortorder.reverse:after {
  20458. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20459. }
  20460. </file>
  20461. <file name="protractor.js" type="protractor">
  20462. // Element locators
  20463. var unsortButton = element(by.partialButtonText('unsorted'));
  20464. var nameHeader = element(by.partialButtonText('Name'));
  20465. var phoneHeader = element(by.partialButtonText('Phone'));
  20466. var ageHeader = element(by.partialButtonText('Age'));
  20467. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20468. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20469. it('should sort friends by some property, when clicking on the column header', function() {
  20470. expect(firstName.getText()).toBe('Adam');
  20471. expect(lastName.getText()).toBe('John');
  20472. phoneHeader.click();
  20473. expect(firstName.getText()).toBe('John');
  20474. expect(lastName.getText()).toBe('Mary');
  20475. nameHeader.click();
  20476. expect(firstName.getText()).toBe('Adam');
  20477. expect(lastName.getText()).toBe('Mike');
  20478. ageHeader.click();
  20479. expect(firstName.getText()).toBe('John');
  20480. expect(lastName.getText()).toBe('Adam');
  20481. });
  20482. it('should sort friends in reverse order, when clicking on the same column', function() {
  20483. expect(firstName.getText()).toBe('Adam');
  20484. expect(lastName.getText()).toBe('John');
  20485. ageHeader.click();
  20486. expect(firstName.getText()).toBe('John');
  20487. expect(lastName.getText()).toBe('Adam');
  20488. ageHeader.click();
  20489. expect(firstName.getText()).toBe('Adam');
  20490. expect(lastName.getText()).toBe('John');
  20491. });
  20492. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20493. expect(firstName.getText()).toBe('Adam');
  20494. expect(lastName.getText()).toBe('John');
  20495. unsortButton.click();
  20496. expect(firstName.getText()).toBe('John');
  20497. expect(lastName.getText()).toBe('Julie');
  20498. });
  20499. </file>
  20500. </example>
  20501. * <hr />
  20502. *
  20503. * @example
  20504. * ### Using a custom comparator
  20505. *
  20506. * If you have very specific requirements about the way items are sorted, you can pass your own
  20507. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  20508. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  20509. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  20510. *
  20511. <example name="orderBy-custom-comparator" module="orderByExample4">
  20512. <file name="index.html">
  20513. <div ng-controller="ExampleController">
  20514. <div class="friends-container custom-comparator">
  20515. <h3>Locale-sensitive Comparator</h3>
  20516. <table class="friends">
  20517. <tr>
  20518. <th>Name</th>
  20519. <th>Favorite Letter</th>
  20520. </tr>
  20521. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  20522. <td>{{friend.name}}</td>
  20523. <td>{{friend.favoriteLetter}}</td>
  20524. </tr>
  20525. </table>
  20526. </div>
  20527. <div class="friends-container default-comparator">
  20528. <h3>Default Comparator</h3>
  20529. <table class="friends">
  20530. <tr>
  20531. <th>Name</th>
  20532. <th>Favorite Letter</th>
  20533. </tr>
  20534. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  20535. <td>{{friend.name}}</td>
  20536. <td>{{friend.favoriteLetter}}</td>
  20537. </tr>
  20538. </table>
  20539. </div>
  20540. </div>
  20541. </file>
  20542. <file name="script.js">
  20543. angular.module('orderByExample4', [])
  20544. .controller('ExampleController', ['$scope', function($scope) {
  20545. $scope.friends = [
  20546. {name: 'John', favoriteLetter: 'Ä'},
  20547. {name: 'Mary', favoriteLetter: 'Ü'},
  20548. {name: 'Mike', favoriteLetter: 'Ö'},
  20549. {name: 'Adam', favoriteLetter: 'H'},
  20550. {name: 'Julie', favoriteLetter: 'Z'}
  20551. ];
  20552. $scope.localeSensitiveComparator = function(v1, v2) {
  20553. // If we don't get strings, just compare by index
  20554. if (v1.type !== 'string' || v2.type !== 'string') {
  20555. return (v1.index < v2.index) ? -1 : 1;
  20556. }
  20557. // Compare strings alphabetically, taking locale into account
  20558. return v1.value.localeCompare(v2.value);
  20559. };
  20560. }]);
  20561. </file>
  20562. <file name="style.css">
  20563. .friends-container {
  20564. display: inline-block;
  20565. margin: 0 30px;
  20566. }
  20567. .friends {
  20568. border-collapse: collapse;
  20569. }
  20570. .friends th {
  20571. border-bottom: 1px solid;
  20572. }
  20573. .friends td, .friends th {
  20574. border-left: 1px solid;
  20575. padding: 5px 10px;
  20576. }
  20577. .friends td:first-child, .friends th:first-child {
  20578. border-left: none;
  20579. }
  20580. </file>
  20581. <file name="protractor.js" type="protractor">
  20582. // Element locators
  20583. var container = element(by.css('.custom-comparator'));
  20584. var names = container.all(by.repeater('friends').column('friend.name'));
  20585. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20586. expect(names.get(0).getText()).toBe('John');
  20587. expect(names.get(1).getText()).toBe('Adam');
  20588. expect(names.get(2).getText()).toBe('Mike');
  20589. expect(names.get(3).getText()).toBe('Mary');
  20590. expect(names.get(4).getText()).toBe('Julie');
  20591. });
  20592. </file>
  20593. </example>
  20594. *
  20595. */
  20596. orderByFilter.$inject = ['$parse'];
  20597. function orderByFilter($parse) {
  20598. return function(array, sortPredicate, reverseOrder, compareFn) {
  20599. if (array == null) return array;
  20600. if (!isArrayLike(array)) {
  20601. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20602. }
  20603. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20604. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20605. var predicates = processPredicates(sortPredicate);
  20606. var descending = reverseOrder ? -1 : 1;
  20607. // Define the `compare()` function. Use a default comparator if none is specified.
  20608. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20609. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20610. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20611. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20612. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20613. compareValues.sort(doComparison);
  20614. array = compareValues.map(function(item) { return item.value; });
  20615. return array;
  20616. function getComparisonObject(value, index) {
  20617. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20618. // This will be used to keep the sort stable when none of the input predicates can
  20619. // distinguish between two elements.
  20620. return {
  20621. value: value,
  20622. tieBreaker: {value: index, type: 'number', index: index},
  20623. predicateValues: predicates.map(function(predicate) {
  20624. return getPredicateValue(predicate.get(value), index);
  20625. })
  20626. };
  20627. }
  20628. function doComparison(v1, v2) {
  20629. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20630. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20631. if (result) {
  20632. return result * predicates[i].descending * descending;
  20633. }
  20634. }
  20635. return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
  20636. }
  20637. };
  20638. function processPredicates(sortPredicates) {
  20639. return sortPredicates.map(function(predicate) {
  20640. var descending = 1, get = identity;
  20641. if (isFunction(predicate)) {
  20642. get = predicate;
  20643. } else if (isString(predicate)) {
  20644. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20645. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20646. predicate = predicate.substring(1);
  20647. }
  20648. if (predicate !== '') {
  20649. get = $parse(predicate);
  20650. if (get.constant) {
  20651. var key = get();
  20652. get = function(value) { return value[key]; };
  20653. }
  20654. }
  20655. }
  20656. return {get: get, descending: descending};
  20657. });
  20658. }
  20659. function isPrimitive(value) {
  20660. switch (typeof value) {
  20661. case 'number': /* falls through */
  20662. case 'boolean': /* falls through */
  20663. case 'string':
  20664. return true;
  20665. default:
  20666. return false;
  20667. }
  20668. }
  20669. function objectValue(value) {
  20670. // If `valueOf` is a valid function use that
  20671. if (isFunction(value.valueOf)) {
  20672. value = value.valueOf();
  20673. if (isPrimitive(value)) return value;
  20674. }
  20675. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20676. if (hasCustomToString(value)) {
  20677. value = value.toString();
  20678. if (isPrimitive(value)) return value;
  20679. }
  20680. return value;
  20681. }
  20682. function getPredicateValue(value, index) {
  20683. var type = typeof value;
  20684. if (value === null) {
  20685. type = 'string';
  20686. value = 'null';
  20687. } else if (type === 'object') {
  20688. value = objectValue(value);
  20689. }
  20690. return {value: value, type: type, index: index};
  20691. }
  20692. function defaultCompare(v1, v2) {
  20693. var result = 0;
  20694. var type1 = v1.type;
  20695. var type2 = v2.type;
  20696. if (type1 === type2) {
  20697. var value1 = v1.value;
  20698. var value2 = v2.value;
  20699. if (type1 === 'string') {
  20700. // Compare strings case-insensitively
  20701. value1 = value1.toLowerCase();
  20702. value2 = value2.toLowerCase();
  20703. } else if (type1 === 'object') {
  20704. // For basic objects, use the position of the object
  20705. // in the collection instead of the value
  20706. if (isObject(value1)) value1 = v1.index;
  20707. if (isObject(value2)) value2 = v2.index;
  20708. }
  20709. if (value1 !== value2) {
  20710. result = value1 < value2 ? -1 : 1;
  20711. }
  20712. } else {
  20713. result = type1 < type2 ? -1 : 1;
  20714. }
  20715. return result;
  20716. }
  20717. }
  20718. function ngDirective(directive) {
  20719. if (isFunction(directive)) {
  20720. directive = {
  20721. link: directive
  20722. };
  20723. }
  20724. directive.restrict = directive.restrict || 'AC';
  20725. return valueFn(directive);
  20726. }
  20727. /**
  20728. * @ngdoc directive
  20729. * @name a
  20730. * @restrict E
  20731. *
  20732. * @description
  20733. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20734. * the href attribute is empty.
  20735. *
  20736. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20737. */
  20738. var htmlAnchorDirective = valueFn({
  20739. restrict: 'E',
  20740. compile: function(element, attr) {
  20741. if (!attr.href && !attr.xlinkHref) {
  20742. return function(scope, element) {
  20743. // If the linked element is not an anchor tag anymore, do nothing
  20744. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20745. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20746. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20747. 'xlink:href' : 'href';
  20748. element.on('click', function(event) {
  20749. // if we have no href url, then don't navigate anywhere.
  20750. if (!element.attr(href)) {
  20751. event.preventDefault();
  20752. }
  20753. });
  20754. };
  20755. }
  20756. }
  20757. });
  20758. /**
  20759. * @ngdoc directive
  20760. * @name ngHref
  20761. * @restrict A
  20762. * @priority 99
  20763. *
  20764. * @description
  20765. * Using AngularJS markup like `{{hash}}` in an href attribute will
  20766. * make the link go to the wrong URL if the user clicks it before
  20767. * AngularJS has a chance to replace the `{{hash}}` markup with its
  20768. * value. Until AngularJS replaces the markup the link will be broken
  20769. * and will most likely return a 404 error. The `ngHref` directive
  20770. * solves this problem.
  20771. *
  20772. * The wrong way to write it:
  20773. * ```html
  20774. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20775. * ```
  20776. *
  20777. * The correct way to write it:
  20778. * ```html
  20779. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20780. * ```
  20781. *
  20782. * @element A
  20783. * @param {template} ngHref any string which can contain `{{}}` markup.
  20784. *
  20785. * @example
  20786. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20787. * in links and their different behaviors:
  20788. <example name="ng-href">
  20789. <file name="index.html">
  20790. <input ng-model="value" /><br />
  20791. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20792. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20793. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20794. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20795. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20796. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20797. </file>
  20798. <file name="protractor.js" type="protractor">
  20799. it('should execute ng-click but not reload when href without value', function() {
  20800. element(by.id('link-1')).click();
  20801. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20802. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20803. });
  20804. it('should execute ng-click but not reload when href empty string', function() {
  20805. element(by.id('link-2')).click();
  20806. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20807. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20808. });
  20809. it('should execute ng-click and change url when ng-href specified', function() {
  20810. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20811. element(by.id('link-3')).click();
  20812. // At this point, we navigate away from an AngularJS page, so we need
  20813. // to use browser.driver to get the base webdriver.
  20814. browser.wait(function() {
  20815. return browser.driver.getCurrentUrl().then(function(url) {
  20816. return url.match(/\/123$/);
  20817. });
  20818. }, 5000, 'page should navigate to /123');
  20819. });
  20820. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20821. element(by.id('link-4')).click();
  20822. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20823. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20824. });
  20825. it('should execute ng-click but not reload when no href but name specified', function() {
  20826. element(by.id('link-5')).click();
  20827. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20828. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20829. });
  20830. it('should only change url when only ng-href', function() {
  20831. element(by.model('value')).clear();
  20832. element(by.model('value')).sendKeys('6');
  20833. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20834. element(by.id('link-6')).click();
  20835. // At this point, we navigate away from an AngularJS page, so we need
  20836. // to use browser.driver to get the base webdriver.
  20837. browser.wait(function() {
  20838. return browser.driver.getCurrentUrl().then(function(url) {
  20839. return url.match(/\/6$/);
  20840. });
  20841. }, 5000, 'page should navigate to /6');
  20842. });
  20843. </file>
  20844. </example>
  20845. */
  20846. /**
  20847. * @ngdoc directive
  20848. * @name ngSrc
  20849. * @restrict A
  20850. * @priority 99
  20851. *
  20852. * @description
  20853. * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't
  20854. * work right: The browser will fetch from the URL with the literal
  20855. * text `{{hash}}` until AngularJS replaces the expression inside
  20856. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20857. *
  20858. * The buggy way to write it:
  20859. * ```html
  20860. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20861. * ```
  20862. *
  20863. * The correct way to write it:
  20864. * ```html
  20865. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20866. * ```
  20867. *
  20868. * @element IMG
  20869. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20870. */
  20871. /**
  20872. * @ngdoc directive
  20873. * @name ngSrcset
  20874. * @restrict A
  20875. * @priority 99
  20876. *
  20877. * @description
  20878. * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't
  20879. * work right: The browser will fetch from the URL with the literal
  20880. * text `{{hash}}` until AngularJS replaces the expression inside
  20881. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20882. *
  20883. * The buggy way to write it:
  20884. * ```html
  20885. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20886. * ```
  20887. *
  20888. * The correct way to write it:
  20889. * ```html
  20890. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20891. * ```
  20892. *
  20893. * @element IMG
  20894. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20895. */
  20896. /**
  20897. * @ngdoc directive
  20898. * @name ngDisabled
  20899. * @restrict A
  20900. * @priority 100
  20901. *
  20902. * @description
  20903. *
  20904. * This directive sets the `disabled` attribute on the element (typically a form control,
  20905. * e.g. `input`, `button`, `select` etc.) if the
  20906. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20907. *
  20908. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20909. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20910. *
  20911. * @example
  20912. <example name="ng-disabled">
  20913. <file name="index.html">
  20914. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20915. <button ng-model="button" ng-disabled="checked">Button</button>
  20916. </file>
  20917. <file name="protractor.js" type="protractor">
  20918. it('should toggle button', function() {
  20919. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20920. element(by.model('checked')).click();
  20921. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20922. });
  20923. </file>
  20924. </example>
  20925. *
  20926. * @element INPUT
  20927. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20928. * then the `disabled` attribute will be set on the element
  20929. */
  20930. /**
  20931. * @ngdoc directive
  20932. * @name ngChecked
  20933. * @restrict A
  20934. * @priority 100
  20935. *
  20936. * @description
  20937. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20938. *
  20939. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20940. * as this can lead to unexpected behavior.
  20941. *
  20942. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20943. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20944. *
  20945. * @example
  20946. <example name="ng-checked">
  20947. <file name="index.html">
  20948. <label>Check me to check both: <input type="checkbox" ng-model="leader"></label><br/>
  20949. <input id="checkFollower" type="checkbox" ng-checked="leader" aria-label="Follower input">
  20950. </file>
  20951. <file name="protractor.js" type="protractor">
  20952. it('should check both checkBoxes', function() {
  20953. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy();
  20954. element(by.model('leader')).click();
  20955. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy();
  20956. });
  20957. </file>
  20958. </example>
  20959. *
  20960. * @element INPUT
  20961. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20962. * then the `checked` attribute will be set on the element
  20963. */
  20964. /**
  20965. * @ngdoc directive
  20966. * @name ngReadonly
  20967. * @restrict A
  20968. * @priority 100
  20969. *
  20970. * @description
  20971. *
  20972. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20973. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20974. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20975. *
  20976. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20977. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20978. *
  20979. * @example
  20980. <example name="ng-readonly">
  20981. <file name="index.html">
  20982. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20983. <input type="text" ng-readonly="checked" value="I'm AngularJS" aria-label="Readonly field" />
  20984. </file>
  20985. <file name="protractor.js" type="protractor">
  20986. it('should toggle readonly attr', function() {
  20987. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20988. element(by.model('checked')).click();
  20989. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20990. });
  20991. </file>
  20992. </example>
  20993. *
  20994. * @element INPUT
  20995. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20996. * then special attribute "readonly" will be set on the element
  20997. */
  20998. /**
  20999. * @ngdoc directive
  21000. * @name ngSelected
  21001. * @restrict A
  21002. * @priority 100
  21003. *
  21004. * @description
  21005. *
  21006. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  21007. *
  21008. * A special directive is necessary because we cannot use interpolation inside the `selected`
  21009. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21010. *
  21011. * <div class="alert alert-warning">
  21012. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  21013. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  21014. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  21015. * selected options.
  21016. * </div>
  21017. *
  21018. * @example
  21019. <example name="ng-selected">
  21020. <file name="index.html">
  21021. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  21022. <select aria-label="ngSelected demo">
  21023. <option>Hello!</option>
  21024. <option id="greet" ng-selected="selected">Greetings!</option>
  21025. </select>
  21026. </file>
  21027. <file name="protractor.js" type="protractor">
  21028. it('should select Greetings!', function() {
  21029. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  21030. element(by.model('selected')).click();
  21031. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  21032. });
  21033. </file>
  21034. </example>
  21035. *
  21036. * @element OPTION
  21037. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  21038. * then special attribute "selected" will be set on the element
  21039. */
  21040. /**
  21041. * @ngdoc directive
  21042. * @name ngOpen
  21043. * @restrict A
  21044. * @priority 100
  21045. *
  21046. * @description
  21047. *
  21048. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  21049. *
  21050. * A special directive is necessary because we cannot use interpolation inside the `open`
  21051. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21052. *
  21053. * ## A note about browser compatibility
  21054. *
  21055. * Internet Explorer and Edge do not support the `details` element, it is
  21056. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  21057. *
  21058. * @example
  21059. <example name="ng-open">
  21060. <file name="index.html">
  21061. <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/>
  21062. <details id="details" ng-open="open">
  21063. <summary>List</summary>
  21064. <ul>
  21065. <li>Apple</li>
  21066. <li>Orange</li>
  21067. <li>Durian</li>
  21068. </ul>
  21069. </details>
  21070. </file>
  21071. <file name="protractor.js" type="protractor">
  21072. it('should toggle open', function() {
  21073. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  21074. element(by.model('open')).click();
  21075. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  21076. });
  21077. </file>
  21078. </example>
  21079. *
  21080. * @element DETAILS
  21081. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  21082. * then special attribute "open" will be set on the element
  21083. */
  21084. var ngAttributeAliasDirectives = {};
  21085. // boolean attrs are evaluated
  21086. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  21087. // binding to multiple is not supported
  21088. if (propName === 'multiple') return;
  21089. function defaultLinkFn(scope, element, attr) {
  21090. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  21091. attr.$set(attrName, !!value);
  21092. });
  21093. }
  21094. var normalized = directiveNormalize('ng-' + attrName);
  21095. var linkFn = defaultLinkFn;
  21096. if (propName === 'checked') {
  21097. linkFn = function(scope, element, attr) {
  21098. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  21099. if (attr.ngModel !== attr[normalized]) {
  21100. defaultLinkFn(scope, element, attr);
  21101. }
  21102. };
  21103. }
  21104. ngAttributeAliasDirectives[normalized] = function() {
  21105. return {
  21106. restrict: 'A',
  21107. priority: 100,
  21108. link: linkFn
  21109. };
  21110. };
  21111. });
  21112. // aliased input attrs are evaluated
  21113. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  21114. ngAttributeAliasDirectives[ngAttr] = function() {
  21115. return {
  21116. priority: 100,
  21117. link: function(scope, element, attr) {
  21118. //special case ngPattern when a literal regular expression value
  21119. //is used as the expression (this way we don't have to watch anything).
  21120. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  21121. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  21122. if (match) {
  21123. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  21124. return;
  21125. }
  21126. }
  21127. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  21128. attr.$set(ngAttr, value);
  21129. });
  21130. }
  21131. };
  21132. };
  21133. });
  21134. // ng-src, ng-srcset, ng-href are interpolated
  21135. forEach(['src', 'srcset', 'href'], function(attrName) {
  21136. var normalized = directiveNormalize('ng-' + attrName);
  21137. ngAttributeAliasDirectives[normalized] = function() {
  21138. return {
  21139. priority: 99, // it needs to run after the attributes are interpolated
  21140. link: function(scope, element, attr) {
  21141. var propName = attrName,
  21142. name = attrName;
  21143. if (attrName === 'href' &&
  21144. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  21145. name = 'xlinkHref';
  21146. attr.$attr[name] = 'xlink:href';
  21147. propName = null;
  21148. }
  21149. attr.$observe(normalized, function(value) {
  21150. if (!value) {
  21151. if (attrName === 'href') {
  21152. attr.$set(name, null);
  21153. }
  21154. return;
  21155. }
  21156. attr.$set(name, value);
  21157. // Support: IE 9-11 only
  21158. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  21159. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  21160. // to set the property as well to achieve the desired effect.
  21161. // We use attr[attrName] value since $set can sanitize the url.
  21162. if (msie && propName) element.prop(propName, attr[name]);
  21163. });
  21164. }
  21165. };
  21166. };
  21167. });
  21168. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  21169. */
  21170. var nullFormCtrl = {
  21171. $addControl: noop,
  21172. $$renameControl: nullFormRenameControl,
  21173. $removeControl: noop,
  21174. $setValidity: noop,
  21175. $setDirty: noop,
  21176. $setPristine: noop,
  21177. $setSubmitted: noop
  21178. },
  21179. PENDING_CLASS = 'ng-pending',
  21180. SUBMITTED_CLASS = 'ng-submitted';
  21181. function nullFormRenameControl(control, name) {
  21182. control.$name = name;
  21183. }
  21184. /**
  21185. * @ngdoc type
  21186. * @name form.FormController
  21187. *
  21188. * @property {boolean} $pristine True if user has not interacted with the form yet.
  21189. * @property {boolean} $dirty True if user has already interacted with the form.
  21190. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  21191. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  21192. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  21193. *
  21194. * @property {Object} $pending An object hash, containing references to controls or forms with
  21195. * pending validators, where:
  21196. *
  21197. * - keys are validations tokens (error names).
  21198. * - values are arrays of controls or forms that have a pending validator for the given error name.
  21199. *
  21200. * See {@link form.FormController#$error $error} for a list of built-in validation tokens.
  21201. *
  21202. * @property {Object} $error An object hash, containing references to controls or forms with failing
  21203. * validators, where:
  21204. *
  21205. * - keys are validation tokens (error names),
  21206. * - values are arrays of controls or forms that have a failing validator for the given error name.
  21207. *
  21208. * Built-in validation tokens:
  21209. * - `email`
  21210. * - `max`
  21211. * - `maxlength`
  21212. * - `min`
  21213. * - `minlength`
  21214. * - `number`
  21215. * - `pattern`
  21216. * - `required`
  21217. * - `url`
  21218. * - `date`
  21219. * - `datetimelocal`
  21220. * - `time`
  21221. * - `week`
  21222. * - `month`
  21223. *
  21224. * @description
  21225. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  21226. * such as being valid/invalid or dirty/pristine.
  21227. *
  21228. * Each {@link ng.directive:form form} directive creates an instance
  21229. * of `FormController`.
  21230. *
  21231. */
  21232. //asks for $scope to fool the BC controller module
  21233. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  21234. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  21235. this.$$controls = [];
  21236. // init state
  21237. this.$error = {};
  21238. this.$$success = {};
  21239. this.$pending = undefined;
  21240. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  21241. this.$dirty = false;
  21242. this.$pristine = true;
  21243. this.$valid = true;
  21244. this.$invalid = false;
  21245. this.$submitted = false;
  21246. this.$$parentForm = nullFormCtrl;
  21247. this.$$element = $element;
  21248. this.$$animate = $animate;
  21249. setupValidity(this);
  21250. }
  21251. FormController.prototype = {
  21252. /**
  21253. * @ngdoc method
  21254. * @name form.FormController#$rollbackViewValue
  21255. *
  21256. * @description
  21257. * Rollback all form controls pending updates to the `$modelValue`.
  21258. *
  21259. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21260. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  21261. * a form that uses `ng-model-options` to pend updates.
  21262. */
  21263. $rollbackViewValue: function() {
  21264. forEach(this.$$controls, function(control) {
  21265. control.$rollbackViewValue();
  21266. });
  21267. },
  21268. /**
  21269. * @ngdoc method
  21270. * @name form.FormController#$commitViewValue
  21271. *
  21272. * @description
  21273. * Commit all form controls pending updates to the `$modelValue`.
  21274. *
  21275. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21276. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  21277. * usually handles calling this in response to input events.
  21278. */
  21279. $commitViewValue: function() {
  21280. forEach(this.$$controls, function(control) {
  21281. control.$commitViewValue();
  21282. });
  21283. },
  21284. /**
  21285. * @ngdoc method
  21286. * @name form.FormController#$addControl
  21287. * @param {object} control control object, either a {@link form.FormController} or an
  21288. * {@link ngModel.NgModelController}
  21289. *
  21290. * @description
  21291. * Register a control with the form. Input elements using ngModelController do this automatically
  21292. * when they are linked.
  21293. *
  21294. * Note that the current state of the control will not be reflected on the new parent form. This
  21295. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  21296. * state.
  21297. *
  21298. * However, if the method is used programmatically, for example by adding dynamically created controls,
  21299. * or controls that have been previously removed without destroying their corresponding DOM element,
  21300. * it's the developers responsibility to make sure the current state propagates to the parent form.
  21301. *
  21302. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  21303. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  21304. */
  21305. $addControl: function(control) {
  21306. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  21307. // and not added to the scope. Now we throw an error.
  21308. assertNotHasOwnProperty(control.$name, 'input');
  21309. this.$$controls.push(control);
  21310. if (control.$name) {
  21311. this[control.$name] = control;
  21312. }
  21313. control.$$parentForm = this;
  21314. },
  21315. // Private API: rename a form control
  21316. $$renameControl: function(control, newName) {
  21317. var oldName = control.$name;
  21318. if (this[oldName] === control) {
  21319. delete this[oldName];
  21320. }
  21321. this[newName] = control;
  21322. control.$name = newName;
  21323. },
  21324. /**
  21325. * @ngdoc method
  21326. * @name form.FormController#$removeControl
  21327. * @param {object} control control object, either a {@link form.FormController} or an
  21328. * {@link ngModel.NgModelController}
  21329. *
  21330. * @description
  21331. * Deregister a control from the form.
  21332. *
  21333. * Input elements using ngModelController do this automatically when they are destroyed.
  21334. *
  21335. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  21336. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  21337. * different from case to case. For example, removing the only `$dirty` control from a form may or
  21338. * may not mean that the form is still `$dirty`.
  21339. */
  21340. $removeControl: function(control) {
  21341. if (control.$name && this[control.$name] === control) {
  21342. delete this[control.$name];
  21343. }
  21344. forEach(this.$pending, function(value, name) {
  21345. // eslint-disable-next-line no-invalid-this
  21346. this.$setValidity(name, null, control);
  21347. }, this);
  21348. forEach(this.$error, function(value, name) {
  21349. // eslint-disable-next-line no-invalid-this
  21350. this.$setValidity(name, null, control);
  21351. }, this);
  21352. forEach(this.$$success, function(value, name) {
  21353. // eslint-disable-next-line no-invalid-this
  21354. this.$setValidity(name, null, control);
  21355. }, this);
  21356. arrayRemove(this.$$controls, control);
  21357. control.$$parentForm = nullFormCtrl;
  21358. },
  21359. /**
  21360. * @ngdoc method
  21361. * @name form.FormController#$setDirty
  21362. *
  21363. * @description
  21364. * Sets the form to a dirty state.
  21365. *
  21366. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  21367. * state (ng-dirty class). This method will also propagate to parent forms.
  21368. */
  21369. $setDirty: function() {
  21370. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  21371. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  21372. this.$dirty = true;
  21373. this.$pristine = false;
  21374. this.$$parentForm.$setDirty();
  21375. },
  21376. /**
  21377. * @ngdoc method
  21378. * @name form.FormController#$setPristine
  21379. *
  21380. * @description
  21381. * Sets the form to its pristine state.
  21382. *
  21383. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  21384. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  21385. * state to false.
  21386. *
  21387. * This method will also propagate to all the controls contained in this form.
  21388. *
  21389. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  21390. * saving or resetting it.
  21391. */
  21392. $setPristine: function() {
  21393. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  21394. this.$dirty = false;
  21395. this.$pristine = true;
  21396. this.$submitted = false;
  21397. forEach(this.$$controls, function(control) {
  21398. control.$setPristine();
  21399. });
  21400. },
  21401. /**
  21402. * @ngdoc method
  21403. * @name form.FormController#$setUntouched
  21404. *
  21405. * @description
  21406. * Sets the form to its untouched state.
  21407. *
  21408. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  21409. * untouched state (ng-untouched class).
  21410. *
  21411. * Setting a form controls back to their untouched state is often useful when setting the form
  21412. * back to its pristine state.
  21413. */
  21414. $setUntouched: function() {
  21415. forEach(this.$$controls, function(control) {
  21416. control.$setUntouched();
  21417. });
  21418. },
  21419. /**
  21420. * @ngdoc method
  21421. * @name form.FormController#$setSubmitted
  21422. *
  21423. * @description
  21424. * Sets the form to its submitted state.
  21425. */
  21426. $setSubmitted: function() {
  21427. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  21428. this.$submitted = true;
  21429. this.$$parentForm.$setSubmitted();
  21430. }
  21431. };
  21432. /**
  21433. * @ngdoc method
  21434. * @name form.FormController#$setValidity
  21435. *
  21436. * @description
  21437. * Change the validity state of the form, and notify the parent form (if any).
  21438. *
  21439. * Application developers will rarely need to call this method directly. It is used internally, by
  21440. * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a
  21441. * control's validity state to the parent `FormController`.
  21442. *
  21443. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be
  21444. * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for
  21445. * unfulfilled `$asyncValidators`), so that it is available for data-binding. The
  21446. * `validationErrorKey` should be in camelCase and will get converted into dash-case for
  21447. * class name. Example: `myError` will result in `ng-valid-my-error` and
  21448. * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.
  21449. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending
  21450. * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  21451. * Skipped is used by AngularJS when validators do not run because of parse errors and when
  21452. * `$asyncValidators` do not run because any of the `$validators` failed.
  21453. * @param {NgModelController | FormController} controller - The controller whose validity state is
  21454. * triggering the change.
  21455. */
  21456. addSetValidityMethod({
  21457. clazz: FormController,
  21458. set: function(object, property, controller) {
  21459. var list = object[property];
  21460. if (!list) {
  21461. object[property] = [controller];
  21462. } else {
  21463. var index = list.indexOf(controller);
  21464. if (index === -1) {
  21465. list.push(controller);
  21466. }
  21467. }
  21468. },
  21469. unset: function(object, property, controller) {
  21470. var list = object[property];
  21471. if (!list) {
  21472. return;
  21473. }
  21474. arrayRemove(list, controller);
  21475. if (list.length === 0) {
  21476. delete object[property];
  21477. }
  21478. }
  21479. });
  21480. /**
  21481. * @ngdoc directive
  21482. * @name ngForm
  21483. * @restrict EAC
  21484. *
  21485. * @description
  21486. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  21487. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  21488. * sub-group of controls needs to be determined.
  21489. *
  21490. * Note: the purpose of `ngForm` is to group controls,
  21491. * but not to be a replacement for the `<form>` tag with all of its capabilities
  21492. * (e.g. posting to the server, ...).
  21493. *
  21494. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  21495. * related scope, under this name.
  21496. *
  21497. */
  21498. /**
  21499. * @ngdoc directive
  21500. * @name form
  21501. * @restrict E
  21502. *
  21503. * @description
  21504. * Directive that instantiates
  21505. * {@link form.FormController FormController}.
  21506. *
  21507. * If the `name` attribute is specified, the form controller is published onto the current scope under
  21508. * this name.
  21509. *
  21510. * ## Alias: {@link ng.directive:ngForm `ngForm`}
  21511. *
  21512. * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child
  21513. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  21514. * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  21515. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  21516. * of controls needs to be determined.
  21517. *
  21518. * ## CSS classes
  21519. * - `ng-valid` is set if the form is valid.
  21520. * - `ng-invalid` is set if the form is invalid.
  21521. * - `ng-pending` is set if the form is pending.
  21522. * - `ng-pristine` is set if the form is pristine.
  21523. * - `ng-dirty` is set if the form is dirty.
  21524. * - `ng-submitted` is set if the form was submitted.
  21525. *
  21526. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21527. *
  21528. *
  21529. * ## Submitting a form and preventing the default action
  21530. *
  21531. * Since the role of forms in client-side AngularJS applications is different than in classical
  21532. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  21533. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  21534. * to handle the form submission in an application-specific way.
  21535. *
  21536. * For this reason, AngularJS prevents the default action (form submission to the server) unless the
  21537. * `<form>` element has an `action` attribute specified.
  21538. *
  21539. * You can use one of the following two ways to specify what javascript method should be called when
  21540. * a form is submitted:
  21541. *
  21542. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  21543. * - {@link ng.directive:ngClick ngClick} directive on the first
  21544. * button or input field of type submit (input[type=submit])
  21545. *
  21546. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  21547. * or {@link ng.directive:ngClick ngClick} directives.
  21548. * This is because of the following form submission rules in the HTML specification:
  21549. *
  21550. * - If a form has only one input field then hitting enter in this field triggers form submit
  21551. * (`ngSubmit`)
  21552. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  21553. * doesn't trigger submit
  21554. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  21555. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  21556. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  21557. *
  21558. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  21559. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21560. * to have access to the updated model.
  21561. *
  21562. * @animations
  21563. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  21564. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  21565. * other validations that are performed within the form. Animations in ngForm are similar to how
  21566. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  21567. * as JS animations.
  21568. *
  21569. * The following example shows a simple way to utilize CSS transitions to style a form element
  21570. * that has been rendered as invalid after it has been validated:
  21571. *
  21572. * <pre>
  21573. * //be sure to include ngAnimate as a module to hook into more
  21574. * //advanced animations
  21575. * .my-form {
  21576. * transition:0.5s linear all;
  21577. * background: white;
  21578. * }
  21579. * .my-form.ng-invalid {
  21580. * background: red;
  21581. * color:white;
  21582. * }
  21583. * </pre>
  21584. *
  21585. * @example
  21586. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21587. <file name="index.html">
  21588. <script>
  21589. angular.module('formExample', [])
  21590. .controller('FormController', ['$scope', function($scope) {
  21591. $scope.userType = 'guest';
  21592. }]);
  21593. </script>
  21594. <style>
  21595. .my-form {
  21596. transition:all linear 0.5s;
  21597. background: transparent;
  21598. }
  21599. .my-form.ng-invalid {
  21600. background: red;
  21601. }
  21602. </style>
  21603. <form name="myForm" ng-controller="FormController" class="my-form">
  21604. userType: <input name="input" ng-model="userType" required>
  21605. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21606. <code>userType = {{userType}}</code><br>
  21607. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21608. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21609. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21610. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21611. </form>
  21612. </file>
  21613. <file name="protractor.js" type="protractor">
  21614. it('should initialize to model', function() {
  21615. var userType = element(by.binding('userType'));
  21616. var valid = element(by.binding('myForm.input.$valid'));
  21617. expect(userType.getText()).toContain('guest');
  21618. expect(valid.getText()).toContain('true');
  21619. });
  21620. it('should be invalid if empty', function() {
  21621. var userType = element(by.binding('userType'));
  21622. var valid = element(by.binding('myForm.input.$valid'));
  21623. var userInput = element(by.model('userType'));
  21624. userInput.clear();
  21625. userInput.sendKeys('');
  21626. expect(userType.getText()).toEqual('userType =');
  21627. expect(valid.getText()).toContain('false');
  21628. });
  21629. </file>
  21630. </example>
  21631. *
  21632. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21633. * related scope, under this name.
  21634. */
  21635. var formDirectiveFactory = function(isNgForm) {
  21636. return ['$timeout', '$parse', function($timeout, $parse) {
  21637. var formDirective = {
  21638. name: 'form',
  21639. restrict: isNgForm ? 'EAC' : 'E',
  21640. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21641. controller: FormController,
  21642. compile: function ngFormCompile(formElement, attr) {
  21643. // Setup initial state of the control
  21644. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21645. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21646. return {
  21647. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21648. var controller = ctrls[0];
  21649. // if `action` attr is not present on the form, prevent the default action (submission)
  21650. if (!('action' in attr)) {
  21651. // we can't use jq events because if a form is destroyed during submission the default
  21652. // action is not prevented. see #1238
  21653. //
  21654. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21655. // page reload if the form was destroyed by submission of the form via a click handler
  21656. // on a button in the form. Looks like an IE9 specific bug.
  21657. var handleFormSubmission = function(event) {
  21658. scope.$apply(function() {
  21659. controller.$commitViewValue();
  21660. controller.$setSubmitted();
  21661. });
  21662. event.preventDefault();
  21663. };
  21664. formElement[0].addEventListener('submit', handleFormSubmission);
  21665. // unregister the preventDefault listener so that we don't not leak memory but in a
  21666. // way that will achieve the prevention of the default action.
  21667. formElement.on('$destroy', function() {
  21668. $timeout(function() {
  21669. formElement[0].removeEventListener('submit', handleFormSubmission);
  21670. }, 0, false);
  21671. });
  21672. }
  21673. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21674. parentFormCtrl.$addControl(controller);
  21675. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21676. if (nameAttr) {
  21677. setter(scope, controller);
  21678. attr.$observe(nameAttr, function(newValue) {
  21679. if (controller.$name === newValue) return;
  21680. setter(scope, undefined);
  21681. controller.$$parentForm.$$renameControl(controller, newValue);
  21682. setter = getSetter(controller.$name);
  21683. setter(scope, controller);
  21684. });
  21685. }
  21686. formElement.on('$destroy', function() {
  21687. controller.$$parentForm.$removeControl(controller);
  21688. setter(scope, undefined);
  21689. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21690. });
  21691. }
  21692. };
  21693. }
  21694. };
  21695. return formDirective;
  21696. function getSetter(expression) {
  21697. if (expression === '') {
  21698. //create an assignable expression, so forms with an empty name can be renamed later
  21699. return $parse('this[""]').assign;
  21700. }
  21701. return $parse(expression).assign || noop;
  21702. }
  21703. }];
  21704. };
  21705. var formDirective = formDirectiveFactory();
  21706. var ngFormDirective = formDirectiveFactory(true);
  21707. // helper methods
  21708. function setupValidity(instance) {
  21709. instance.$$classCache = {};
  21710. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21711. }
  21712. function addSetValidityMethod(context) {
  21713. var clazz = context.clazz,
  21714. set = context.set,
  21715. unset = context.unset;
  21716. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21717. if (isUndefined(state)) {
  21718. createAndSet(this, '$pending', validationErrorKey, controller);
  21719. } else {
  21720. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21721. }
  21722. if (!isBoolean(state)) {
  21723. unset(this.$error, validationErrorKey, controller);
  21724. unset(this.$$success, validationErrorKey, controller);
  21725. } else {
  21726. if (state) {
  21727. unset(this.$error, validationErrorKey, controller);
  21728. set(this.$$success, validationErrorKey, controller);
  21729. } else {
  21730. set(this.$error, validationErrorKey, controller);
  21731. unset(this.$$success, validationErrorKey, controller);
  21732. }
  21733. }
  21734. if (this.$pending) {
  21735. cachedToggleClass(this, PENDING_CLASS, true);
  21736. this.$valid = this.$invalid = undefined;
  21737. toggleValidationCss(this, '', null);
  21738. } else {
  21739. cachedToggleClass(this, PENDING_CLASS, false);
  21740. this.$valid = isObjectEmpty(this.$error);
  21741. this.$invalid = !this.$valid;
  21742. toggleValidationCss(this, '', this.$valid);
  21743. }
  21744. // re-read the state as the set/unset methods could have
  21745. // combined state in this.$error[validationError] (used for forms),
  21746. // where setting/unsetting only increments/decrements the value,
  21747. // and does not replace it.
  21748. var combinedState;
  21749. if (this.$pending && this.$pending[validationErrorKey]) {
  21750. combinedState = undefined;
  21751. } else if (this.$error[validationErrorKey]) {
  21752. combinedState = false;
  21753. } else if (this.$$success[validationErrorKey]) {
  21754. combinedState = true;
  21755. } else {
  21756. combinedState = null;
  21757. }
  21758. toggleValidationCss(this, validationErrorKey, combinedState);
  21759. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21760. };
  21761. function createAndSet(ctrl, name, value, controller) {
  21762. if (!ctrl[name]) {
  21763. ctrl[name] = {};
  21764. }
  21765. set(ctrl[name], value, controller);
  21766. }
  21767. function unsetAndCleanup(ctrl, name, value, controller) {
  21768. if (ctrl[name]) {
  21769. unset(ctrl[name], value, controller);
  21770. }
  21771. if (isObjectEmpty(ctrl[name])) {
  21772. ctrl[name] = undefined;
  21773. }
  21774. }
  21775. function cachedToggleClass(ctrl, className, switchValue) {
  21776. if (switchValue && !ctrl.$$classCache[className]) {
  21777. ctrl.$$animate.addClass(ctrl.$$element, className);
  21778. ctrl.$$classCache[className] = true;
  21779. } else if (!switchValue && ctrl.$$classCache[className]) {
  21780. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21781. ctrl.$$classCache[className] = false;
  21782. }
  21783. }
  21784. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21785. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21786. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21787. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21788. }
  21789. }
  21790. function isObjectEmpty(obj) {
  21791. if (obj) {
  21792. for (var prop in obj) {
  21793. if (obj.hasOwnProperty(prop)) {
  21794. return false;
  21795. }
  21796. }
  21797. }
  21798. return true;
  21799. }
  21800. /* global
  21801. VALID_CLASS: false,
  21802. INVALID_CLASS: false,
  21803. PRISTINE_CLASS: false,
  21804. DIRTY_CLASS: false,
  21805. ngModelMinErr: false
  21806. */
  21807. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21808. 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)$/;
  21809. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21810. // Note: We are being more lenient, because browsers are too.
  21811. // 1. Scheme
  21812. // 2. Slashes
  21813. // 3. Username
  21814. // 4. Password
  21815. // 5. Hostname
  21816. // 6. Port
  21817. // 7. Path
  21818. // 8. Query
  21819. // 9. Fragment
  21820. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21821. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21822. // eslint-disable-next-line max-len
  21823. 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])?)*$/;
  21824. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21825. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21826. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21827. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21828. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21829. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21830. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21831. var PARTIAL_VALIDATION_TYPES = createMap();
  21832. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21833. PARTIAL_VALIDATION_TYPES[type] = true;
  21834. });
  21835. var inputType = {
  21836. /**
  21837. * @ngdoc input
  21838. * @name input[text]
  21839. *
  21840. * @description
  21841. * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements.
  21842. *
  21843. *
  21844. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  21845. * @param {string=} name Property name of the form under which the control is published.
  21846. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21847. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21848. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21849. * `required` when you want to data-bind to the `required` attribute.
  21850. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21851. * minlength.
  21852. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21853. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21854. * any length.
  21855. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21856. * that contains the regular expression body that will be converted to a regular expression
  21857. * as in the ngPattern directive.
  21858. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21859. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  21860. * If the expression evaluates to a RegExp object, then this is used directly.
  21861. * If the expression evaluates to a string, then it will be converted to a RegExp
  21862. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21863. * `new RegExp('^abc$')`.<br />
  21864. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21865. * start at the index of the last search's match, thus not taking the whole input value into
  21866. * account.
  21867. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  21868. * interaction with the input element.
  21869. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  21870. * This parameter is ignored for input[type=password] controls, which will never trim the
  21871. * input.
  21872. *
  21873. * @example
  21874. <example name="text-input-directive" module="textInputExample">
  21875. <file name="index.html">
  21876. <script>
  21877. angular.module('textInputExample', [])
  21878. .controller('ExampleController', ['$scope', function($scope) {
  21879. $scope.example = {
  21880. text: 'guest',
  21881. word: /^\s*\w*\s*$/
  21882. };
  21883. }]);
  21884. </script>
  21885. <form name="myForm" ng-controller="ExampleController">
  21886. <label>Single word:
  21887. <input type="text" name="input" ng-model="example.text"
  21888. ng-pattern="example.word" required ng-trim="false">
  21889. </label>
  21890. <div role="alert">
  21891. <span class="error" ng-show="myForm.input.$error.required">
  21892. Required!</span>
  21893. <span class="error" ng-show="myForm.input.$error.pattern">
  21894. Single word only!</span>
  21895. </div>
  21896. <code>text = {{example.text}}</code><br/>
  21897. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21898. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21899. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21900. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21901. </form>
  21902. </file>
  21903. <file name="protractor.js" type="protractor">
  21904. var text = element(by.binding('example.text'));
  21905. var valid = element(by.binding('myForm.input.$valid'));
  21906. var input = element(by.model('example.text'));
  21907. it('should initialize to model', function() {
  21908. expect(text.getText()).toContain('guest');
  21909. expect(valid.getText()).toContain('true');
  21910. });
  21911. it('should be invalid if empty', function() {
  21912. input.clear();
  21913. input.sendKeys('');
  21914. expect(text.getText()).toEqual('text =');
  21915. expect(valid.getText()).toContain('false');
  21916. });
  21917. it('should be invalid if multi word', function() {
  21918. input.clear();
  21919. input.sendKeys('hello world');
  21920. expect(valid.getText()).toContain('false');
  21921. });
  21922. </file>
  21923. </example>
  21924. */
  21925. 'text': textInputType,
  21926. /**
  21927. * @ngdoc input
  21928. * @name input[date]
  21929. *
  21930. * @description
  21931. * Input with date validation and transformation. In browsers that do not yet support
  21932. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21933. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21934. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21935. * expected input format via a placeholder or label.
  21936. *
  21937. * The model must always be a Date object, otherwise AngularJS will throw an error.
  21938. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21939. *
  21940. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21941. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21942. *
  21943. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  21944. * @param {string=} name Property name of the form under which the control is published.
  21945. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21946. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21947. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21948. * constraint validation.
  21949. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21950. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21951. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21952. * constraint validation.
  21953. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21954. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21955. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21956. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21957. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21958. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21959. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21960. * `required` when you want to data-bind to the `required` attribute.
  21961. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  21962. * interaction with the input element.
  21963. *
  21964. * @example
  21965. <example name="date-input-directive" module="dateInputExample">
  21966. <file name="index.html">
  21967. <script>
  21968. angular.module('dateInputExample', [])
  21969. .controller('DateController', ['$scope', function($scope) {
  21970. $scope.example = {
  21971. value: new Date(2013, 9, 22)
  21972. };
  21973. }]);
  21974. </script>
  21975. <form name="myForm" ng-controller="DateController as dateCtrl">
  21976. <label for="exampleInput">Pick a date in 2013:</label>
  21977. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21978. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21979. <div role="alert">
  21980. <span class="error" ng-show="myForm.input.$error.required">
  21981. Required!</span>
  21982. <span class="error" ng-show="myForm.input.$error.date">
  21983. Not a valid date!</span>
  21984. </div>
  21985. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21986. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21987. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21988. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21989. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21990. </form>
  21991. </file>
  21992. <file name="protractor.js" type="protractor">
  21993. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21994. var valid = element(by.binding('myForm.input.$valid'));
  21995. // currently protractor/webdriver does not support
  21996. // sending keys to all known HTML5 input controls
  21997. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21998. function setInput(val) {
  21999. // set the value of the element and force validation.
  22000. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22001. "ipt.value = '" + val + "';" +
  22002. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22003. browser.executeScript(scr);
  22004. }
  22005. it('should initialize to model', function() {
  22006. expect(value.getText()).toContain('2013-10-22');
  22007. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22008. });
  22009. it('should be invalid if empty', function() {
  22010. setInput('');
  22011. expect(value.getText()).toEqual('value =');
  22012. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22013. });
  22014. it('should be invalid if over max', function() {
  22015. setInput('2015-01-01');
  22016. expect(value.getText()).toContain('');
  22017. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22018. });
  22019. </file>
  22020. </example>
  22021. */
  22022. 'date': createDateInputType('date', DATE_REGEXP,
  22023. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  22024. 'yyyy-MM-dd'),
  22025. /**
  22026. * @ngdoc input
  22027. * @name input[datetime-local]
  22028. *
  22029. * @description
  22030. * Input with datetime validation and transformation. In browsers that do not yet support
  22031. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22032. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  22033. *
  22034. * The model must always be a Date object, otherwise AngularJS will throw an error.
  22035. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22036. *
  22037. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22038. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22039. *
  22040. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22041. * @param {string=} name Property name of the form under which the control is published.
  22042. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22043. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  22044. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  22045. * Note that `min` will also add native HTML5 constraint validation.
  22046. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22047. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  22048. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  22049. * Note that `max` will also add native HTML5 constraint validation.
  22050. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  22051. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22052. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  22053. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22054. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22055. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22056. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22057. * `required` when you want to data-bind to the `required` attribute.
  22058. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22059. * interaction with the input element.
  22060. *
  22061. * @example
  22062. <example name="datetimelocal-input-directive" module="dateExample">
  22063. <file name="index.html">
  22064. <script>
  22065. angular.module('dateExample', [])
  22066. .controller('DateController', ['$scope', function($scope) {
  22067. $scope.example = {
  22068. value: new Date(2010, 11, 28, 14, 57)
  22069. };
  22070. }]);
  22071. </script>
  22072. <form name="myForm" ng-controller="DateController as dateCtrl">
  22073. <label for="exampleInput">Pick a date between in 2013:</label>
  22074. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  22075. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  22076. <div role="alert">
  22077. <span class="error" ng-show="myForm.input.$error.required">
  22078. Required!</span>
  22079. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  22080. Not a valid date!</span>
  22081. </div>
  22082. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  22083. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22084. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22085. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22086. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22087. </form>
  22088. </file>
  22089. <file name="protractor.js" type="protractor">
  22090. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  22091. var valid = element(by.binding('myForm.input.$valid'));
  22092. // currently protractor/webdriver does not support
  22093. // sending keys to all known HTML5 input controls
  22094. // for various browsers (https://github.com/angular/protractor/issues/562).
  22095. function setInput(val) {
  22096. // set the value of the element and force validation.
  22097. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22098. "ipt.value = '" + val + "';" +
  22099. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22100. browser.executeScript(scr);
  22101. }
  22102. it('should initialize to model', function() {
  22103. expect(value.getText()).toContain('2010-12-28T14:57:00');
  22104. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22105. });
  22106. it('should be invalid if empty', function() {
  22107. setInput('');
  22108. expect(value.getText()).toEqual('value =');
  22109. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22110. });
  22111. it('should be invalid if over max', function() {
  22112. setInput('2015-01-01T23:59:00');
  22113. expect(value.getText()).toContain('');
  22114. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22115. });
  22116. </file>
  22117. </example>
  22118. */
  22119. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  22120. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  22121. 'yyyy-MM-ddTHH:mm:ss.sss'),
  22122. /**
  22123. * @ngdoc input
  22124. * @name input[time]
  22125. *
  22126. * @description
  22127. * Input with time validation and transformation. In browsers that do not yet support
  22128. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22129. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  22130. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  22131. *
  22132. * The model must always be a Date object, otherwise AngularJS will throw an error.
  22133. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22134. *
  22135. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22136. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22137. *
  22138. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22139. * @param {string=} name Property name of the form under which the control is published.
  22140. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22141. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22142. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  22143. * native HTML5 constraint validation.
  22144. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22145. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22146. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  22147. * native HTML5 constraint validation.
  22148. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  22149. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22150. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  22151. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22152. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22153. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22154. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22155. * `required` when you want to data-bind to the `required` attribute.
  22156. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22157. * interaction with the input element.
  22158. *
  22159. * @example
  22160. <example name="time-input-directive" module="timeExample">
  22161. <file name="index.html">
  22162. <script>
  22163. angular.module('timeExample', [])
  22164. .controller('DateController', ['$scope', function($scope) {
  22165. $scope.example = {
  22166. value: new Date(1970, 0, 1, 14, 57, 0)
  22167. };
  22168. }]);
  22169. </script>
  22170. <form name="myForm" ng-controller="DateController as dateCtrl">
  22171. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  22172. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  22173. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  22174. <div role="alert">
  22175. <span class="error" ng-show="myForm.input.$error.required">
  22176. Required!</span>
  22177. <span class="error" ng-show="myForm.input.$error.time">
  22178. Not a valid date!</span>
  22179. </div>
  22180. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  22181. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22182. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22183. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22184. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22185. </form>
  22186. </file>
  22187. <file name="protractor.js" type="protractor">
  22188. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  22189. var valid = element(by.binding('myForm.input.$valid'));
  22190. // currently protractor/webdriver does not support
  22191. // sending keys to all known HTML5 input controls
  22192. // for various browsers (https://github.com/angular/protractor/issues/562).
  22193. function setInput(val) {
  22194. // set the value of the element and force validation.
  22195. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22196. "ipt.value = '" + val + "';" +
  22197. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22198. browser.executeScript(scr);
  22199. }
  22200. it('should initialize to model', function() {
  22201. expect(value.getText()).toContain('14:57:00');
  22202. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22203. });
  22204. it('should be invalid if empty', function() {
  22205. setInput('');
  22206. expect(value.getText()).toEqual('value =');
  22207. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22208. });
  22209. it('should be invalid if over max', function() {
  22210. setInput('23:59:00');
  22211. expect(value.getText()).toContain('');
  22212. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22213. });
  22214. </file>
  22215. </example>
  22216. */
  22217. 'time': createDateInputType('time', TIME_REGEXP,
  22218. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  22219. 'HH:mm:ss.sss'),
  22220. /**
  22221. * @ngdoc input
  22222. * @name input[week]
  22223. *
  22224. * @description
  22225. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  22226. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22227. * week format (yyyy-W##), for example: `2013-W02`.
  22228. *
  22229. * The model must always be a Date object, otherwise AngularJS will throw an error.
  22230. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22231. *
  22232. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22233. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22234. *
  22235. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22236. * @param {string=} name Property name of the form under which the control is published.
  22237. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22238. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22239. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  22240. * native HTML5 constraint validation.
  22241. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22242. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22243. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  22244. * native HTML5 constraint validation.
  22245. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22246. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22247. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22248. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22249. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22250. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22251. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22252. * `required` when you want to data-bind to the `required` attribute.
  22253. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22254. * interaction with the input element.
  22255. *
  22256. * @example
  22257. <example name="week-input-directive" module="weekExample">
  22258. <file name="index.html">
  22259. <script>
  22260. angular.module('weekExample', [])
  22261. .controller('DateController', ['$scope', function($scope) {
  22262. $scope.example = {
  22263. value: new Date(2013, 0, 3)
  22264. };
  22265. }]);
  22266. </script>
  22267. <form name="myForm" ng-controller="DateController as dateCtrl">
  22268. <label>Pick a date between in 2013:
  22269. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  22270. placeholder="YYYY-W##" min="2012-W32"
  22271. max="2013-W52" required />
  22272. </label>
  22273. <div role="alert">
  22274. <span class="error" ng-show="myForm.input.$error.required">
  22275. Required!</span>
  22276. <span class="error" ng-show="myForm.input.$error.week">
  22277. Not a valid date!</span>
  22278. </div>
  22279. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  22280. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22281. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22282. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22283. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22284. </form>
  22285. </file>
  22286. <file name="protractor.js" type="protractor">
  22287. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  22288. var valid = element(by.binding('myForm.input.$valid'));
  22289. // currently protractor/webdriver does not support
  22290. // sending keys to all known HTML5 input controls
  22291. // for various browsers (https://github.com/angular/protractor/issues/562).
  22292. function setInput(val) {
  22293. // set the value of the element and force validation.
  22294. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22295. "ipt.value = '" + val + "';" +
  22296. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22297. browser.executeScript(scr);
  22298. }
  22299. it('should initialize to model', function() {
  22300. expect(value.getText()).toContain('2013-W01');
  22301. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22302. });
  22303. it('should be invalid if empty', function() {
  22304. setInput('');
  22305. expect(value.getText()).toEqual('value =');
  22306. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22307. });
  22308. it('should be invalid if over max', function() {
  22309. setInput('2015-W01');
  22310. expect(value.getText()).toContain('');
  22311. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22312. });
  22313. </file>
  22314. </example>
  22315. */
  22316. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  22317. /**
  22318. * @ngdoc input
  22319. * @name input[month]
  22320. *
  22321. * @description
  22322. * Input with month validation and transformation. In browsers that do not yet support
  22323. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22324. * month format (yyyy-MM), for example: `2009-01`.
  22325. *
  22326. * The model must always be a Date object, otherwise AngularJS will throw an error.
  22327. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22328. * If the model is not set to the first of the month, the next view to model update will set it
  22329. * to the first of the month.
  22330. *
  22331. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22332. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22333. *
  22334. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22335. * @param {string=} name Property name of the form under which the control is published.
  22336. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22337. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22338. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  22339. * native HTML5 constraint validation.
  22340. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22341. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22342. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  22343. * native HTML5 constraint validation.
  22344. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22345. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22346. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22347. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22348. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22349. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22350. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22351. * `required` when you want to data-bind to the `required` attribute.
  22352. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22353. * interaction with the input element.
  22354. *
  22355. * @example
  22356. <example name="month-input-directive" module="monthExample">
  22357. <file name="index.html">
  22358. <script>
  22359. angular.module('monthExample', [])
  22360. .controller('DateController', ['$scope', function($scope) {
  22361. $scope.example = {
  22362. value: new Date(2013, 9, 1)
  22363. };
  22364. }]);
  22365. </script>
  22366. <form name="myForm" ng-controller="DateController as dateCtrl">
  22367. <label for="exampleInput">Pick a month in 2013:</label>
  22368. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  22369. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  22370. <div role="alert">
  22371. <span class="error" ng-show="myForm.input.$error.required">
  22372. Required!</span>
  22373. <span class="error" ng-show="myForm.input.$error.month">
  22374. Not a valid month!</span>
  22375. </div>
  22376. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  22377. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22378. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22379. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22380. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22381. </form>
  22382. </file>
  22383. <file name="protractor.js" type="protractor">
  22384. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  22385. var valid = element(by.binding('myForm.input.$valid'));
  22386. // currently protractor/webdriver does not support
  22387. // sending keys to all known HTML5 input controls
  22388. // for various browsers (https://github.com/angular/protractor/issues/562).
  22389. function setInput(val) {
  22390. // set the value of the element and force validation.
  22391. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22392. "ipt.value = '" + val + "';" +
  22393. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22394. browser.executeScript(scr);
  22395. }
  22396. it('should initialize to model', function() {
  22397. expect(value.getText()).toContain('2013-10');
  22398. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22399. });
  22400. it('should be invalid if empty', function() {
  22401. setInput('');
  22402. expect(value.getText()).toEqual('value =');
  22403. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22404. });
  22405. it('should be invalid if over max', function() {
  22406. setInput('2015-01');
  22407. expect(value.getText()).toContain('');
  22408. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22409. });
  22410. </file>
  22411. </example>
  22412. */
  22413. 'month': createDateInputType('month', MONTH_REGEXP,
  22414. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  22415. 'yyyy-MM'),
  22416. /**
  22417. * @ngdoc input
  22418. * @name input[number]
  22419. *
  22420. * @description
  22421. * Text input with number validation and transformation. Sets the `number` validation
  22422. * error if not a valid number.
  22423. *
  22424. * <div class="alert alert-warning">
  22425. * The model must always be of type `number` otherwise AngularJS will throw an error.
  22426. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  22427. * error docs for more information and an example of how to convert your model if necessary.
  22428. * </div>
  22429. *
  22430. * ## Issues with HTML5 constraint validation
  22431. *
  22432. * In browsers that follow the
  22433. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  22434. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  22435. * If a non-number is entered in the input, the browser will report the value as an empty string,
  22436. * which means the view / model values in `ngModel` and subsequently the scope value
  22437. * will also be an empty string.
  22438. *
  22439. *
  22440. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22441. * @param {string=} name Property name of the form under which the control is published.
  22442. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22443. * Can be interpolated.
  22444. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22445. * Can be interpolated.
  22446. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  22447. * but does not trigger HTML5 native validation. Takes an expression.
  22448. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  22449. * but does not trigger HTML5 native validation. Takes an expression.
  22450. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  22451. * Can be interpolated.
  22452. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  22453. * but does not trigger HTML5 native validation. Takes an expression.
  22454. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22455. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22456. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22457. * `required` when you want to data-bind to the `required` attribute.
  22458. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22459. * minlength.
  22460. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22461. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22462. * any length.
  22463. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22464. * that contains the regular expression body that will be converted to a regular expression
  22465. * as in the ngPattern directive.
  22466. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22467. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  22468. * If the expression evaluates to a RegExp object, then this is used directly.
  22469. * If the expression evaluates to a string, then it will be converted to a RegExp
  22470. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22471. * `new RegExp('^abc$')`.<br />
  22472. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22473. * start at the index of the last search's match, thus not taking the whole input value into
  22474. * account.
  22475. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22476. * interaction with the input element.
  22477. *
  22478. * @example
  22479. <example name="number-input-directive" module="numberExample">
  22480. <file name="index.html">
  22481. <script>
  22482. angular.module('numberExample', [])
  22483. .controller('ExampleController', ['$scope', function($scope) {
  22484. $scope.example = {
  22485. value: 12
  22486. };
  22487. }]);
  22488. </script>
  22489. <form name="myForm" ng-controller="ExampleController">
  22490. <label>Number:
  22491. <input type="number" name="input" ng-model="example.value"
  22492. min="0" max="99" required>
  22493. </label>
  22494. <div role="alert">
  22495. <span class="error" ng-show="myForm.input.$error.required">
  22496. Required!</span>
  22497. <span class="error" ng-show="myForm.input.$error.number">
  22498. Not valid number!</span>
  22499. </div>
  22500. <tt>value = {{example.value}}</tt><br/>
  22501. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22502. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22503. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22504. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22505. </form>
  22506. </file>
  22507. <file name="protractor.js" type="protractor">
  22508. var value = element(by.binding('example.value'));
  22509. var valid = element(by.binding('myForm.input.$valid'));
  22510. var input = element(by.model('example.value'));
  22511. it('should initialize to model', function() {
  22512. expect(value.getText()).toContain('12');
  22513. expect(valid.getText()).toContain('true');
  22514. });
  22515. it('should be invalid if empty', function() {
  22516. input.clear();
  22517. input.sendKeys('');
  22518. expect(value.getText()).toEqual('value =');
  22519. expect(valid.getText()).toContain('false');
  22520. });
  22521. it('should be invalid if over max', function() {
  22522. input.clear();
  22523. input.sendKeys('123');
  22524. expect(value.getText()).toEqual('value =');
  22525. expect(valid.getText()).toContain('false');
  22526. });
  22527. </file>
  22528. </example>
  22529. */
  22530. 'number': numberInputType,
  22531. /**
  22532. * @ngdoc input
  22533. * @name input[url]
  22534. *
  22535. * @description
  22536. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  22537. * valid URL.
  22538. *
  22539. * <div class="alert alert-warning">
  22540. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  22541. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  22542. * the built-in validators (see the {@link guide/forms Forms guide})
  22543. * </div>
  22544. *
  22545. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22546. * @param {string=} name Property name of the form under which the control is published.
  22547. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22548. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22549. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22550. * `required` when you want to data-bind to the `required` attribute.
  22551. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22552. * minlength.
  22553. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22554. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22555. * any length.
  22556. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22557. * that contains the regular expression body that will be converted to a regular expression
  22558. * as in the ngPattern directive.
  22559. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22560. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  22561. * If the expression evaluates to a RegExp object, then this is used directly.
  22562. * If the expression evaluates to a string, then it will be converted to a RegExp
  22563. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22564. * `new RegExp('^abc$')`.<br />
  22565. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22566. * start at the index of the last search's match, thus not taking the whole input value into
  22567. * account.
  22568. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22569. * interaction with the input element.
  22570. *
  22571. * @example
  22572. <example name="url-input-directive" module="urlExample">
  22573. <file name="index.html">
  22574. <script>
  22575. angular.module('urlExample', [])
  22576. .controller('ExampleController', ['$scope', function($scope) {
  22577. $scope.url = {
  22578. text: 'http://google.com'
  22579. };
  22580. }]);
  22581. </script>
  22582. <form name="myForm" ng-controller="ExampleController">
  22583. <label>URL:
  22584. <input type="url" name="input" ng-model="url.text" required>
  22585. <label>
  22586. <div role="alert">
  22587. <span class="error" ng-show="myForm.input.$error.required">
  22588. Required!</span>
  22589. <span class="error" ng-show="myForm.input.$error.url">
  22590. Not valid url!</span>
  22591. </div>
  22592. <tt>text = {{url.text}}</tt><br/>
  22593. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22594. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22595. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22596. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22597. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  22598. </form>
  22599. </file>
  22600. <file name="protractor.js" type="protractor">
  22601. var text = element(by.binding('url.text'));
  22602. var valid = element(by.binding('myForm.input.$valid'));
  22603. var input = element(by.model('url.text'));
  22604. it('should initialize to model', function() {
  22605. expect(text.getText()).toContain('http://google.com');
  22606. expect(valid.getText()).toContain('true');
  22607. });
  22608. it('should be invalid if empty', function() {
  22609. input.clear();
  22610. input.sendKeys('');
  22611. expect(text.getText()).toEqual('text =');
  22612. expect(valid.getText()).toContain('false');
  22613. });
  22614. it('should be invalid if not url', function() {
  22615. input.clear();
  22616. input.sendKeys('box');
  22617. expect(valid.getText()).toContain('false');
  22618. });
  22619. </file>
  22620. </example>
  22621. */
  22622. 'url': urlInputType,
  22623. /**
  22624. * @ngdoc input
  22625. * @name input[email]
  22626. *
  22627. * @description
  22628. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22629. * address.
  22630. *
  22631. * <div class="alert alert-warning">
  22632. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22633. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22634. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22635. * </div>
  22636. *
  22637. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22638. * @param {string=} name Property name of the form under which the control is published.
  22639. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22640. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22641. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22642. * `required` when you want to data-bind to the `required` attribute.
  22643. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22644. * minlength.
  22645. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22646. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22647. * any length.
  22648. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22649. * that contains the regular expression body that will be converted to a regular expression
  22650. * as in the ngPattern directive.
  22651. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22652. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  22653. * If the expression evaluates to a RegExp object, then this is used directly.
  22654. * If the expression evaluates to a string, then it will be converted to a RegExp
  22655. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22656. * `new RegExp('^abc$')`.<br />
  22657. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22658. * start at the index of the last search's match, thus not taking the whole input value into
  22659. * account.
  22660. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22661. * interaction with the input element.
  22662. *
  22663. * @example
  22664. <example name="email-input-directive" module="emailExample">
  22665. <file name="index.html">
  22666. <script>
  22667. angular.module('emailExample', [])
  22668. .controller('ExampleController', ['$scope', function($scope) {
  22669. $scope.email = {
  22670. text: 'me@example.com'
  22671. };
  22672. }]);
  22673. </script>
  22674. <form name="myForm" ng-controller="ExampleController">
  22675. <label>Email:
  22676. <input type="email" name="input" ng-model="email.text" required>
  22677. </label>
  22678. <div role="alert">
  22679. <span class="error" ng-show="myForm.input.$error.required">
  22680. Required!</span>
  22681. <span class="error" ng-show="myForm.input.$error.email">
  22682. Not valid email!</span>
  22683. </div>
  22684. <tt>text = {{email.text}}</tt><br/>
  22685. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22686. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22687. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22688. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22689. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22690. </form>
  22691. </file>
  22692. <file name="protractor.js" type="protractor">
  22693. var text = element(by.binding('email.text'));
  22694. var valid = element(by.binding('myForm.input.$valid'));
  22695. var input = element(by.model('email.text'));
  22696. it('should initialize to model', function() {
  22697. expect(text.getText()).toContain('me@example.com');
  22698. expect(valid.getText()).toContain('true');
  22699. });
  22700. it('should be invalid if empty', function() {
  22701. input.clear();
  22702. input.sendKeys('');
  22703. expect(text.getText()).toEqual('text =');
  22704. expect(valid.getText()).toContain('false');
  22705. });
  22706. it('should be invalid if not email', function() {
  22707. input.clear();
  22708. input.sendKeys('xxx');
  22709. expect(valid.getText()).toContain('false');
  22710. });
  22711. </file>
  22712. </example>
  22713. */
  22714. 'email': emailInputType,
  22715. /**
  22716. * @ngdoc input
  22717. * @name input[radio]
  22718. *
  22719. * @description
  22720. * HTML radio button.
  22721. *
  22722. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22723. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22724. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22725. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22726. * @param {string=} name Property name of the form under which the control is published.
  22727. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22728. * interaction with the input element.
  22729. * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio
  22730. * is selected. Should be used instead of the `value` attribute if you need
  22731. * a non-string `ngModel` (`boolean`, `array`, ...).
  22732. *
  22733. * @example
  22734. <example name="radio-input-directive" module="radioExample">
  22735. <file name="index.html">
  22736. <script>
  22737. angular.module('radioExample', [])
  22738. .controller('ExampleController', ['$scope', function($scope) {
  22739. $scope.color = {
  22740. name: 'blue'
  22741. };
  22742. $scope.specialValue = {
  22743. "id": "12345",
  22744. "value": "green"
  22745. };
  22746. }]);
  22747. </script>
  22748. <form name="myForm" ng-controller="ExampleController">
  22749. <label>
  22750. <input type="radio" ng-model="color.name" value="red">
  22751. Red
  22752. </label><br/>
  22753. <label>
  22754. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22755. Green
  22756. </label><br/>
  22757. <label>
  22758. <input type="radio" ng-model="color.name" value="blue">
  22759. Blue
  22760. </label><br/>
  22761. <tt>color = {{color.name | json}}</tt><br/>
  22762. </form>
  22763. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22764. </file>
  22765. <file name="protractor.js" type="protractor">
  22766. it('should change state', function() {
  22767. var inputs = element.all(by.model('color.name'));
  22768. var color = element(by.binding('color.name'));
  22769. expect(color.getText()).toContain('blue');
  22770. inputs.get(0).click();
  22771. expect(color.getText()).toContain('red');
  22772. inputs.get(1).click();
  22773. expect(color.getText()).toContain('green');
  22774. });
  22775. </file>
  22776. </example>
  22777. */
  22778. 'radio': radioInputType,
  22779. /**
  22780. * @ngdoc input
  22781. * @name input[range]
  22782. *
  22783. * @description
  22784. * Native range input with validation and transformation.
  22785. *
  22786. * The model for the range input must always be a `Number`.
  22787. *
  22788. * IE9 and other browsers that do not support the `range` type fall back
  22789. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22790. * validation and number parsing are nevertheless supported.
  22791. *
  22792. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22793. * in a way that never allows the input to hold an invalid value. That means:
  22794. * - any non-numerical value is set to `(max + min) / 2`.
  22795. * - any numerical value that is less than the current min val, or greater than the current max val
  22796. * is set to the min / max val respectively.
  22797. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22798. * is used.
  22799. *
  22800. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22801. * for more info.
  22802. *
  22803. * This has the following consequences for AngularJS:
  22804. *
  22805. * Since the element value should always reflect the current model value, a range input
  22806. * will set the bound ngModel expression to the value that the browser has set for the
  22807. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22808. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22809. * AngularJS will then set the model to `50`, to prevent input and model value being out of sync.
  22810. *
  22811. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22812. * initialized. It also means a range input can never have the required error.
  22813. *
  22814. * This does not only affect changes to the model value, but also to the values of the `min`,
  22815. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22816. * the input value, AngularJS will also update the model value.
  22817. *
  22818. * Automatic value adjustment also means that a range input element can never have the `required`,
  22819. * `min`, or `max` errors.
  22820. *
  22821. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22822. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22823. * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step`
  22824. * error on the input, and set the model to `undefined`.
  22825. *
  22826. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22827. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22828. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22829. *
  22830. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22831. * @param {string=} name Property name of the form under which the control is published.
  22832. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22833. * than `min`. Can be interpolated.
  22834. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22835. * Can be interpolated.
  22836. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22837. * Can be interpolated.
  22838. * @param {string=} ngChange AngularJS expression to be executed when the ngModel value changes due
  22839. * to user interaction with the input element.
  22840. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22841. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22842. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22843. *
  22844. * @example
  22845. <example name="range-input-directive" module="rangeExample">
  22846. <file name="index.html">
  22847. <script>
  22848. angular.module('rangeExample', [])
  22849. .controller('ExampleController', ['$scope', function($scope) {
  22850. $scope.value = 75;
  22851. $scope.min = 10;
  22852. $scope.max = 90;
  22853. }]);
  22854. </script>
  22855. <form name="myForm" ng-controller="ExampleController">
  22856. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22857. <hr>
  22858. Model as number: <input type="number" ng-model="value"><br>
  22859. Min: <input type="number" ng-model="min"><br>
  22860. Max: <input type="number" ng-model="max"><br>
  22861. value = <code>{{value}}</code><br/>
  22862. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22863. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22864. </form>
  22865. </file>
  22866. </example>
  22867. * ## Range Input with ngMin & ngMax attributes
  22868. * @example
  22869. <example name="range-input-directive-ng" module="rangeExample">
  22870. <file name="index.html">
  22871. <script>
  22872. angular.module('rangeExample', [])
  22873. .controller('ExampleController', ['$scope', function($scope) {
  22874. $scope.value = 75;
  22875. $scope.min = 10;
  22876. $scope.max = 90;
  22877. }]);
  22878. </script>
  22879. <form name="myForm" ng-controller="ExampleController">
  22880. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22881. <hr>
  22882. Model as number: <input type="number" ng-model="value"><br>
  22883. Min: <input type="number" ng-model="min"><br>
  22884. Max: <input type="number" ng-model="max"><br>
  22885. value = <code>{{value}}</code><br/>
  22886. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22887. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22888. </form>
  22889. </file>
  22890. </example>
  22891. */
  22892. 'range': rangeInputType,
  22893. /**
  22894. * @ngdoc input
  22895. * @name input[checkbox]
  22896. *
  22897. * @description
  22898. * HTML checkbox.
  22899. *
  22900. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22901. * @param {string=} name Property name of the form under which the control is published.
  22902. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22903. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22904. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22905. * interaction with the input element.
  22906. *
  22907. * @example
  22908. <example name="checkbox-input-directive" module="checkboxExample">
  22909. <file name="index.html">
  22910. <script>
  22911. angular.module('checkboxExample', [])
  22912. .controller('ExampleController', ['$scope', function($scope) {
  22913. $scope.checkboxModel = {
  22914. value1 : true,
  22915. value2 : 'YES'
  22916. };
  22917. }]);
  22918. </script>
  22919. <form name="myForm" ng-controller="ExampleController">
  22920. <label>Value1:
  22921. <input type="checkbox" ng-model="checkboxModel.value1">
  22922. </label><br/>
  22923. <label>Value2:
  22924. <input type="checkbox" ng-model="checkboxModel.value2"
  22925. ng-true-value="'YES'" ng-false-value="'NO'">
  22926. </label><br/>
  22927. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22928. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22929. </form>
  22930. </file>
  22931. <file name="protractor.js" type="protractor">
  22932. it('should change state', function() {
  22933. var value1 = element(by.binding('checkboxModel.value1'));
  22934. var value2 = element(by.binding('checkboxModel.value2'));
  22935. expect(value1.getText()).toContain('true');
  22936. expect(value2.getText()).toContain('YES');
  22937. element(by.model('checkboxModel.value1')).click();
  22938. element(by.model('checkboxModel.value2')).click();
  22939. expect(value1.getText()).toContain('false');
  22940. expect(value2.getText()).toContain('NO');
  22941. });
  22942. </file>
  22943. </example>
  22944. */
  22945. 'checkbox': checkboxInputType,
  22946. 'hidden': noop,
  22947. 'button': noop,
  22948. 'submit': noop,
  22949. 'reset': noop,
  22950. 'file': noop
  22951. };
  22952. function stringBasedInputType(ctrl) {
  22953. ctrl.$formatters.push(function(value) {
  22954. return ctrl.$isEmpty(value) ? value : value.toString();
  22955. });
  22956. }
  22957. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22958. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22959. stringBasedInputType(ctrl);
  22960. }
  22961. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22962. var type = lowercase(element[0].type);
  22963. // In composition mode, users are still inputting intermediate text buffer,
  22964. // hold the listener until composition is done.
  22965. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22966. if (!$sniffer.android) {
  22967. var composing = false;
  22968. element.on('compositionstart', function() {
  22969. composing = true;
  22970. });
  22971. element.on('compositionend', function() {
  22972. composing = false;
  22973. listener();
  22974. });
  22975. }
  22976. var timeout;
  22977. var listener = function(ev) {
  22978. if (timeout) {
  22979. $browser.defer.cancel(timeout);
  22980. timeout = null;
  22981. }
  22982. if (composing) return;
  22983. var value = element.val(),
  22984. event = ev && ev.type;
  22985. // By default we will trim the value
  22986. // If the attribute ng-trim exists we will avoid trimming
  22987. // If input type is 'password', the value is never trimmed
  22988. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22989. value = trim(value);
  22990. }
  22991. // If a control is suffering from bad input (due to native validators), browsers discard its
  22992. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22993. // control's value is the same empty value twice in a row.
  22994. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22995. ctrl.$setViewValue(value, event);
  22996. }
  22997. };
  22998. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22999. // input event on backspace, delete or cut
  23000. if ($sniffer.hasEvent('input')) {
  23001. element.on('input', listener);
  23002. } else {
  23003. var deferListener = function(ev, input, origValue) {
  23004. if (!timeout) {
  23005. timeout = $browser.defer(function() {
  23006. timeout = null;
  23007. if (!input || input.value !== origValue) {
  23008. listener(ev);
  23009. }
  23010. });
  23011. }
  23012. };
  23013. element.on('keydown', /** @this */ function(event) {
  23014. var key = event.keyCode;
  23015. // ignore
  23016. // command modifiers arrows
  23017. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  23018. deferListener(event, this, this.value);
  23019. });
  23020. // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it
  23021. if ($sniffer.hasEvent('paste')) {
  23022. element.on('paste cut drop', deferListener);
  23023. }
  23024. }
  23025. // if user paste into input using mouse on older browser
  23026. // or form autocomplete on newer browser, we need "change" event to catch it
  23027. element.on('change', listener);
  23028. // Some native input types (date-family) have the ability to change validity without
  23029. // firing any input/change events.
  23030. // For these event types, when native validators are present and the browser supports the type,
  23031. // check for validity changes on various DOM events.
  23032. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  23033. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  23034. if (!timeout) {
  23035. var validity = this[VALIDITY_STATE_PROPERTY];
  23036. var origBadInput = validity.badInput;
  23037. var origTypeMismatch = validity.typeMismatch;
  23038. timeout = $browser.defer(function() {
  23039. timeout = null;
  23040. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  23041. listener(ev);
  23042. }
  23043. });
  23044. }
  23045. });
  23046. }
  23047. ctrl.$render = function() {
  23048. // Workaround for Firefox validation #12102.
  23049. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  23050. if (element.val() !== value) {
  23051. element.val(value);
  23052. }
  23053. };
  23054. }
  23055. function weekParser(isoWeek, existingDate) {
  23056. if (isDate(isoWeek)) {
  23057. return isoWeek;
  23058. }
  23059. if (isString(isoWeek)) {
  23060. WEEK_REGEXP.lastIndex = 0;
  23061. var parts = WEEK_REGEXP.exec(isoWeek);
  23062. if (parts) {
  23063. var year = +parts[1],
  23064. week = +parts[2],
  23065. hours = 0,
  23066. minutes = 0,
  23067. seconds = 0,
  23068. milliseconds = 0,
  23069. firstThurs = getFirstThursdayOfYear(year),
  23070. addDays = (week - 1) * 7;
  23071. if (existingDate) {
  23072. hours = existingDate.getHours();
  23073. minutes = existingDate.getMinutes();
  23074. seconds = existingDate.getSeconds();
  23075. milliseconds = existingDate.getMilliseconds();
  23076. }
  23077. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  23078. }
  23079. }
  23080. return NaN;
  23081. }
  23082. function createDateParser(regexp, mapping) {
  23083. return function(iso, date) {
  23084. var parts, map;
  23085. if (isDate(iso)) {
  23086. return iso;
  23087. }
  23088. if (isString(iso)) {
  23089. // When a date is JSON'ified to wraps itself inside of an extra
  23090. // set of double quotes. This makes the date parsing code unable
  23091. // to match the date string and parse it as a date.
  23092. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  23093. iso = iso.substring(1, iso.length - 1);
  23094. }
  23095. if (ISO_DATE_REGEXP.test(iso)) {
  23096. return new Date(iso);
  23097. }
  23098. regexp.lastIndex = 0;
  23099. parts = regexp.exec(iso);
  23100. if (parts) {
  23101. parts.shift();
  23102. if (date) {
  23103. map = {
  23104. yyyy: date.getFullYear(),
  23105. MM: date.getMonth() + 1,
  23106. dd: date.getDate(),
  23107. HH: date.getHours(),
  23108. mm: date.getMinutes(),
  23109. ss: date.getSeconds(),
  23110. sss: date.getMilliseconds() / 1000
  23111. };
  23112. } else {
  23113. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  23114. }
  23115. forEach(parts, function(part, index) {
  23116. if (index < mapping.length) {
  23117. map[mapping[index]] = +part;
  23118. }
  23119. });
  23120. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  23121. }
  23122. }
  23123. return NaN;
  23124. };
  23125. }
  23126. function createDateInputType(type, regexp, parseDate, format) {
  23127. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  23128. badInputChecker(scope, element, attr, ctrl);
  23129. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23130. var timezone = ctrl && ctrl.$options.getOption('timezone');
  23131. var previousDate;
  23132. ctrl.$$parserName = type;
  23133. ctrl.$parsers.push(function(value) {
  23134. if (ctrl.$isEmpty(value)) return null;
  23135. if (regexp.test(value)) {
  23136. // Note: We cannot read ctrl.$modelValue, as there might be a different
  23137. // parser/formatter in the processing chain so that the model
  23138. // contains some different data format!
  23139. var parsedDate = parseDate(value, previousDate);
  23140. if (timezone) {
  23141. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  23142. }
  23143. return parsedDate;
  23144. }
  23145. return undefined;
  23146. });
  23147. ctrl.$formatters.push(function(value) {
  23148. if (value && !isDate(value)) {
  23149. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  23150. }
  23151. if (isValidDate(value)) {
  23152. previousDate = value;
  23153. if (previousDate && timezone) {
  23154. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  23155. }
  23156. return $filter('date')(value, format, timezone);
  23157. } else {
  23158. previousDate = null;
  23159. return '';
  23160. }
  23161. });
  23162. if (isDefined(attr.min) || attr.ngMin) {
  23163. var minVal;
  23164. ctrl.$validators.min = function(value) {
  23165. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  23166. };
  23167. attr.$observe('min', function(val) {
  23168. minVal = parseObservedDateValue(val);
  23169. ctrl.$validate();
  23170. });
  23171. }
  23172. if (isDefined(attr.max) || attr.ngMax) {
  23173. var maxVal;
  23174. ctrl.$validators.max = function(value) {
  23175. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  23176. };
  23177. attr.$observe('max', function(val) {
  23178. maxVal = parseObservedDateValue(val);
  23179. ctrl.$validate();
  23180. });
  23181. }
  23182. function isValidDate(value) {
  23183. // Invalid Date: getTime() returns NaN
  23184. return value && !(value.getTime && value.getTime() !== value.getTime());
  23185. }
  23186. function parseObservedDateValue(val) {
  23187. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  23188. }
  23189. };
  23190. }
  23191. function badInputChecker(scope, element, attr, ctrl) {
  23192. var node = element[0];
  23193. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  23194. if (nativeValidation) {
  23195. ctrl.$parsers.push(function(value) {
  23196. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  23197. return validity.badInput || validity.typeMismatch ? undefined : value;
  23198. });
  23199. }
  23200. }
  23201. function numberFormatterParser(ctrl) {
  23202. ctrl.$$parserName = 'number';
  23203. ctrl.$parsers.push(function(value) {
  23204. if (ctrl.$isEmpty(value)) return null;
  23205. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  23206. return undefined;
  23207. });
  23208. ctrl.$formatters.push(function(value) {
  23209. if (!ctrl.$isEmpty(value)) {
  23210. if (!isNumber(value)) {
  23211. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  23212. }
  23213. value = value.toString();
  23214. }
  23215. return value;
  23216. });
  23217. }
  23218. function parseNumberAttrVal(val) {
  23219. if (isDefined(val) && !isNumber(val)) {
  23220. val = parseFloat(val);
  23221. }
  23222. return !isNumberNaN(val) ? val : undefined;
  23223. }
  23224. function isNumberInteger(num) {
  23225. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  23226. // (minus the assumption that `num` is a number)
  23227. // eslint-disable-next-line no-bitwise
  23228. return (num | 0) === num;
  23229. }
  23230. function countDecimals(num) {
  23231. var numString = num.toString();
  23232. var decimalSymbolIndex = numString.indexOf('.');
  23233. if (decimalSymbolIndex === -1) {
  23234. if (-1 < num && num < 1) {
  23235. // It may be in the exponential notation format (`1e-X`)
  23236. var match = /e-(\d+)$/.exec(numString);
  23237. if (match) {
  23238. return Number(match[1]);
  23239. }
  23240. }
  23241. return 0;
  23242. }
  23243. return numString.length - decimalSymbolIndex - 1;
  23244. }
  23245. function isValidForStep(viewValue, stepBase, step) {
  23246. // At this point `stepBase` and `step` are expected to be non-NaN values
  23247. // and `viewValue` is expected to be a valid stringified number.
  23248. var value = Number(viewValue);
  23249. var isNonIntegerValue = !isNumberInteger(value);
  23250. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  23251. var isNonIntegerStep = !isNumberInteger(step);
  23252. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  23253. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  23254. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  23255. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  23256. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  23257. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  23258. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  23259. var multiplier = Math.pow(10, decimalCount);
  23260. value = value * multiplier;
  23261. stepBase = stepBase * multiplier;
  23262. step = step * multiplier;
  23263. if (isNonIntegerValue) value = Math.round(value);
  23264. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  23265. if (isNonIntegerStep) step = Math.round(step);
  23266. }
  23267. return (value - stepBase) % step === 0;
  23268. }
  23269. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23270. badInputChecker(scope, element, attr, ctrl);
  23271. numberFormatterParser(ctrl);
  23272. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23273. var minVal;
  23274. var maxVal;
  23275. if (isDefined(attr.min) || attr.ngMin) {
  23276. ctrl.$validators.min = function(value) {
  23277. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  23278. };
  23279. attr.$observe('min', function(val) {
  23280. minVal = parseNumberAttrVal(val);
  23281. // TODO(matsko): implement validateLater to reduce number of validations
  23282. ctrl.$validate();
  23283. });
  23284. }
  23285. if (isDefined(attr.max) || attr.ngMax) {
  23286. ctrl.$validators.max = function(value) {
  23287. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  23288. };
  23289. attr.$observe('max', function(val) {
  23290. maxVal = parseNumberAttrVal(val);
  23291. // TODO(matsko): implement validateLater to reduce number of validations
  23292. ctrl.$validate();
  23293. });
  23294. }
  23295. if (isDefined(attr.step) || attr.ngStep) {
  23296. var stepVal;
  23297. ctrl.$validators.step = function(modelValue, viewValue) {
  23298. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23299. isValidForStep(viewValue, minVal || 0, stepVal);
  23300. };
  23301. attr.$observe('step', function(val) {
  23302. stepVal = parseNumberAttrVal(val);
  23303. // TODO(matsko): implement validateLater to reduce number of validations
  23304. ctrl.$validate();
  23305. });
  23306. }
  23307. }
  23308. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23309. badInputChecker(scope, element, attr, ctrl);
  23310. numberFormatterParser(ctrl);
  23311. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23312. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  23313. minVal = supportsRange ? 0 : undefined,
  23314. maxVal = supportsRange ? 100 : undefined,
  23315. stepVal = supportsRange ? 1 : undefined,
  23316. validity = element[0].validity,
  23317. hasMinAttr = isDefined(attr.min),
  23318. hasMaxAttr = isDefined(attr.max),
  23319. hasStepAttr = isDefined(attr.step);
  23320. var originalRender = ctrl.$render;
  23321. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  23322. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  23323. //$render would cause the min / max validators to be applied with the wrong value
  23324. function rangeRender() {
  23325. originalRender();
  23326. ctrl.$setViewValue(element.val());
  23327. } :
  23328. originalRender;
  23329. if (hasMinAttr) {
  23330. ctrl.$validators.min = supportsRange ?
  23331. // Since all browsers set the input to a valid value, we don't need to check validity
  23332. function noopMinValidator() { return true; } :
  23333. // non-support browsers validate the min val
  23334. function minValidator(modelValue, viewValue) {
  23335. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  23336. };
  23337. setInitialValueAndObserver('min', minChange);
  23338. }
  23339. if (hasMaxAttr) {
  23340. ctrl.$validators.max = supportsRange ?
  23341. // Since all browsers set the input to a valid value, we don't need to check validity
  23342. function noopMaxValidator() { return true; } :
  23343. // non-support browsers validate the max val
  23344. function maxValidator(modelValue, viewValue) {
  23345. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  23346. };
  23347. setInitialValueAndObserver('max', maxChange);
  23348. }
  23349. if (hasStepAttr) {
  23350. ctrl.$validators.step = supportsRange ?
  23351. function nativeStepValidator() {
  23352. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  23353. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  23354. // validity error instead, so we can at least report an error in that case.
  23355. return !validity.stepMismatch;
  23356. } :
  23357. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  23358. function stepValidator(modelValue, viewValue) {
  23359. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23360. isValidForStep(viewValue, minVal || 0, stepVal);
  23361. };
  23362. setInitialValueAndObserver('step', stepChange);
  23363. }
  23364. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  23365. // interpolated attributes set the attribute value only after a digest, but we need the
  23366. // attribute value when the input is first rendered, so that the browser can adjust the
  23367. // input value based on the min/max value
  23368. element.attr(htmlAttrName, attr[htmlAttrName]);
  23369. attr.$observe(htmlAttrName, changeFn);
  23370. }
  23371. function minChange(val) {
  23372. minVal = parseNumberAttrVal(val);
  23373. // ignore changes before model is initialized
  23374. if (isNumberNaN(ctrl.$modelValue)) {
  23375. return;
  23376. }
  23377. if (supportsRange) {
  23378. var elVal = element.val();
  23379. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  23380. if (minVal > elVal) {
  23381. elVal = minVal;
  23382. element.val(elVal);
  23383. }
  23384. ctrl.$setViewValue(elVal);
  23385. } else {
  23386. // TODO(matsko): implement validateLater to reduce number of validations
  23387. ctrl.$validate();
  23388. }
  23389. }
  23390. function maxChange(val) {
  23391. maxVal = parseNumberAttrVal(val);
  23392. // ignore changes before model is initialized
  23393. if (isNumberNaN(ctrl.$modelValue)) {
  23394. return;
  23395. }
  23396. if (supportsRange) {
  23397. var elVal = element.val();
  23398. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  23399. if (maxVal < elVal) {
  23400. element.val(maxVal);
  23401. // IE11 and Chrome don't set the value to the minVal when max < min
  23402. elVal = maxVal < minVal ? minVal : maxVal;
  23403. }
  23404. ctrl.$setViewValue(elVal);
  23405. } else {
  23406. // TODO(matsko): implement validateLater to reduce number of validations
  23407. ctrl.$validate();
  23408. }
  23409. }
  23410. function stepChange(val) {
  23411. stepVal = parseNumberAttrVal(val);
  23412. // ignore changes before model is initialized
  23413. if (isNumberNaN(ctrl.$modelValue)) {
  23414. return;
  23415. }
  23416. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  23417. if (supportsRange && ctrl.$viewValue !== element.val()) {
  23418. ctrl.$setViewValue(element.val());
  23419. } else {
  23420. // TODO(matsko): implement validateLater to reduce number of validations
  23421. ctrl.$validate();
  23422. }
  23423. }
  23424. }
  23425. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23426. // Note: no badInputChecker here by purpose as `url` is only a validation
  23427. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23428. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23429. stringBasedInputType(ctrl);
  23430. ctrl.$$parserName = 'url';
  23431. ctrl.$validators.url = function(modelValue, viewValue) {
  23432. var value = modelValue || viewValue;
  23433. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  23434. };
  23435. }
  23436. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23437. // Note: no badInputChecker here by purpose as `url` is only a validation
  23438. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23439. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23440. stringBasedInputType(ctrl);
  23441. ctrl.$$parserName = 'email';
  23442. ctrl.$validators.email = function(modelValue, viewValue) {
  23443. var value = modelValue || viewValue;
  23444. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  23445. };
  23446. }
  23447. function radioInputType(scope, element, attr, ctrl) {
  23448. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  23449. // make the name unique, if not defined
  23450. if (isUndefined(attr.name)) {
  23451. element.attr('name', nextUid());
  23452. }
  23453. var listener = function(ev) {
  23454. var value;
  23455. if (element[0].checked) {
  23456. value = attr.value;
  23457. if (doTrim) {
  23458. value = trim(value);
  23459. }
  23460. ctrl.$setViewValue(value, ev && ev.type);
  23461. }
  23462. };
  23463. element.on('click', listener);
  23464. ctrl.$render = function() {
  23465. var value = attr.value;
  23466. if (doTrim) {
  23467. value = trim(value);
  23468. }
  23469. element[0].checked = (value === ctrl.$viewValue);
  23470. };
  23471. attr.$observe('value', ctrl.$render);
  23472. }
  23473. function parseConstantExpr($parse, context, name, expression, fallback) {
  23474. var parseFn;
  23475. if (isDefined(expression)) {
  23476. parseFn = $parse(expression);
  23477. if (!parseFn.constant) {
  23478. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  23479. '`{1}`.', name, expression);
  23480. }
  23481. return parseFn(context);
  23482. }
  23483. return fallback;
  23484. }
  23485. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  23486. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  23487. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  23488. var listener = function(ev) {
  23489. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  23490. };
  23491. element.on('click', listener);
  23492. ctrl.$render = function() {
  23493. element[0].checked = ctrl.$viewValue;
  23494. };
  23495. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  23496. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  23497. // it to a boolean.
  23498. ctrl.$isEmpty = function(value) {
  23499. return value === false;
  23500. };
  23501. ctrl.$formatters.push(function(value) {
  23502. return equals(value, trueValue);
  23503. });
  23504. ctrl.$parsers.push(function(value) {
  23505. return value ? trueValue : falseValue;
  23506. });
  23507. }
  23508. /**
  23509. * @ngdoc directive
  23510. * @name textarea
  23511. * @restrict E
  23512. *
  23513. * @description
  23514. * HTML textarea element control with AngularJS data-binding. The data-binding and validation
  23515. * properties of this element are exactly the same as those of the
  23516. * {@link ng.directive:input input element}.
  23517. *
  23518. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23519. * @param {string=} name Property name of the form under which the control is published.
  23520. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23521. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23522. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23523. * `required` when you want to data-bind to the `required` attribute.
  23524. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23525. * minlength.
  23526. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23527. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23528. * length.
  23529. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23530. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23531. * If the expression evaluates to a RegExp object, then this is used directly.
  23532. * If the expression evaluates to a string, then it will be converted to a RegExp
  23533. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23534. * `new RegExp('^abc$')`.<br />
  23535. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23536. * start at the index of the last search's match, thus not taking the whole input value into
  23537. * account.
  23538. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23539. * interaction with the input element.
  23540. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  23541. *
  23542. * @knownIssue
  23543. *
  23544. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  23545. * insert the placeholder value as the textarea's content. If the placeholder value contains
  23546. * interpolation (`{{ ... }}`), an error will be logged in the console when AngularJS tries to update
  23547. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  23548. * textarea, but can be undesirable.
  23549. *
  23550. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  23551. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  23552. * find more details on `ngAttr` in the
  23553. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  23554. * Developer Guide.
  23555. */
  23556. /**
  23557. * @ngdoc directive
  23558. * @name input
  23559. * @restrict E
  23560. *
  23561. * @description
  23562. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  23563. * input state control, and validation.
  23564. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  23565. *
  23566. * <div class="alert alert-warning">
  23567. * **Note:** Not every feature offered is available for all input types.
  23568. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  23569. * </div>
  23570. *
  23571. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23572. * @param {string=} name Property name of the form under which the control is published.
  23573. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23574. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  23575. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23576. * minlength.
  23577. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23578. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23579. * length.
  23580. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23581. * value does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23582. * If the expression evaluates to a RegExp object, then this is used directly.
  23583. * If the expression evaluates to a string, then it will be converted to a RegExp
  23584. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23585. * `new RegExp('^abc$')`.<br />
  23586. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23587. * start at the index of the last search's match, thus not taking the whole input value into
  23588. * account.
  23589. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23590. * interaction with the input element.
  23591. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  23592. * This parameter is ignored for input[type=password] controls, which will never trim the
  23593. * input.
  23594. *
  23595. * @example
  23596. <example name="input-directive" module="inputExample">
  23597. <file name="index.html">
  23598. <script>
  23599. angular.module('inputExample', [])
  23600. .controller('ExampleController', ['$scope', function($scope) {
  23601. $scope.user = {name: 'guest', last: 'visitor'};
  23602. }]);
  23603. </script>
  23604. <div ng-controller="ExampleController">
  23605. <form name="myForm">
  23606. <label>
  23607. User name:
  23608. <input type="text" name="userName" ng-model="user.name" required>
  23609. </label>
  23610. <div role="alert">
  23611. <span class="error" ng-show="myForm.userName.$error.required">
  23612. Required!</span>
  23613. </div>
  23614. <label>
  23615. Last name:
  23616. <input type="text" name="lastName" ng-model="user.last"
  23617. ng-minlength="3" ng-maxlength="10">
  23618. </label>
  23619. <div role="alert">
  23620. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23621. Too short!</span>
  23622. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23623. Too long!</span>
  23624. </div>
  23625. </form>
  23626. <hr>
  23627. <tt>user = {{user}}</tt><br/>
  23628. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23629. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23630. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23631. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23632. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23633. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23634. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23635. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23636. </div>
  23637. </file>
  23638. <file name="protractor.js" type="protractor">
  23639. var user = element(by.exactBinding('user'));
  23640. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23641. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23642. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23643. var formValid = element(by.binding('myForm.$valid'));
  23644. var userNameInput = element(by.model('user.name'));
  23645. var userLastInput = element(by.model('user.last'));
  23646. it('should initialize to model', function() {
  23647. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23648. expect(userNameValid.getText()).toContain('true');
  23649. expect(formValid.getText()).toContain('true');
  23650. });
  23651. it('should be invalid if empty when required', function() {
  23652. userNameInput.clear();
  23653. userNameInput.sendKeys('');
  23654. expect(user.getText()).toContain('{"last":"visitor"}');
  23655. expect(userNameValid.getText()).toContain('false');
  23656. expect(formValid.getText()).toContain('false');
  23657. });
  23658. it('should be valid if empty when min length is set', function() {
  23659. userLastInput.clear();
  23660. userLastInput.sendKeys('');
  23661. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23662. expect(lastNameValid.getText()).toContain('true');
  23663. expect(formValid.getText()).toContain('true');
  23664. });
  23665. it('should be invalid if less than required min length', function() {
  23666. userLastInput.clear();
  23667. userLastInput.sendKeys('xx');
  23668. expect(user.getText()).toContain('{"name":"guest"}');
  23669. expect(lastNameValid.getText()).toContain('false');
  23670. expect(lastNameError.getText()).toContain('minlength');
  23671. expect(formValid.getText()).toContain('false');
  23672. });
  23673. it('should be invalid if longer than max length', function() {
  23674. userLastInput.clear();
  23675. userLastInput.sendKeys('some ridiculously long name');
  23676. expect(user.getText()).toContain('{"name":"guest"}');
  23677. expect(lastNameValid.getText()).toContain('false');
  23678. expect(lastNameError.getText()).toContain('maxlength');
  23679. expect(formValid.getText()).toContain('false');
  23680. });
  23681. </file>
  23682. </example>
  23683. */
  23684. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23685. function($browser, $sniffer, $filter, $parse) {
  23686. return {
  23687. restrict: 'E',
  23688. require: ['?ngModel'],
  23689. link: {
  23690. pre: function(scope, element, attr, ctrls) {
  23691. if (ctrls[0]) {
  23692. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23693. $browser, $filter, $parse);
  23694. }
  23695. }
  23696. }
  23697. };
  23698. }];
  23699. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23700. /**
  23701. * @ngdoc directive
  23702. * @name ngValue
  23703. * @restrict A
  23704. * @priority 100
  23705. *
  23706. * @description
  23707. * Binds the given expression to the value of the element.
  23708. *
  23709. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23710. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23711. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23712. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23713. *
  23714. * It can also be used to achieve one-way binding of a given expression to an input element
  23715. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23716. *
  23717. * @element ANY
  23718. * @param {string=} ngValue AngularJS expression, whose value will be bound to the `value` attribute
  23719. * and `value` property of the element.
  23720. *
  23721. * @example
  23722. <example name="ngValue-directive" module="valueExample">
  23723. <file name="index.html">
  23724. <script>
  23725. angular.module('valueExample', [])
  23726. .controller('ExampleController', ['$scope', function($scope) {
  23727. $scope.names = ['pizza', 'unicorns', 'robots'];
  23728. $scope.my = { favorite: 'unicorns' };
  23729. }]);
  23730. </script>
  23731. <form ng-controller="ExampleController">
  23732. <h2>Which is your favorite?</h2>
  23733. <label ng-repeat="name in names" for="{{name}}">
  23734. {{name}}
  23735. <input type="radio"
  23736. ng-model="my.favorite"
  23737. ng-value="name"
  23738. id="{{name}}"
  23739. name="favorite">
  23740. </label>
  23741. <div>You chose {{my.favorite}}</div>
  23742. </form>
  23743. </file>
  23744. <file name="protractor.js" type="protractor">
  23745. var favorite = element(by.binding('my.favorite'));
  23746. it('should initialize to model', function() {
  23747. expect(favorite.getText()).toContain('unicorns');
  23748. });
  23749. it('should bind the values to the inputs', function() {
  23750. element.all(by.model('my.favorite')).get(0).click();
  23751. expect(favorite.getText()).toContain('pizza');
  23752. });
  23753. </file>
  23754. </example>
  23755. */
  23756. var ngValueDirective = function() {
  23757. /**
  23758. * inputs use the value attribute as their default value if the value property is not set.
  23759. * Once the value property has been set (by adding input), it will not react to changes to
  23760. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23761. * makes it possible to use ngValue as a sort of one-way bind.
  23762. */
  23763. function updateElementValue(element, attr, value) {
  23764. // Support: IE9 only
  23765. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23766. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23767. element.prop('value', propValue);
  23768. attr.$set('value', value);
  23769. }
  23770. return {
  23771. restrict: 'A',
  23772. priority: 100,
  23773. compile: function(tpl, tplAttr) {
  23774. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23775. return function ngValueConstantLink(scope, elm, attr) {
  23776. var value = scope.$eval(attr.ngValue);
  23777. updateElementValue(elm, attr, value);
  23778. };
  23779. } else {
  23780. return function ngValueLink(scope, elm, attr) {
  23781. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23782. updateElementValue(elm, attr, value);
  23783. });
  23784. };
  23785. }
  23786. }
  23787. };
  23788. };
  23789. /**
  23790. * @ngdoc directive
  23791. * @name ngBind
  23792. * @restrict AC
  23793. *
  23794. * @description
  23795. * The `ngBind` attribute tells AngularJS to replace the text content of the specified HTML element
  23796. * with the value of a given expression, and to update the text content when the value of that
  23797. * expression changes.
  23798. *
  23799. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23800. * `{{ expression }}` which is similar but less verbose.
  23801. *
  23802. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23803. * displayed by the browser in its raw state before AngularJS compiles it. Since `ngBind` is an
  23804. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23805. *
  23806. * An alternative solution to this problem would be using the
  23807. * {@link ng.directive:ngCloak ngCloak} directive.
  23808. *
  23809. *
  23810. * @element ANY
  23811. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23812. *
  23813. * @example
  23814. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23815. <example module="bindExample" name="ng-bind">
  23816. <file name="index.html">
  23817. <script>
  23818. angular.module('bindExample', [])
  23819. .controller('ExampleController', ['$scope', function($scope) {
  23820. $scope.name = 'Whirled';
  23821. }]);
  23822. </script>
  23823. <div ng-controller="ExampleController">
  23824. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23825. Hello <span ng-bind="name"></span>!
  23826. </div>
  23827. </file>
  23828. <file name="protractor.js" type="protractor">
  23829. it('should check ng-bind', function() {
  23830. var nameInput = element(by.model('name'));
  23831. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23832. nameInput.clear();
  23833. nameInput.sendKeys('world');
  23834. expect(element(by.binding('name')).getText()).toBe('world');
  23835. });
  23836. </file>
  23837. </example>
  23838. */
  23839. var ngBindDirective = ['$compile', function($compile) {
  23840. return {
  23841. restrict: 'AC',
  23842. compile: function ngBindCompile(templateElement) {
  23843. $compile.$$addBindingClass(templateElement);
  23844. return function ngBindLink(scope, element, attr) {
  23845. $compile.$$addBindingInfo(element, attr.ngBind);
  23846. element = element[0];
  23847. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23848. element.textContent = stringify(value);
  23849. });
  23850. };
  23851. }
  23852. };
  23853. }];
  23854. /**
  23855. * @ngdoc directive
  23856. * @name ngBindTemplate
  23857. *
  23858. * @description
  23859. * The `ngBindTemplate` directive specifies that the element
  23860. * text content should be replaced with the interpolation of the template
  23861. * in the `ngBindTemplate` attribute.
  23862. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23863. * expressions. This directive is needed since some HTML elements
  23864. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23865. *
  23866. * @element ANY
  23867. * @param {string} ngBindTemplate template of form
  23868. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23869. *
  23870. * @example
  23871. * Try it here: enter text in text box and watch the greeting change.
  23872. <example module="bindExample" name="ng-bind-template">
  23873. <file name="index.html">
  23874. <script>
  23875. angular.module('bindExample', [])
  23876. .controller('ExampleController', ['$scope', function($scope) {
  23877. $scope.salutation = 'Hello';
  23878. $scope.name = 'World';
  23879. }]);
  23880. </script>
  23881. <div ng-controller="ExampleController">
  23882. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23883. <label>Name: <input type="text" ng-model="name"></label><br>
  23884. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23885. </div>
  23886. </file>
  23887. <file name="protractor.js" type="protractor">
  23888. it('should check ng-bind', function() {
  23889. var salutationElem = element(by.binding('salutation'));
  23890. var salutationInput = element(by.model('salutation'));
  23891. var nameInput = element(by.model('name'));
  23892. expect(salutationElem.getText()).toBe('Hello World!');
  23893. salutationInput.clear();
  23894. salutationInput.sendKeys('Greetings');
  23895. nameInput.clear();
  23896. nameInput.sendKeys('user');
  23897. expect(salutationElem.getText()).toBe('Greetings user!');
  23898. });
  23899. </file>
  23900. </example>
  23901. */
  23902. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23903. return {
  23904. compile: function ngBindTemplateCompile(templateElement) {
  23905. $compile.$$addBindingClass(templateElement);
  23906. return function ngBindTemplateLink(scope, element, attr) {
  23907. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23908. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23909. element = element[0];
  23910. attr.$observe('ngBindTemplate', function(value) {
  23911. element.textContent = isUndefined(value) ? '' : value;
  23912. });
  23913. };
  23914. }
  23915. };
  23916. }];
  23917. /**
  23918. * @ngdoc directive
  23919. * @name ngBindHtml
  23920. *
  23921. * @description
  23922. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23923. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23924. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23925. * ngSanitize} in your module's dependencies (not in core AngularJS). In order to use {@link ngSanitize}
  23926. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23927. *
  23928. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23929. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23930. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23931. *
  23932. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23933. * will have an exception (instead of an exploit.)
  23934. *
  23935. * @element ANY
  23936. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23937. *
  23938. * @example
  23939. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23940. <file name="index.html">
  23941. <div ng-controller="ExampleController">
  23942. <p ng-bind-html="myHTML"></p>
  23943. </div>
  23944. </file>
  23945. <file name="script.js">
  23946. angular.module('bindHtmlExample', ['ngSanitize'])
  23947. .controller('ExampleController', ['$scope', function($scope) {
  23948. $scope.myHTML =
  23949. 'I am an <code>HTML</code>string with ' +
  23950. '<a href="#">links!</a> and other <em>stuff</em>';
  23951. }]);
  23952. </file>
  23953. <file name="protractor.js" type="protractor">
  23954. it('should check ng-bind-html', function() {
  23955. expect(element(by.binding('myHTML')).getText()).toBe(
  23956. 'I am an HTMLstring with links! and other stuff');
  23957. });
  23958. </file>
  23959. </example>
  23960. */
  23961. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23962. return {
  23963. restrict: 'A',
  23964. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23965. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23966. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23967. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23968. return $sce.valueOf(val);
  23969. });
  23970. $compile.$$addBindingClass(tElement);
  23971. return function ngBindHtmlLink(scope, element, attr) {
  23972. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23973. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23974. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23975. var value = ngBindHtmlGetter(scope);
  23976. element.html($sce.getTrustedHtml(value) || '');
  23977. });
  23978. };
  23979. }
  23980. };
  23981. }];
  23982. /**
  23983. * @ngdoc directive
  23984. * @name ngChange
  23985. * @restrict A
  23986. *
  23987. * @description
  23988. * Evaluate the given expression when the user changes the input.
  23989. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23990. * which only triggers at the end of a change (usually, when the user leaves the
  23991. * form element or presses the return key).
  23992. *
  23993. * The `ngChange` expression is only evaluated when a change in the input value causes
  23994. * a new value to be committed to the model.
  23995. *
  23996. * It will not be evaluated:
  23997. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23998. * * if the input has continued to be invalid since the model will stay `null`
  23999. * * if the model is changed programmatically and not by a change to the input value
  24000. *
  24001. *
  24002. * Note, this directive requires `ngModel` to be present.
  24003. *
  24004. * @element ANY
  24005. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  24006. * in input value.
  24007. *
  24008. * @example
  24009. * <example name="ngChange-directive" module="changeExample">
  24010. * <file name="index.html">
  24011. * <script>
  24012. * angular.module('changeExample', [])
  24013. * .controller('ExampleController', ['$scope', function($scope) {
  24014. * $scope.counter = 0;
  24015. * $scope.change = function() {
  24016. * $scope.counter++;
  24017. * };
  24018. * }]);
  24019. * </script>
  24020. * <div ng-controller="ExampleController">
  24021. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  24022. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  24023. * <label for="ng-change-example2">Confirmed</label><br />
  24024. * <tt>debug = {{confirmed}}</tt><br/>
  24025. * <tt>counter = {{counter}}</tt><br/>
  24026. * </div>
  24027. * </file>
  24028. * <file name="protractor.js" type="protractor">
  24029. * var counter = element(by.binding('counter'));
  24030. * var debug = element(by.binding('confirmed'));
  24031. *
  24032. * it('should evaluate the expression if changing from view', function() {
  24033. * expect(counter.getText()).toContain('0');
  24034. *
  24035. * element(by.id('ng-change-example1')).click();
  24036. *
  24037. * expect(counter.getText()).toContain('1');
  24038. * expect(debug.getText()).toContain('true');
  24039. * });
  24040. *
  24041. * it('should not evaluate the expression if changing from model', function() {
  24042. * element(by.id('ng-change-example2')).click();
  24043. * expect(counter.getText()).toContain('0');
  24044. * expect(debug.getText()).toContain('true');
  24045. * });
  24046. * </file>
  24047. * </example>
  24048. */
  24049. var ngChangeDirective = valueFn({
  24050. restrict: 'A',
  24051. require: 'ngModel',
  24052. link: function(scope, element, attr, ctrl) {
  24053. ctrl.$viewChangeListeners.push(function() {
  24054. scope.$eval(attr.ngChange);
  24055. });
  24056. }
  24057. });
  24058. /* exported
  24059. ngClassDirective,
  24060. ngClassEvenDirective,
  24061. ngClassOddDirective
  24062. */
  24063. function classDirective(name, selector) {
  24064. name = 'ngClass' + name;
  24065. var indexWatchExpression;
  24066. return ['$parse', function($parse) {
  24067. return {
  24068. restrict: 'AC',
  24069. link: function(scope, element, attr) {
  24070. var expression = attr[name].trim();
  24071. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  24072. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  24073. var watchExpression = $parse(expression, watchInterceptor);
  24074. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  24075. var classCounts = element.data('$classCounts');
  24076. var oldModulo = true;
  24077. var oldClassString;
  24078. if (!classCounts) {
  24079. // Use createMap() to prevent class assumptions involving property
  24080. // names in Object.prototype
  24081. classCounts = createMap();
  24082. element.data('$classCounts', classCounts);
  24083. }
  24084. if (name !== 'ngClass') {
  24085. if (!indexWatchExpression) {
  24086. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  24087. // eslint-disable-next-line no-bitwise
  24088. return $index & 1;
  24089. });
  24090. }
  24091. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  24092. }
  24093. scope.$watch(watchExpression, watchAction, isOneTime);
  24094. function addClasses(classString) {
  24095. classString = digestClassCounts(split(classString), 1);
  24096. attr.$addClass(classString);
  24097. }
  24098. function removeClasses(classString) {
  24099. classString = digestClassCounts(split(classString), -1);
  24100. attr.$removeClass(classString);
  24101. }
  24102. function updateClasses(oldClassString, newClassString) {
  24103. var oldClassArray = split(oldClassString);
  24104. var newClassArray = split(newClassString);
  24105. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  24106. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  24107. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  24108. var toAddString = digestClassCounts(toAddArray, 1);
  24109. attr.$addClass(toAddString);
  24110. attr.$removeClass(toRemoveString);
  24111. }
  24112. function digestClassCounts(classArray, count) {
  24113. var classesToUpdate = [];
  24114. forEach(classArray, function(className) {
  24115. if (count > 0 || classCounts[className]) {
  24116. classCounts[className] = (classCounts[className] || 0) + count;
  24117. if (classCounts[className] === +(count > 0)) {
  24118. classesToUpdate.push(className);
  24119. }
  24120. }
  24121. });
  24122. return classesToUpdate.join(' ');
  24123. }
  24124. function ngClassIndexWatchAction(newModulo) {
  24125. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  24126. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  24127. // `ngClass[OneTime]WatchAction()` will update the classes.
  24128. if (newModulo === selector) {
  24129. addClasses(oldClassString);
  24130. } else {
  24131. removeClasses(oldClassString);
  24132. }
  24133. oldModulo = newModulo;
  24134. }
  24135. function ngClassOneTimeWatchAction(newClassValue) {
  24136. var newClassString = toClassString(newClassValue);
  24137. if (newClassString !== oldClassString) {
  24138. ngClassWatchAction(newClassString);
  24139. }
  24140. }
  24141. function ngClassWatchAction(newClassString) {
  24142. if (oldModulo === selector) {
  24143. updateClasses(oldClassString, newClassString);
  24144. }
  24145. oldClassString = newClassString;
  24146. }
  24147. }
  24148. };
  24149. }];
  24150. // Helpers
  24151. function arrayDifference(tokens1, tokens2) {
  24152. if (!tokens1 || !tokens1.length) return [];
  24153. if (!tokens2 || !tokens2.length) return tokens1;
  24154. var values = [];
  24155. outer:
  24156. for (var i = 0; i < tokens1.length; i++) {
  24157. var token = tokens1[i];
  24158. for (var j = 0; j < tokens2.length; j++) {
  24159. if (token === tokens2[j]) continue outer;
  24160. }
  24161. values.push(token);
  24162. }
  24163. return values;
  24164. }
  24165. function split(classString) {
  24166. return classString && classString.split(' ');
  24167. }
  24168. function toClassString(classValue) {
  24169. var classString = classValue;
  24170. if (isArray(classValue)) {
  24171. classString = classValue.map(toClassString).join(' ');
  24172. } else if (isObject(classValue)) {
  24173. classString = Object.keys(classValue).
  24174. filter(function(key) { return classValue[key]; }).
  24175. join(' ');
  24176. }
  24177. return classString;
  24178. }
  24179. function toFlatValue(classValue) {
  24180. var flatValue = classValue;
  24181. if (isArray(classValue)) {
  24182. flatValue = classValue.map(toFlatValue);
  24183. } else if (isObject(classValue)) {
  24184. var hasUndefined = false;
  24185. flatValue = Object.keys(classValue).filter(function(key) {
  24186. var value = classValue[key];
  24187. if (!hasUndefined && isUndefined(value)) {
  24188. hasUndefined = true;
  24189. }
  24190. return value;
  24191. });
  24192. if (hasUndefined) {
  24193. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  24194. // the watcher, by including at least one `undefined` value.
  24195. flatValue.push(undefined);
  24196. }
  24197. }
  24198. return flatValue;
  24199. }
  24200. }
  24201. /**
  24202. * @ngdoc directive
  24203. * @name ngClass
  24204. * @restrict AC
  24205. * @element ANY
  24206. *
  24207. * @description
  24208. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  24209. * an expression that represents all classes to be added.
  24210. *
  24211. * The directive operates in three different ways, depending on which of three types the expression
  24212. * evaluates to:
  24213. *
  24214. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  24215. * names.
  24216. *
  24217. * 2. If the expression evaluates to an object, then for each key-value pair of the
  24218. * object with a truthy value the corresponding key is used as a class name.
  24219. *
  24220. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  24221. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  24222. * to give you more control over what CSS classes appear. See the code below for an example of this.
  24223. *
  24224. *
  24225. * The directive won't add duplicate classes if a particular class was already set.
  24226. *
  24227. * When the expression changes, the previously added classes are removed and only then are the
  24228. * new classes added.
  24229. *
  24230. * @knownIssue
  24231. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  24232. * attribute, when using the `ngClass` directive on the same element.
  24233. * See {@link guide/interpolation#known-issues here} for more info.
  24234. *
  24235. * @animations
  24236. * | Animation | Occurs |
  24237. * |----------------------------------|-------------------------------------|
  24238. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  24239. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  24240. *
  24241. * ### ngClass and pre-existing CSS3 Transitions/Animations
  24242. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  24243. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  24244. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  24245. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  24246. {@link $animate#removeClass $animate.removeClass}.
  24247. *
  24248. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  24249. * of the evaluation can be a string representing space delimited class
  24250. * names, an array, or a map of class names to boolean values. In the case of a map, the
  24251. * names of the properties whose values are truthy will be added as css classes to the
  24252. * element.
  24253. *
  24254. * @example
  24255. * ### Basic
  24256. <example name="ng-class">
  24257. <file name="index.html">
  24258. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  24259. <label>
  24260. <input type="checkbox" ng-model="deleted">
  24261. deleted (apply "strike" class)
  24262. </label><br>
  24263. <label>
  24264. <input type="checkbox" ng-model="important">
  24265. important (apply "bold" class)
  24266. </label><br>
  24267. <label>
  24268. <input type="checkbox" ng-model="error">
  24269. error (apply "has-error" class)
  24270. </label>
  24271. <hr>
  24272. <p ng-class="style">Using String Syntax</p>
  24273. <input type="text" ng-model="style"
  24274. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  24275. <hr>
  24276. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  24277. <input ng-model="style1"
  24278. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  24279. <input ng-model="style2"
  24280. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  24281. <input ng-model="style3"
  24282. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  24283. <hr>
  24284. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  24285. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  24286. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  24287. </file>
  24288. <file name="style.css">
  24289. .strike {
  24290. text-decoration: line-through;
  24291. }
  24292. .bold {
  24293. font-weight: bold;
  24294. }
  24295. .red {
  24296. color: red;
  24297. }
  24298. .has-error {
  24299. color: red;
  24300. background-color: yellow;
  24301. }
  24302. .orange {
  24303. color: orange;
  24304. }
  24305. </file>
  24306. <file name="protractor.js" type="protractor">
  24307. var ps = element.all(by.css('p'));
  24308. it('should let you toggle the class', function() {
  24309. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  24310. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  24311. element(by.model('important')).click();
  24312. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  24313. element(by.model('error')).click();
  24314. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  24315. });
  24316. it('should let you toggle string example', function() {
  24317. expect(ps.get(1).getAttribute('class')).toBe('');
  24318. element(by.model('style')).clear();
  24319. element(by.model('style')).sendKeys('red');
  24320. expect(ps.get(1).getAttribute('class')).toBe('red');
  24321. });
  24322. it('array example should have 3 classes', function() {
  24323. expect(ps.get(2).getAttribute('class')).toBe('');
  24324. element(by.model('style1')).sendKeys('bold');
  24325. element(by.model('style2')).sendKeys('strike');
  24326. element(by.model('style3')).sendKeys('red');
  24327. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  24328. });
  24329. it('array with map example should have 2 classes', function() {
  24330. expect(ps.last().getAttribute('class')).toBe('');
  24331. element(by.model('style4')).sendKeys('bold');
  24332. element(by.model('warning')).click();
  24333. expect(ps.last().getAttribute('class')).toBe('bold orange');
  24334. });
  24335. </file>
  24336. </example>
  24337. @example
  24338. ### Animations
  24339. The example below demonstrates how to perform animations using ngClass.
  24340. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  24341. <file name="index.html">
  24342. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  24343. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  24344. <br>
  24345. <span class="base-class" ng-class="myVar">Sample Text</span>
  24346. </file>
  24347. <file name="style.css">
  24348. .base-class {
  24349. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24350. }
  24351. .base-class.my-class {
  24352. color: red;
  24353. font-size:3em;
  24354. }
  24355. </file>
  24356. <file name="protractor.js" type="protractor">
  24357. it('should check ng-class', function() {
  24358. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24359. toMatch(/my-class/);
  24360. element(by.id('setbtn')).click();
  24361. expect(element(by.css('.base-class')).getAttribute('class')).
  24362. toMatch(/my-class/);
  24363. element(by.id('clearbtn')).click();
  24364. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24365. toMatch(/my-class/);
  24366. });
  24367. </file>
  24368. </example>
  24369. */
  24370. var ngClassDirective = classDirective('', true);
  24371. /**
  24372. * @ngdoc directive
  24373. * @name ngClassOdd
  24374. * @restrict AC
  24375. *
  24376. * @description
  24377. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24378. * {@link ng.directive:ngClass ngClass}, except they work in
  24379. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24380. *
  24381. * This directive can be applied only within the scope of an
  24382. * {@link ng.directive:ngRepeat ngRepeat}.
  24383. *
  24384. * @element ANY
  24385. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  24386. * of the evaluation can be a string representing space delimited class names or an array.
  24387. *
  24388. * @example
  24389. <example name="ng-class-odd">
  24390. <file name="index.html">
  24391. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24392. <li ng-repeat="name in names">
  24393. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24394. {{name}}
  24395. </span>
  24396. </li>
  24397. </ol>
  24398. </file>
  24399. <file name="style.css">
  24400. .odd {
  24401. color: red;
  24402. }
  24403. .even {
  24404. color: blue;
  24405. }
  24406. </file>
  24407. <file name="protractor.js" type="protractor">
  24408. it('should check ng-class-odd and ng-class-even', function() {
  24409. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24410. toMatch(/odd/);
  24411. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24412. toMatch(/even/);
  24413. });
  24414. </file>
  24415. </example>
  24416. */
  24417. var ngClassOddDirective = classDirective('Odd', 0);
  24418. /**
  24419. * @ngdoc directive
  24420. * @name ngClassEven
  24421. * @restrict AC
  24422. *
  24423. * @description
  24424. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24425. * {@link ng.directive:ngClass ngClass}, except they work in
  24426. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24427. *
  24428. * This directive can be applied only within the scope of an
  24429. * {@link ng.directive:ngRepeat ngRepeat}.
  24430. *
  24431. * @element ANY
  24432. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  24433. * result of the evaluation can be a string representing space delimited class names or an array.
  24434. *
  24435. * @example
  24436. <example name="ng-class-even">
  24437. <file name="index.html">
  24438. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24439. <li ng-repeat="name in names">
  24440. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24441. {{name}} &nbsp; &nbsp; &nbsp;
  24442. </span>
  24443. </li>
  24444. </ol>
  24445. </file>
  24446. <file name="style.css">
  24447. .odd {
  24448. color: red;
  24449. }
  24450. .even {
  24451. color: blue;
  24452. }
  24453. </file>
  24454. <file name="protractor.js" type="protractor">
  24455. it('should check ng-class-odd and ng-class-even', function() {
  24456. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24457. toMatch(/odd/);
  24458. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24459. toMatch(/even/);
  24460. });
  24461. </file>
  24462. </example>
  24463. */
  24464. var ngClassEvenDirective = classDirective('Even', 1);
  24465. /**
  24466. * @ngdoc directive
  24467. * @name ngCloak
  24468. * @restrict AC
  24469. *
  24470. * @description
  24471. * The `ngCloak` directive is used to prevent the AngularJS html template from being briefly
  24472. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  24473. * directive to avoid the undesirable flicker effect caused by the html template display.
  24474. *
  24475. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  24476. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  24477. * of the browser view.
  24478. *
  24479. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  24480. * `angular.min.js`.
  24481. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24482. *
  24483. * ```css
  24484. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  24485. * display: none !important;
  24486. * }
  24487. * ```
  24488. *
  24489. * When this css rule is loaded by the browser, all html elements (including their children) that
  24490. * are tagged with the `ngCloak` directive are hidden. When AngularJS encounters this directive
  24491. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  24492. * the compiled element visible.
  24493. *
  24494. * For the best result, the `angular.js` script must be loaded in the head section of the html
  24495. * document; alternatively, the css rule above must be included in the external stylesheet of the
  24496. * application.
  24497. *
  24498. * @element ANY
  24499. *
  24500. * @example
  24501. <example name="ng-cloak">
  24502. <file name="index.html">
  24503. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  24504. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  24505. </file>
  24506. <file name="protractor.js" type="protractor">
  24507. it('should remove the template directive and css class', function() {
  24508. expect($('#template1').getAttribute('ng-cloak')).
  24509. toBeNull();
  24510. expect($('#template2').getAttribute('ng-cloak')).
  24511. toBeNull();
  24512. });
  24513. </file>
  24514. </example>
  24515. *
  24516. */
  24517. var ngCloakDirective = ngDirective({
  24518. compile: function(element, attr) {
  24519. attr.$set('ngCloak', undefined);
  24520. element.removeClass('ng-cloak');
  24521. }
  24522. });
  24523. /**
  24524. * @ngdoc directive
  24525. * @name ngController
  24526. *
  24527. * @description
  24528. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  24529. * supports the principles behind the Model-View-Controller design pattern.
  24530. *
  24531. * MVC components in angular:
  24532. *
  24533. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  24534. * are accessed through bindings.
  24535. * * View — The template (HTML with data bindings) that is rendered into the View.
  24536. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  24537. * logic behind the application to decorate the scope with functions and values
  24538. *
  24539. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  24540. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  24541. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  24542. * and executed twice.
  24543. *
  24544. * @element ANY
  24545. * @scope
  24546. * @priority 500
  24547. * @param {expression} ngController Name of a constructor function registered with the current
  24548. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  24549. * that on the current scope evaluates to a constructor function.
  24550. *
  24551. * The controller instance can be published into a scope property by specifying
  24552. * `ng-controller="as propertyName"`.
  24553. *
  24554. * If the current `$controllerProvider` is configured to use globals (via
  24555. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  24556. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  24557. *
  24558. * @example
  24559. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  24560. * greeting are methods declared on the controller (see source tab). These methods can
  24561. * easily be called from the AngularJS markup. Any changes to the data are automatically reflected
  24562. * in the View without the need for a manual update.
  24563. *
  24564. * Two different declaration styles are included below:
  24565. *
  24566. * * one binds methods and properties directly onto the controller using `this`:
  24567. * `ng-controller="SettingsController1 as settings"`
  24568. * * one injects `$scope` into the controller:
  24569. * `ng-controller="SettingsController2"`
  24570. *
  24571. * The second option is more common in the AngularJS community, and is generally used in boilerplates
  24572. * and in this guide. However, there are advantages to binding properties directly to the controller
  24573. * and avoiding scope.
  24574. *
  24575. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  24576. * multiple controllers apply to an element.
  24577. * * If you are writing your controllers as classes you have easier access to the properties and
  24578. * methods, which will appear on the scope, from inside the controller code.
  24579. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  24580. * inheritance masking primitives.
  24581. *
  24582. * This example demonstrates the `controller as` syntax.
  24583. *
  24584. * <example name="ngControllerAs" module="controllerAsExample">
  24585. * <file name="index.html">
  24586. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  24587. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  24588. * <button ng-click="settings.greet()">greet</button><br/>
  24589. * Contact:
  24590. * <ul>
  24591. * <li ng-repeat="contact in settings.contacts">
  24592. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  24593. * <option>phone</option>
  24594. * <option>email</option>
  24595. * </select>
  24596. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24597. * <button ng-click="settings.clearContact(contact)">clear</button>
  24598. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  24599. * </li>
  24600. * <li><button ng-click="settings.addContact()">add</button></li>
  24601. * </ul>
  24602. * </div>
  24603. * </file>
  24604. * <file name="app.js">
  24605. * angular.module('controllerAsExample', [])
  24606. * .controller('SettingsController1', SettingsController1);
  24607. *
  24608. * function SettingsController1() {
  24609. * this.name = 'John Smith';
  24610. * this.contacts = [
  24611. * {type: 'phone', value: '408 555 1212'},
  24612. * {type: 'email', value: 'john.smith@example.org'}
  24613. * ];
  24614. * }
  24615. *
  24616. * SettingsController1.prototype.greet = function() {
  24617. * alert(this.name);
  24618. * };
  24619. *
  24620. * SettingsController1.prototype.addContact = function() {
  24621. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  24622. * };
  24623. *
  24624. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24625. * var index = this.contacts.indexOf(contactToRemove);
  24626. * this.contacts.splice(index, 1);
  24627. * };
  24628. *
  24629. * SettingsController1.prototype.clearContact = function(contact) {
  24630. * contact.type = 'phone';
  24631. * contact.value = '';
  24632. * };
  24633. * </file>
  24634. * <file name="protractor.js" type="protractor">
  24635. * it('should check controller as', function() {
  24636. * var container = element(by.id('ctrl-as-exmpl'));
  24637. * expect(container.element(by.model('settings.name'))
  24638. * .getAttribute('value')).toBe('John Smith');
  24639. *
  24640. * var firstRepeat =
  24641. * container.element(by.repeater('contact in settings.contacts').row(0));
  24642. * var secondRepeat =
  24643. * container.element(by.repeater('contact in settings.contacts').row(1));
  24644. *
  24645. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24646. * .toBe('408 555 1212');
  24647. *
  24648. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24649. * .toBe('john.smith@example.org');
  24650. *
  24651. * firstRepeat.element(by.buttonText('clear')).click();
  24652. *
  24653. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24654. * .toBe('');
  24655. *
  24656. * container.element(by.buttonText('add')).click();
  24657. *
  24658. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24659. * .element(by.model('contact.value'))
  24660. * .getAttribute('value'))
  24661. * .toBe('yourname@example.org');
  24662. * });
  24663. * </file>
  24664. * </example>
  24665. *
  24666. * This example demonstrates the "attach to `$scope`" style of controller.
  24667. *
  24668. * <example name="ngController" module="controllerExample">
  24669. * <file name="index.html">
  24670. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24671. * <label>Name: <input type="text" ng-model="name"/></label>
  24672. * <button ng-click="greet()">greet</button><br/>
  24673. * Contact:
  24674. * <ul>
  24675. * <li ng-repeat="contact in contacts">
  24676. * <select ng-model="contact.type" id="select_{{$index}}">
  24677. * <option>phone</option>
  24678. * <option>email</option>
  24679. * </select>
  24680. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24681. * <button ng-click="clearContact(contact)">clear</button>
  24682. * <button ng-click="removeContact(contact)">X</button>
  24683. * </li>
  24684. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24685. * </ul>
  24686. * </div>
  24687. * </file>
  24688. * <file name="app.js">
  24689. * angular.module('controllerExample', [])
  24690. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24691. *
  24692. * function SettingsController2($scope) {
  24693. * $scope.name = 'John Smith';
  24694. * $scope.contacts = [
  24695. * {type:'phone', value:'408 555 1212'},
  24696. * {type:'email', value:'john.smith@example.org'}
  24697. * ];
  24698. *
  24699. * $scope.greet = function() {
  24700. * alert($scope.name);
  24701. * };
  24702. *
  24703. * $scope.addContact = function() {
  24704. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24705. * };
  24706. *
  24707. * $scope.removeContact = function(contactToRemove) {
  24708. * var index = $scope.contacts.indexOf(contactToRemove);
  24709. * $scope.contacts.splice(index, 1);
  24710. * };
  24711. *
  24712. * $scope.clearContact = function(contact) {
  24713. * contact.type = 'phone';
  24714. * contact.value = '';
  24715. * };
  24716. * }
  24717. * </file>
  24718. * <file name="protractor.js" type="protractor">
  24719. * it('should check controller', function() {
  24720. * var container = element(by.id('ctrl-exmpl'));
  24721. *
  24722. * expect(container.element(by.model('name'))
  24723. * .getAttribute('value')).toBe('John Smith');
  24724. *
  24725. * var firstRepeat =
  24726. * container.element(by.repeater('contact in contacts').row(0));
  24727. * var secondRepeat =
  24728. * container.element(by.repeater('contact in contacts').row(1));
  24729. *
  24730. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24731. * .toBe('408 555 1212');
  24732. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24733. * .toBe('john.smith@example.org');
  24734. *
  24735. * firstRepeat.element(by.buttonText('clear')).click();
  24736. *
  24737. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24738. * .toBe('');
  24739. *
  24740. * container.element(by.buttonText('add')).click();
  24741. *
  24742. * expect(container.element(by.repeater('contact in contacts').row(2))
  24743. * .element(by.model('contact.value'))
  24744. * .getAttribute('value'))
  24745. * .toBe('yourname@example.org');
  24746. * });
  24747. * </file>
  24748. *</example>
  24749. */
  24750. var ngControllerDirective = [function() {
  24751. return {
  24752. restrict: 'A',
  24753. scope: true,
  24754. controller: '@',
  24755. priority: 500
  24756. };
  24757. }];
  24758. /**
  24759. * @ngdoc directive
  24760. * @name ngCsp
  24761. *
  24762. * @restrict A
  24763. * @element ANY
  24764. * @description
  24765. *
  24766. * AngularJS has some features that can conflict with certain restrictions that are applied when using
  24767. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24768. *
  24769. * If you intend to implement CSP with these rules then you must tell AngularJS not to use these
  24770. * features.
  24771. *
  24772. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24773. *
  24774. *
  24775. * The following default rules in CSP affect AngularJS:
  24776. *
  24777. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24778. * code from strings is forbidden. AngularJS makes use of this in the {@link $parse} service to
  24779. * provide a 30% increase in the speed of evaluating AngularJS expressions. (This CSP rule can be
  24780. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24781. * weaken the protections offered by CSP.)
  24782. *
  24783. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24784. * This prevents apps from injecting custom styles directly into the document. AngularJS makes use of
  24785. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24786. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24787. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24788. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24789. *
  24790. * If you do not provide `ngCsp` then AngularJS tries to autodetect if CSP is blocking dynamic code
  24791. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24792. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24793. * CSP error to be logged in the console:
  24794. *
  24795. * ```
  24796. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24797. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24798. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24799. * ```
  24800. *
  24801. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24802. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24803. * the `angular.js` file.
  24804. *
  24805. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24806. *
  24807. * You can specify which of the CSP related AngularJS features should be deactivated by providing
  24808. * a value for the `ng-csp` attribute. The options are as follows:
  24809. *
  24810. * * no-inline-style: this stops AngularJS from injecting CSS styles into the DOM
  24811. *
  24812. * * no-unsafe-eval: this stops AngularJS from optimizing $parse with unsafe eval of strings
  24813. *
  24814. * You can use these values in the following combinations:
  24815. *
  24816. *
  24817. * * No declaration means that AngularJS will assume that you can do inline styles, but it will do
  24818. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24819. * versions of AngularJS.
  24820. *
  24821. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell AngularJS to deactivate both inline
  24822. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24823. * versions of AngularJS.
  24824. *
  24825. * * Specifying only `no-unsafe-eval` tells AngularJS that we must not use eval, but that we can
  24826. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24827. *
  24828. * * Specifying only `no-inline-style` tells AngularJS that we must not inject styles, but that we can
  24829. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24830. *
  24831. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells AngularJS that we must not inject
  24832. * styles nor use eval, which is the same as an empty: ng-csp.
  24833. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24834. *
  24835. * @example
  24836. *
  24837. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24838. ```html
  24839. <!doctype html>
  24840. <html ng-app ng-csp>
  24841. ...
  24842. ...
  24843. </html>
  24844. ```
  24845. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24846. <example name="example.csp" module="cspExample" ng-csp="true">
  24847. <file name="index.html">
  24848. <div ng-controller="MainController as ctrl">
  24849. <div>
  24850. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24851. <span id="counter">
  24852. {{ctrl.counter}}
  24853. </span>
  24854. </div>
  24855. <div>
  24856. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24857. <span id="evilError">
  24858. {{ctrl.evilError}}
  24859. </span>
  24860. </div>
  24861. </div>
  24862. </file>
  24863. <file name="script.js">
  24864. angular.module('cspExample', [])
  24865. .controller('MainController', function MainController() {
  24866. this.counter = 0;
  24867. this.inc = function() {
  24868. this.counter++;
  24869. };
  24870. this.evil = function() {
  24871. try {
  24872. eval('1+2'); // eslint-disable-line no-eval
  24873. } catch (e) {
  24874. this.evilError = e.message;
  24875. }
  24876. };
  24877. });
  24878. </file>
  24879. <file name="protractor.js" type="protractor">
  24880. var util, webdriver;
  24881. var incBtn = element(by.id('inc'));
  24882. var counter = element(by.id('counter'));
  24883. var evilBtn = element(by.id('evil'));
  24884. var evilError = element(by.id('evilError'));
  24885. function getAndClearSevereErrors() {
  24886. return browser.manage().logs().get('browser').then(function(browserLog) {
  24887. return browserLog.filter(function(logEntry) {
  24888. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24889. });
  24890. });
  24891. }
  24892. function clearErrors() {
  24893. getAndClearSevereErrors();
  24894. }
  24895. function expectNoErrors() {
  24896. getAndClearSevereErrors().then(function(filteredLog) {
  24897. expect(filteredLog.length).toEqual(0);
  24898. if (filteredLog.length) {
  24899. console.log('browser console errors: ' + util.inspect(filteredLog));
  24900. }
  24901. });
  24902. }
  24903. function expectError(regex) {
  24904. getAndClearSevereErrors().then(function(filteredLog) {
  24905. var found = false;
  24906. filteredLog.forEach(function(log) {
  24907. if (log.message.match(regex)) {
  24908. found = true;
  24909. }
  24910. });
  24911. if (!found) {
  24912. throw new Error('expected an error that matches ' + regex);
  24913. }
  24914. });
  24915. }
  24916. beforeEach(function() {
  24917. util = require('util');
  24918. webdriver = require('selenium-webdriver');
  24919. });
  24920. // For now, we only test on Chrome,
  24921. // as Safari does not load the page with Protractor's injected scripts,
  24922. // and Firefox webdriver always disables content security policy (#6358)
  24923. if (browser.params.browser !== 'chrome') {
  24924. return;
  24925. }
  24926. it('should not report errors when the page is loaded', function() {
  24927. // clear errors so we are not dependent on previous tests
  24928. clearErrors();
  24929. // Need to reload the page as the page is already loaded when
  24930. // we come here
  24931. browser.driver.getCurrentUrl().then(function(url) {
  24932. browser.get(url);
  24933. });
  24934. expectNoErrors();
  24935. });
  24936. it('should evaluate expressions', function() {
  24937. expect(counter.getText()).toEqual('0');
  24938. incBtn.click();
  24939. expect(counter.getText()).toEqual('1');
  24940. expectNoErrors();
  24941. });
  24942. it('should throw and report an error when using "eval"', function() {
  24943. evilBtn.click();
  24944. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24945. expectError(/Content Security Policy/);
  24946. });
  24947. </file>
  24948. </example>
  24949. */
  24950. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24951. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24952. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24953. /**
  24954. * @ngdoc directive
  24955. * @name ngClick
  24956. * @restrict A
  24957. * @element ANY
  24958. * @priority 0
  24959. *
  24960. * @description
  24961. * The ngClick directive allows you to specify custom behavior when
  24962. * an element is clicked.
  24963. *
  24964. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24965. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24966. *
  24967. * @example
  24968. <example name="ng-click">
  24969. <file name="index.html">
  24970. <button ng-click="count = count + 1" ng-init="count=0">
  24971. Increment
  24972. </button>
  24973. <span>
  24974. count: {{count}}
  24975. </span>
  24976. </file>
  24977. <file name="protractor.js" type="protractor">
  24978. it('should check ng-click', function() {
  24979. expect(element(by.binding('count')).getText()).toMatch('0');
  24980. element(by.css('button')).click();
  24981. expect(element(by.binding('count')).getText()).toMatch('1');
  24982. });
  24983. </file>
  24984. </example>
  24985. */
  24986. /*
  24987. * A collection of directives that allows creation of custom event handlers that are defined as
  24988. * AngularJS expressions and are compiled and executed within the current scope.
  24989. */
  24990. var ngEventDirectives = {};
  24991. // For events that might fire synchronously during DOM manipulation
  24992. // we need to execute their event handlers asynchronously using $evalAsync,
  24993. // so that they are not executed in an inconsistent state.
  24994. var forceAsyncEvents = {
  24995. 'blur': true,
  24996. 'focus': true
  24997. };
  24998. forEach(
  24999. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  25000. function(eventName) {
  25001. var directiveName = directiveNormalize('ng-' + eventName);
  25002. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  25003. return {
  25004. restrict: 'A',
  25005. compile: function($element, attr) {
  25006. // NOTE:
  25007. // We expose the powerful `$event` object on the scope that provides access to the Window,
  25008. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  25009. // sandbox was never meant to be a security feature anyway).
  25010. var fn = $parse(attr[directiveName]);
  25011. return function ngEventHandler(scope, element) {
  25012. element.on(eventName, function(event) {
  25013. var callback = function() {
  25014. fn(scope, {$event: event});
  25015. };
  25016. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  25017. scope.$evalAsync(callback);
  25018. } else {
  25019. scope.$apply(callback);
  25020. }
  25021. });
  25022. };
  25023. }
  25024. };
  25025. }];
  25026. }
  25027. );
  25028. /**
  25029. * @ngdoc directive
  25030. * @name ngDblclick
  25031. * @restrict A
  25032. * @element ANY
  25033. * @priority 0
  25034. *
  25035. * @description
  25036. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  25037. *
  25038. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  25039. * a dblclick. (The Event object is available as `$event`)
  25040. *
  25041. * @example
  25042. <example name="ng-dblclick">
  25043. <file name="index.html">
  25044. <button ng-dblclick="count = count + 1" ng-init="count=0">
  25045. Increment (on double click)
  25046. </button>
  25047. count: {{count}}
  25048. </file>
  25049. </example>
  25050. */
  25051. /**
  25052. * @ngdoc directive
  25053. * @name ngMousedown
  25054. * @restrict A
  25055. * @element ANY
  25056. * @priority 0
  25057. *
  25058. * @description
  25059. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  25060. *
  25061. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  25062. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  25063. *
  25064. * @example
  25065. <example name="ng-mousedown">
  25066. <file name="index.html">
  25067. <button ng-mousedown="count = count + 1" ng-init="count=0">
  25068. Increment (on mouse down)
  25069. </button>
  25070. count: {{count}}
  25071. </file>
  25072. </example>
  25073. */
  25074. /**
  25075. * @ngdoc directive
  25076. * @name ngMouseup
  25077. * @restrict A
  25078. * @element ANY
  25079. * @priority 0
  25080. *
  25081. * @description
  25082. * Specify custom behavior on mouseup event.
  25083. *
  25084. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  25085. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  25086. *
  25087. * @example
  25088. <example name="ng-mouseup">
  25089. <file name="index.html">
  25090. <button ng-mouseup="count = count + 1" ng-init="count=0">
  25091. Increment (on mouse up)
  25092. </button>
  25093. count: {{count}}
  25094. </file>
  25095. </example>
  25096. */
  25097. /**
  25098. * @ngdoc directive
  25099. * @name ngMouseover
  25100. * @restrict A
  25101. * @element ANY
  25102. * @priority 0
  25103. *
  25104. * @description
  25105. * Specify custom behavior on mouseover event.
  25106. *
  25107. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  25108. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  25109. *
  25110. * @example
  25111. <example name="ng-mouseover">
  25112. <file name="index.html">
  25113. <button ng-mouseover="count = count + 1" ng-init="count=0">
  25114. Increment (when mouse is over)
  25115. </button>
  25116. count: {{count}}
  25117. </file>
  25118. </example>
  25119. */
  25120. /**
  25121. * @ngdoc directive
  25122. * @name ngMouseenter
  25123. * @restrict A
  25124. * @element ANY
  25125. * @priority 0
  25126. *
  25127. * @description
  25128. * Specify custom behavior on mouseenter event.
  25129. *
  25130. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  25131. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  25132. *
  25133. * @example
  25134. <example name="ng-mouseenter">
  25135. <file name="index.html">
  25136. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  25137. Increment (when mouse enters)
  25138. </button>
  25139. count: {{count}}
  25140. </file>
  25141. </example>
  25142. */
  25143. /**
  25144. * @ngdoc directive
  25145. * @name ngMouseleave
  25146. * @restrict A
  25147. * @element ANY
  25148. * @priority 0
  25149. *
  25150. * @description
  25151. * Specify custom behavior on mouseleave event.
  25152. *
  25153. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  25154. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  25155. *
  25156. * @example
  25157. <example name="ng-mouseleave">
  25158. <file name="index.html">
  25159. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  25160. Increment (when mouse leaves)
  25161. </button>
  25162. count: {{count}}
  25163. </file>
  25164. </example>
  25165. */
  25166. /**
  25167. * @ngdoc directive
  25168. * @name ngMousemove
  25169. * @restrict A
  25170. * @element ANY
  25171. * @priority 0
  25172. *
  25173. * @description
  25174. * Specify custom behavior on mousemove event.
  25175. *
  25176. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  25177. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  25178. *
  25179. * @example
  25180. <example name="ng-mousemove">
  25181. <file name="index.html">
  25182. <button ng-mousemove="count = count + 1" ng-init="count=0">
  25183. Increment (when mouse moves)
  25184. </button>
  25185. count: {{count}}
  25186. </file>
  25187. </example>
  25188. */
  25189. /**
  25190. * @ngdoc directive
  25191. * @name ngKeydown
  25192. * @restrict A
  25193. * @element ANY
  25194. * @priority 0
  25195. *
  25196. * @description
  25197. * Specify custom behavior on keydown event.
  25198. *
  25199. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  25200. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25201. *
  25202. * @example
  25203. <example name="ng-keydown">
  25204. <file name="index.html">
  25205. <input ng-keydown="count = count + 1" ng-init="count=0">
  25206. key down count: {{count}}
  25207. </file>
  25208. </example>
  25209. */
  25210. /**
  25211. * @ngdoc directive
  25212. * @name ngKeyup
  25213. * @restrict A
  25214. * @element ANY
  25215. * @priority 0
  25216. *
  25217. * @description
  25218. * Specify custom behavior on keyup event.
  25219. *
  25220. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  25221. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25222. *
  25223. * @example
  25224. <example name="ng-keyup">
  25225. <file name="index.html">
  25226. <p>Typing in the input box below updates the key count</p>
  25227. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  25228. <p>Typing in the input box below updates the keycode</p>
  25229. <input ng-keyup="event=$event">
  25230. <p>event keyCode: {{ event.keyCode }}</p>
  25231. <p>event altKey: {{ event.altKey }}</p>
  25232. </file>
  25233. </example>
  25234. */
  25235. /**
  25236. * @ngdoc directive
  25237. * @name ngKeypress
  25238. * @restrict A
  25239. * @element ANY
  25240. *
  25241. * @description
  25242. * Specify custom behavior on keypress event.
  25243. *
  25244. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  25245. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  25246. * and can be interrogated for keyCode, altKey, etc.)
  25247. *
  25248. * @example
  25249. <example name="ng-keypress">
  25250. <file name="index.html">
  25251. <input ng-keypress="count = count + 1" ng-init="count=0">
  25252. key press count: {{count}}
  25253. </file>
  25254. </example>
  25255. */
  25256. /**
  25257. * @ngdoc directive
  25258. * @name ngSubmit
  25259. * @restrict A
  25260. * @element form
  25261. * @priority 0
  25262. *
  25263. * @description
  25264. * Enables binding AngularJS expressions to onsubmit events.
  25265. *
  25266. * Additionally it prevents the default action (which for form means sending the request to the
  25267. * server and reloading the current page), but only if the form does not contain `action`,
  25268. * `data-action`, or `x-action` attributes.
  25269. *
  25270. * <div class="alert alert-warning">
  25271. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  25272. * `ngSubmit` handlers together. See the
  25273. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  25274. * for a detailed discussion of when `ngSubmit` may be triggered.
  25275. * </div>
  25276. *
  25277. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  25278. * ({@link guide/expression#-event- Event object is available as `$event`})
  25279. *
  25280. * @example
  25281. <example module="submitExample" name="ng-submit">
  25282. <file name="index.html">
  25283. <script>
  25284. angular.module('submitExample', [])
  25285. .controller('ExampleController', ['$scope', function($scope) {
  25286. $scope.list = [];
  25287. $scope.text = 'hello';
  25288. $scope.submit = function() {
  25289. if ($scope.text) {
  25290. $scope.list.push(this.text);
  25291. $scope.text = '';
  25292. }
  25293. };
  25294. }]);
  25295. </script>
  25296. <form ng-submit="submit()" ng-controller="ExampleController">
  25297. Enter text and hit enter:
  25298. <input type="text" ng-model="text" name="text" />
  25299. <input type="submit" id="submit" value="Submit" />
  25300. <pre>list={{list}}</pre>
  25301. </form>
  25302. </file>
  25303. <file name="protractor.js" type="protractor">
  25304. it('should check ng-submit', function() {
  25305. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25306. element(by.css('#submit')).click();
  25307. expect(element(by.binding('list')).getText()).toContain('hello');
  25308. expect(element(by.model('text')).getAttribute('value')).toBe('');
  25309. });
  25310. it('should ignore empty strings', function() {
  25311. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25312. element(by.css('#submit')).click();
  25313. element(by.css('#submit')).click();
  25314. expect(element(by.binding('list')).getText()).toContain('hello');
  25315. });
  25316. </file>
  25317. </example>
  25318. */
  25319. /**
  25320. * @ngdoc directive
  25321. * @name ngFocus
  25322. * @restrict A
  25323. * @element window, input, select, textarea, a
  25324. * @priority 0
  25325. *
  25326. * @description
  25327. * Specify custom behavior on focus event.
  25328. *
  25329. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  25330. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25331. * during an `$apply` to ensure a consistent state.
  25332. *
  25333. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  25334. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  25335. *
  25336. * @example
  25337. * See {@link ng.directive:ngClick ngClick}
  25338. */
  25339. /**
  25340. * @ngdoc directive
  25341. * @name ngBlur
  25342. * @restrict A
  25343. * @element window, input, select, textarea, a
  25344. * @priority 0
  25345. *
  25346. * @description
  25347. * Specify custom behavior on blur event.
  25348. *
  25349. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  25350. * an element has lost focus.
  25351. *
  25352. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  25353. * (e.g. removing a focussed input),
  25354. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25355. * during an `$apply` to ensure a consistent state.
  25356. *
  25357. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  25358. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  25359. *
  25360. * @example
  25361. * See {@link ng.directive:ngClick ngClick}
  25362. */
  25363. /**
  25364. * @ngdoc directive
  25365. * @name ngCopy
  25366. * @restrict A
  25367. * @element window, input, select, textarea, a
  25368. * @priority 0
  25369. *
  25370. * @description
  25371. * Specify custom behavior on copy event.
  25372. *
  25373. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  25374. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  25375. *
  25376. * @example
  25377. <example name="ng-copy">
  25378. <file name="index.html">
  25379. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  25380. copied: {{copied}}
  25381. </file>
  25382. </example>
  25383. */
  25384. /**
  25385. * @ngdoc directive
  25386. * @name ngCut
  25387. * @restrict A
  25388. * @element window, input, select, textarea, a
  25389. * @priority 0
  25390. *
  25391. * @description
  25392. * Specify custom behavior on cut event.
  25393. *
  25394. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  25395. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  25396. *
  25397. * @example
  25398. <example name="ng-cut">
  25399. <file name="index.html">
  25400. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  25401. cut: {{cut}}
  25402. </file>
  25403. </example>
  25404. */
  25405. /**
  25406. * @ngdoc directive
  25407. * @name ngPaste
  25408. * @restrict A
  25409. * @element window, input, select, textarea, a
  25410. * @priority 0
  25411. *
  25412. * @description
  25413. * Specify custom behavior on paste event.
  25414. *
  25415. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  25416. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  25417. *
  25418. * @example
  25419. <example name="ng-paste">
  25420. <file name="index.html">
  25421. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  25422. pasted: {{paste}}
  25423. </file>
  25424. </example>
  25425. */
  25426. /**
  25427. * @ngdoc directive
  25428. * @name ngIf
  25429. * @restrict A
  25430. * @multiElement
  25431. *
  25432. * @description
  25433. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  25434. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  25435. * value then the element is removed from the DOM, otherwise a clone of the
  25436. * element is reinserted into the DOM.
  25437. *
  25438. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  25439. * element in the DOM rather than changing its visibility via the `display` css property. A common
  25440. * case when this difference is significant is when using css selectors that rely on an element's
  25441. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  25442. *
  25443. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  25444. * is created when the element is restored. The scope created within `ngIf` inherits from
  25445. * its parent scope using
  25446. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  25447. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  25448. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  25449. * variable within the child scope will override (hide) the value in the parent scope.
  25450. *
  25451. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  25452. * is if an element's class attribute is directly modified after it's compiled, using something like
  25453. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  25454. * the added class will be lost because the original compiled state is used to regenerate the element.
  25455. *
  25456. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  25457. * and `leave` effects.
  25458. *
  25459. * @animations
  25460. * | Animation | Occurs |
  25461. * |----------------------------------|-------------------------------------|
  25462. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  25463. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  25464. *
  25465. * @element ANY
  25466. * @scope
  25467. * @priority 600
  25468. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  25469. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  25470. * element is added to the DOM tree.
  25471. *
  25472. * @example
  25473. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  25474. <file name="index.html">
  25475. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  25476. Show when checked:
  25477. <span ng-if="checked" class="animate-if">
  25478. This is removed when the checkbox is unchecked.
  25479. </span>
  25480. </file>
  25481. <file name="animations.css">
  25482. .animate-if {
  25483. background:white;
  25484. border:1px solid black;
  25485. padding:10px;
  25486. }
  25487. .animate-if.ng-enter, .animate-if.ng-leave {
  25488. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25489. }
  25490. .animate-if.ng-enter,
  25491. .animate-if.ng-leave.ng-leave-active {
  25492. opacity:0;
  25493. }
  25494. .animate-if.ng-leave,
  25495. .animate-if.ng-enter.ng-enter-active {
  25496. opacity:1;
  25497. }
  25498. </file>
  25499. </example>
  25500. */
  25501. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  25502. return {
  25503. multiElement: true,
  25504. transclude: 'element',
  25505. priority: 600,
  25506. terminal: true,
  25507. restrict: 'A',
  25508. $$tlb: true,
  25509. link: function($scope, $element, $attr, ctrl, $transclude) {
  25510. var block, childScope, previousElements;
  25511. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  25512. if (value) {
  25513. if (!childScope) {
  25514. $transclude(function(clone, newScope) {
  25515. childScope = newScope;
  25516. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  25517. // Note: We only need the first/last node of the cloned nodes.
  25518. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25519. // by a directive with templateUrl when its template arrives.
  25520. block = {
  25521. clone: clone
  25522. };
  25523. $animate.enter(clone, $element.parent(), $element);
  25524. });
  25525. }
  25526. } else {
  25527. if (previousElements) {
  25528. previousElements.remove();
  25529. previousElements = null;
  25530. }
  25531. if (childScope) {
  25532. childScope.$destroy();
  25533. childScope = null;
  25534. }
  25535. if (block) {
  25536. previousElements = getBlockNodes(block.clone);
  25537. $animate.leave(previousElements).done(function(response) {
  25538. if (response !== false) previousElements = null;
  25539. });
  25540. block = null;
  25541. }
  25542. }
  25543. });
  25544. }
  25545. };
  25546. }];
  25547. /**
  25548. * @ngdoc directive
  25549. * @name ngInclude
  25550. * @restrict ECA
  25551. * @scope
  25552. * @priority -400
  25553. *
  25554. * @description
  25555. * Fetches, compiles and includes an external HTML fragment.
  25556. *
  25557. * By default, the template URL is restricted to the same domain and protocol as the
  25558. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  25559. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  25560. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  25561. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to AngularJS's {@link
  25562. * ng.$sce Strict Contextual Escaping}.
  25563. *
  25564. * In addition, the browser's
  25565. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  25566. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  25567. * policy may further restrict whether the template is successfully loaded.
  25568. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  25569. * access on some browsers.
  25570. *
  25571. * @animations
  25572. * | Animation | Occurs |
  25573. * |----------------------------------|-------------------------------------|
  25574. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  25575. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  25576. *
  25577. * The enter and leave animation occur concurrently.
  25578. *
  25579. * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant,
  25580. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  25581. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  25582. * <div class="alert alert-warning">
  25583. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  25584. * a function with the name on the window element, which will usually throw a
  25585. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  25586. * different form that {@link guide/directive#normalization matches} `onload`.
  25587. * </div>
  25588. *
  25589. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  25590. * $anchorScroll} to scroll the viewport after the content is loaded.
  25591. *
  25592. * - If the attribute is not set, disable scrolling.
  25593. * - If the attribute is set without value, enable scrolling.
  25594. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  25595. *
  25596. * @example
  25597. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  25598. <file name="index.html">
  25599. <div ng-controller="ExampleController">
  25600. <select ng-model="template" ng-options="t.name for t in templates">
  25601. <option value="">(blank)</option>
  25602. </select>
  25603. url of the template: <code>{{template.url}}</code>
  25604. <hr/>
  25605. <div class="slide-animate-container">
  25606. <div class="slide-animate" ng-include="template.url"></div>
  25607. </div>
  25608. </div>
  25609. </file>
  25610. <file name="script.js">
  25611. angular.module('includeExample', ['ngAnimate'])
  25612. .controller('ExampleController', ['$scope', function($scope) {
  25613. $scope.templates =
  25614. [{ name: 'template1.html', url: 'template1.html'},
  25615. { name: 'template2.html', url: 'template2.html'}];
  25616. $scope.template = $scope.templates[0];
  25617. }]);
  25618. </file>
  25619. <file name="template1.html">
  25620. Content of template1.html
  25621. </file>
  25622. <file name="template2.html">
  25623. Content of template2.html
  25624. </file>
  25625. <file name="animations.css">
  25626. .slide-animate-container {
  25627. position:relative;
  25628. background:white;
  25629. border:1px solid black;
  25630. height:40px;
  25631. overflow:hidden;
  25632. }
  25633. .slide-animate {
  25634. padding:10px;
  25635. }
  25636. .slide-animate.ng-enter, .slide-animate.ng-leave {
  25637. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25638. position:absolute;
  25639. top:0;
  25640. left:0;
  25641. right:0;
  25642. bottom:0;
  25643. display:block;
  25644. padding:10px;
  25645. }
  25646. .slide-animate.ng-enter {
  25647. top:-50px;
  25648. }
  25649. .slide-animate.ng-enter.ng-enter-active {
  25650. top:0;
  25651. }
  25652. .slide-animate.ng-leave {
  25653. top:0;
  25654. }
  25655. .slide-animate.ng-leave.ng-leave-active {
  25656. top:50px;
  25657. }
  25658. </file>
  25659. <file name="protractor.js" type="protractor">
  25660. var templateSelect = element(by.model('template'));
  25661. var includeElem = element(by.css('[ng-include]'));
  25662. it('should load template1.html', function() {
  25663. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25664. });
  25665. it('should load template2.html', function() {
  25666. if (browser.params.browser === 'firefox') {
  25667. // Firefox can't handle using selects
  25668. // See https://github.com/angular/protractor/issues/480
  25669. return;
  25670. }
  25671. templateSelect.click();
  25672. templateSelect.all(by.css('option')).get(2).click();
  25673. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25674. });
  25675. it('should change to blank', function() {
  25676. if (browser.params.browser === 'firefox') {
  25677. // Firefox can't handle using selects
  25678. return;
  25679. }
  25680. templateSelect.click();
  25681. templateSelect.all(by.css('option')).get(0).click();
  25682. expect(includeElem.isPresent()).toBe(false);
  25683. });
  25684. </file>
  25685. </example>
  25686. */
  25687. /**
  25688. * @ngdoc event
  25689. * @name ngInclude#$includeContentRequested
  25690. * @eventType emit on the scope ngInclude was declared in
  25691. * @description
  25692. * Emitted every time the ngInclude content is requested.
  25693. *
  25694. * @param {Object} angularEvent Synthetic event object.
  25695. * @param {String} src URL of content to load.
  25696. */
  25697. /**
  25698. * @ngdoc event
  25699. * @name ngInclude#$includeContentLoaded
  25700. * @eventType emit on the current ngInclude scope
  25701. * @description
  25702. * Emitted every time the ngInclude content is reloaded.
  25703. *
  25704. * @param {Object} angularEvent Synthetic event object.
  25705. * @param {String} src URL of content to load.
  25706. */
  25707. /**
  25708. * @ngdoc event
  25709. * @name ngInclude#$includeContentError
  25710. * @eventType emit on the scope ngInclude was declared in
  25711. * @description
  25712. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25713. *
  25714. * @param {Object} angularEvent Synthetic event object.
  25715. * @param {String} src URL of content to load.
  25716. */
  25717. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25718. function($templateRequest, $anchorScroll, $animate) {
  25719. return {
  25720. restrict: 'ECA',
  25721. priority: 400,
  25722. terminal: true,
  25723. transclude: 'element',
  25724. controller: angular.noop,
  25725. compile: function(element, attr) {
  25726. var srcExp = attr.ngInclude || attr.src,
  25727. onloadExp = attr.onload || '',
  25728. autoScrollExp = attr.autoscroll;
  25729. return function(scope, $element, $attr, ctrl, $transclude) {
  25730. var changeCounter = 0,
  25731. currentScope,
  25732. previousElement,
  25733. currentElement;
  25734. var cleanupLastIncludeContent = function() {
  25735. if (previousElement) {
  25736. previousElement.remove();
  25737. previousElement = null;
  25738. }
  25739. if (currentScope) {
  25740. currentScope.$destroy();
  25741. currentScope = null;
  25742. }
  25743. if (currentElement) {
  25744. $animate.leave(currentElement).done(function(response) {
  25745. if (response !== false) previousElement = null;
  25746. });
  25747. previousElement = currentElement;
  25748. currentElement = null;
  25749. }
  25750. };
  25751. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25752. var afterAnimation = function(response) {
  25753. if (response !== false && isDefined(autoScrollExp) &&
  25754. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25755. $anchorScroll();
  25756. }
  25757. };
  25758. var thisChangeId = ++changeCounter;
  25759. if (src) {
  25760. //set the 2nd param to true to ignore the template request error so that the inner
  25761. //contents and scope can be cleaned up.
  25762. $templateRequest(src, true).then(function(response) {
  25763. if (scope.$$destroyed) return;
  25764. if (thisChangeId !== changeCounter) return;
  25765. var newScope = scope.$new();
  25766. ctrl.template = response;
  25767. // Note: This will also link all children of ng-include that were contained in the original
  25768. // html. If that content contains controllers, ... they could pollute/change the scope.
  25769. // However, using ng-include on an element with additional content does not make sense...
  25770. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25771. // function is called before linking the content, which would apply child
  25772. // directives to non existing elements.
  25773. var clone = $transclude(newScope, function(clone) {
  25774. cleanupLastIncludeContent();
  25775. $animate.enter(clone, null, $element).done(afterAnimation);
  25776. });
  25777. currentScope = newScope;
  25778. currentElement = clone;
  25779. currentScope.$emit('$includeContentLoaded', src);
  25780. scope.$eval(onloadExp);
  25781. }, function() {
  25782. if (scope.$$destroyed) return;
  25783. if (thisChangeId === changeCounter) {
  25784. cleanupLastIncludeContent();
  25785. scope.$emit('$includeContentError', src);
  25786. }
  25787. });
  25788. scope.$emit('$includeContentRequested', src);
  25789. } else {
  25790. cleanupLastIncludeContent();
  25791. ctrl.template = null;
  25792. }
  25793. });
  25794. };
  25795. }
  25796. };
  25797. }];
  25798. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25799. // It will replace and compile the content of the element with the loaded template.
  25800. // We need this directive so that the element content is already filled when
  25801. // the link function of another directive on the same element as ngInclude
  25802. // is called.
  25803. var ngIncludeFillContentDirective = ['$compile',
  25804. function($compile) {
  25805. return {
  25806. restrict: 'ECA',
  25807. priority: -400,
  25808. require: 'ngInclude',
  25809. link: function(scope, $element, $attr, ctrl) {
  25810. if (toString.call($element[0]).match(/SVG/)) {
  25811. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25812. // support innerHTML, so detect this here and try to generate the contents
  25813. // specially.
  25814. $element.empty();
  25815. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25816. function namespaceAdaptedClone(clone) {
  25817. $element.append(clone);
  25818. }, {futureParentElement: $element});
  25819. return;
  25820. }
  25821. $element.html(ctrl.template);
  25822. $compile($element.contents())(scope);
  25823. }
  25824. };
  25825. }];
  25826. /**
  25827. * @ngdoc directive
  25828. * @name ngInit
  25829. * @restrict AC
  25830. * @priority 450
  25831. * @element ANY
  25832. *
  25833. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25834. *
  25835. * @description
  25836. * The `ngInit` directive allows you to evaluate an expression in the
  25837. * current scope.
  25838. *
  25839. * <div class="alert alert-danger">
  25840. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25841. * There are only a few appropriate uses of `ngInit`:
  25842. * <ul>
  25843. * <li>aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`},
  25844. * as seen in the demo below.</li>
  25845. * <li>initializing data during development, or for examples, as seen throughout these docs.</li>
  25846. * <li>injecting data via server side scripting.</li>
  25847. * </ul>
  25848. *
  25849. * Besides these few cases, you should use {@link guide/component Components} or
  25850. * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope.
  25851. * </div>
  25852. *
  25853. * <div class="alert alert-warning">
  25854. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25855. * sure you have parentheses to ensure correct operator precedence:
  25856. * <pre class="prettyprint">
  25857. * `<div ng-init="test1 = ($index | toString)"></div>`
  25858. * </pre>
  25859. * </div>
  25860. *
  25861. * @example
  25862. <example module="initExample" name="ng-init">
  25863. <file name="index.html">
  25864. <script>
  25865. angular.module('initExample', [])
  25866. .controller('ExampleController', ['$scope', function($scope) {
  25867. $scope.list = [['a', 'b'], ['c', 'd']];
  25868. }]);
  25869. </script>
  25870. <div ng-controller="ExampleController">
  25871. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25872. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25873. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25874. </div>
  25875. </div>
  25876. </div>
  25877. </file>
  25878. <file name="protractor.js" type="protractor">
  25879. it('should alias index positions', function() {
  25880. var elements = element.all(by.css('.example-init'));
  25881. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25882. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25883. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25884. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25885. });
  25886. </file>
  25887. </example>
  25888. */
  25889. var ngInitDirective = ngDirective({
  25890. priority: 450,
  25891. compile: function() {
  25892. return {
  25893. pre: function(scope, element, attrs) {
  25894. scope.$eval(attrs.ngInit);
  25895. }
  25896. };
  25897. }
  25898. });
  25899. /**
  25900. * @ngdoc directive
  25901. * @name ngList
  25902. * @restrict A
  25903. * @priority 100
  25904. *
  25905. * @param {string=} ngList optional delimiter that should be used to split the value.
  25906. *
  25907. * @description
  25908. * Text input that converts between a delimited string and an array of strings. The default
  25909. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25910. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25911. *
  25912. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25913. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25914. * list item is respected. This implies that the user of the directive is responsible for
  25915. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25916. * tab or newline character.
  25917. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25918. * when joining the list items back together) and whitespace around each list item is stripped
  25919. * before it is added to the model.
  25920. *
  25921. * @example
  25922. * ### Validation
  25923. *
  25924. * <example name="ngList-directive" module="listExample">
  25925. * <file name="app.js">
  25926. * angular.module('listExample', [])
  25927. * .controller('ExampleController', ['$scope', function($scope) {
  25928. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25929. * }]);
  25930. * </file>
  25931. * <file name="index.html">
  25932. * <form name="myForm" ng-controller="ExampleController">
  25933. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25934. * <span role="alert">
  25935. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25936. * Required!</span>
  25937. * </span>
  25938. * <br>
  25939. * <tt>names = {{names}}</tt><br/>
  25940. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25941. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25942. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25943. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25944. * </form>
  25945. * </file>
  25946. * <file name="protractor.js" type="protractor">
  25947. * var listInput = element(by.model('names'));
  25948. * var names = element(by.exactBinding('names'));
  25949. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25950. * var error = element(by.css('span.error'));
  25951. *
  25952. * it('should initialize to model', function() {
  25953. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25954. * expect(valid.getText()).toContain('true');
  25955. * expect(error.getCssValue('display')).toBe('none');
  25956. * });
  25957. *
  25958. * it('should be invalid if empty', function() {
  25959. * listInput.clear();
  25960. * listInput.sendKeys('');
  25961. *
  25962. * expect(names.getText()).toContain('');
  25963. * expect(valid.getText()).toContain('false');
  25964. * expect(error.getCssValue('display')).not.toBe('none');
  25965. * });
  25966. * </file>
  25967. * </example>
  25968. *
  25969. * @example
  25970. * ### Splitting on newline
  25971. *
  25972. * <example name="ngList-directive-newlines">
  25973. * <file name="index.html">
  25974. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25975. * <pre>{{ list | json }}</pre>
  25976. * </file>
  25977. * <file name="protractor.js" type="protractor">
  25978. * it("should split the text by newlines", function() {
  25979. * var listInput = element(by.model('list'));
  25980. * var output = element(by.binding('list | json'));
  25981. * listInput.sendKeys('abc\ndef\nghi');
  25982. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25983. * });
  25984. * </file>
  25985. * </example>
  25986. *
  25987. */
  25988. var ngListDirective = function() {
  25989. return {
  25990. restrict: 'A',
  25991. priority: 100,
  25992. require: 'ngModel',
  25993. link: function(scope, element, attr, ctrl) {
  25994. var ngList = attr.ngList || ', ';
  25995. var trimValues = attr.ngTrim !== 'false';
  25996. var separator = trimValues ? trim(ngList) : ngList;
  25997. var parse = function(viewValue) {
  25998. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25999. if (isUndefined(viewValue)) return;
  26000. var list = [];
  26001. if (viewValue) {
  26002. forEach(viewValue.split(separator), function(value) {
  26003. if (value) list.push(trimValues ? trim(value) : value);
  26004. });
  26005. }
  26006. return list;
  26007. };
  26008. ctrl.$parsers.push(parse);
  26009. ctrl.$formatters.push(function(value) {
  26010. if (isArray(value)) {
  26011. return value.join(ngList);
  26012. }
  26013. return undefined;
  26014. });
  26015. // Override the standard $isEmpty because an empty array means the input is empty.
  26016. ctrl.$isEmpty = function(value) {
  26017. return !value || !value.length;
  26018. };
  26019. }
  26020. };
  26021. };
  26022. /* global VALID_CLASS: true,
  26023. INVALID_CLASS: true,
  26024. PRISTINE_CLASS: true,
  26025. DIRTY_CLASS: true,
  26026. UNTOUCHED_CLASS: true,
  26027. TOUCHED_CLASS: true,
  26028. PENDING_CLASS: true,
  26029. addSetValidityMethod: true,
  26030. setupValidity: true,
  26031. defaultModelOptions: false
  26032. */
  26033. var VALID_CLASS = 'ng-valid',
  26034. INVALID_CLASS = 'ng-invalid',
  26035. PRISTINE_CLASS = 'ng-pristine',
  26036. DIRTY_CLASS = 'ng-dirty',
  26037. UNTOUCHED_CLASS = 'ng-untouched',
  26038. TOUCHED_CLASS = 'ng-touched',
  26039. EMPTY_CLASS = 'ng-empty',
  26040. NOT_EMPTY_CLASS = 'ng-not-empty';
  26041. var ngModelMinErr = minErr('ngModel');
  26042. /**
  26043. * @ngdoc type
  26044. * @name ngModel.NgModelController
  26045. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  26046. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  26047. * is set.
  26048. *
  26049. * @property {*} $modelValue The value in the model that the control is bound to.
  26050. *
  26051. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  26052. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  26053. `$viewValue`} from the DOM, usually via user input.
  26054. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  26055. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  26056. The functions are called in array order, each passing
  26057. its return value through to the next. The last return value is forwarded to the
  26058. {@link ngModel.NgModelController#$validators `$validators`} collection.
  26059. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  26060. `$viewValue`}.
  26061. Returning `undefined` from a parser means a parse error occurred. In that case,
  26062. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  26063. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  26064. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  26065. This simple example shows a parser that would convert text input value to lowercase:
  26066. * ```js
  26067. * function parse(value) {
  26068. * if (value) {
  26069. * return value.toLowerCase();
  26070. * }
  26071. * }
  26072. * ngModelController.$parsers.push(parse);
  26073. * ```
  26074. *
  26075. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  26076. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  26077. value of the control is changed by user interaction.
  26078. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  26079. `$modelValue`} for display in the control.
  26080. The functions are called in reverse array order, each passing the value through to the
  26081. next. The last return value is used as the actual DOM value.
  26082. This simple example shows a formatter that would convert the model value to uppercase:
  26083. * ```js
  26084. * function format(value) {
  26085. * if (value) {
  26086. * return value.toUpperCase();
  26087. * }
  26088. * }
  26089. * ngModel.$formatters.push(format);
  26090. * ```
  26091. *
  26092. * @property {Object.<string, function>} $validators A collection of validators that are applied
  26093. * whenever the model value changes. The key value within the object refers to the name of the
  26094. * validator while the function refers to the validation operation. The validation operation is
  26095. * provided with the model value as an argument and must return a true or false value depending
  26096. * on the response of that validation.
  26097. *
  26098. * ```js
  26099. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  26100. * var value = modelValue || viewValue;
  26101. * return /[0-9]+/.test(value) &&
  26102. * /[a-z]+/.test(value) &&
  26103. * /[A-Z]+/.test(value) &&
  26104. * /\W+/.test(value);
  26105. * };
  26106. * ```
  26107. *
  26108. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  26109. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  26110. * is expected to return a promise when it is run during the model validation process. Once the promise
  26111. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  26112. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  26113. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  26114. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  26115. * will only run once all synchronous validators have passed.
  26116. *
  26117. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  26118. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  26119. *
  26120. * ```js
  26121. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  26122. * var value = modelValue || viewValue;
  26123. *
  26124. * // Lookup user by username
  26125. * return $http.get('/api/users/' + value).
  26126. * then(function resolved() {
  26127. * //username exists, this means validation fails
  26128. * return $q.reject('exists');
  26129. * }, function rejected() {
  26130. * //username does not exist, therefore this validation passes
  26131. * return true;
  26132. * });
  26133. * };
  26134. * ```
  26135. *
  26136. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever
  26137. * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change
  26138. * to {@link ngModel.NgModelController#$modelValue `$modelValue`}.
  26139. * It is called with no arguments, and its return value is ignored.
  26140. * This can be used in place of additional $watches against the model value.
  26141. *
  26142. * @property {Object} $error An object hash with all failing validator ids as keys.
  26143. * @property {Object} $pending An object hash with all pending validator ids as keys.
  26144. *
  26145. * @property {boolean} $untouched True if control has not lost focus yet.
  26146. * @property {boolean} $touched True if control has lost focus.
  26147. * @property {boolean} $pristine True if user has not interacted with the control yet.
  26148. * @property {boolean} $dirty True if user has already interacted with the control.
  26149. * @property {boolean} $valid True if there is no error.
  26150. * @property {boolean} $invalid True if at least one error on the control.
  26151. * @property {string} $name The name attribute of the control.
  26152. *
  26153. * @description
  26154. *
  26155. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  26156. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  26157. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  26158. * listening to DOM events.
  26159. * Such DOM related logic should be provided by other directives which make use of
  26160. * `NgModelController` for data-binding to control elements.
  26161. * AngularJS provides this DOM logic for most {@link input `input`} elements.
  26162. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  26163. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  26164. *
  26165. * @example
  26166. * ### Custom Control Example
  26167. * This example shows how to use `NgModelController` with a custom control to achieve
  26168. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  26169. * collaborate together to achieve the desired result.
  26170. *
  26171. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  26172. * contents be edited in place by the user.
  26173. *
  26174. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  26175. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  26176. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  26177. * that content using the `$sce` service.
  26178. *
  26179. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  26180. <file name="style.css">
  26181. [contenteditable] {
  26182. border: 1px solid black;
  26183. background-color: white;
  26184. min-height: 20px;
  26185. }
  26186. .ng-invalid {
  26187. border: 1px solid red;
  26188. }
  26189. </file>
  26190. <file name="script.js">
  26191. angular.module('customControl', ['ngSanitize']).
  26192. directive('contenteditable', ['$sce', function($sce) {
  26193. return {
  26194. restrict: 'A', // only activate on element attribute
  26195. require: '?ngModel', // get a hold of NgModelController
  26196. link: function(scope, element, attrs, ngModel) {
  26197. if (!ngModel) return; // do nothing if no ng-model
  26198. // Specify how UI should be updated
  26199. ngModel.$render = function() {
  26200. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  26201. };
  26202. // Listen for change events to enable binding
  26203. element.on('blur keyup change', function() {
  26204. scope.$evalAsync(read);
  26205. });
  26206. read(); // initialize
  26207. // Write data to the model
  26208. function read() {
  26209. var html = element.html();
  26210. // When we clear the content editable the browser leaves a <br> behind
  26211. // If strip-br attribute is provided then we strip this out
  26212. if (attrs.stripBr && html === '<br>') {
  26213. html = '';
  26214. }
  26215. ngModel.$setViewValue(html);
  26216. }
  26217. }
  26218. };
  26219. }]);
  26220. </file>
  26221. <file name="index.html">
  26222. <form name="myForm">
  26223. <div contenteditable
  26224. name="myWidget" ng-model="userContent"
  26225. strip-br="true"
  26226. required>Change me!</div>
  26227. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  26228. <hr>
  26229. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  26230. </form>
  26231. </file>
  26232. <file name="protractor.js" type="protractor">
  26233. it('should data-bind and become invalid', function() {
  26234. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  26235. // SafariDriver can't handle contenteditable
  26236. // and Firefox driver can't clear contenteditables very well
  26237. return;
  26238. }
  26239. var contentEditable = element(by.css('[contenteditable]'));
  26240. var content = 'Change me!';
  26241. expect(contentEditable.getText()).toEqual(content);
  26242. contentEditable.clear();
  26243. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  26244. expect(contentEditable.getText()).toEqual('');
  26245. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  26246. });
  26247. </file>
  26248. * </example>
  26249. *
  26250. *
  26251. */
  26252. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  26253. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  26254. this.$viewValue = Number.NaN;
  26255. this.$modelValue = Number.NaN;
  26256. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  26257. this.$validators = {};
  26258. this.$asyncValidators = {};
  26259. this.$parsers = [];
  26260. this.$formatters = [];
  26261. this.$viewChangeListeners = [];
  26262. this.$untouched = true;
  26263. this.$touched = false;
  26264. this.$pristine = true;
  26265. this.$dirty = false;
  26266. this.$valid = true;
  26267. this.$invalid = false;
  26268. this.$error = {}; // keep invalid keys here
  26269. this.$$success = {}; // keep valid keys here
  26270. this.$pending = undefined; // keep pending keys here
  26271. this.$name = $interpolate($attr.name || '', false)($scope);
  26272. this.$$parentForm = nullFormCtrl;
  26273. this.$options = defaultModelOptions;
  26274. this.$$updateEvents = '';
  26275. // Attach the correct context to the event handler function for updateOn
  26276. this.$$updateEventHandler = this.$$updateEventHandler.bind(this);
  26277. this.$$parsedNgModel = $parse($attr.ngModel);
  26278. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  26279. this.$$ngModelGet = this.$$parsedNgModel;
  26280. this.$$ngModelSet = this.$$parsedNgModelAssign;
  26281. this.$$pendingDebounce = null;
  26282. this.$$parserValid = undefined;
  26283. this.$$currentValidationRunId = 0;
  26284. // https://github.com/angular/angular.js/issues/15833
  26285. // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched
  26286. Object.defineProperty(this, '$$scope', {value: $scope});
  26287. this.$$attr = $attr;
  26288. this.$$element = $element;
  26289. this.$$animate = $animate;
  26290. this.$$timeout = $timeout;
  26291. this.$$parse = $parse;
  26292. this.$$q = $q;
  26293. this.$$exceptionHandler = $exceptionHandler;
  26294. setupValidity(this);
  26295. setupModelWatcher(this);
  26296. }
  26297. NgModelController.prototype = {
  26298. $$initGetterSetters: function() {
  26299. if (this.$options.getOption('getterSetter')) {
  26300. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  26301. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  26302. this.$$ngModelGet = function($scope) {
  26303. var modelValue = this.$$parsedNgModel($scope);
  26304. if (isFunction(modelValue)) {
  26305. modelValue = invokeModelGetter($scope);
  26306. }
  26307. return modelValue;
  26308. };
  26309. this.$$ngModelSet = function($scope, newValue) {
  26310. if (isFunction(this.$$parsedNgModel($scope))) {
  26311. invokeModelSetter($scope, {$$$p: newValue});
  26312. } else {
  26313. this.$$parsedNgModelAssign($scope, newValue);
  26314. }
  26315. };
  26316. } else if (!this.$$parsedNgModel.assign) {
  26317. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  26318. this.$$attr.ngModel, startingTag(this.$$element));
  26319. }
  26320. },
  26321. /**
  26322. * @ngdoc method
  26323. * @name ngModel.NgModelController#$render
  26324. *
  26325. * @description
  26326. * Called when the view needs to be updated. It is expected that the user of the ng-model
  26327. * directive will implement this method.
  26328. *
  26329. * The `$render()` method is invoked in the following situations:
  26330. *
  26331. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  26332. * committed value then `$render()` is called to update the input control.
  26333. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  26334. * the `$viewValue` are different from last time.
  26335. *
  26336. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  26337. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  26338. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  26339. * invoked if you only change a property on the objects.
  26340. */
  26341. $render: noop,
  26342. /**
  26343. * @ngdoc method
  26344. * @name ngModel.NgModelController#$isEmpty
  26345. *
  26346. * @description
  26347. * This is called when we need to determine if the value of an input is empty.
  26348. *
  26349. * For instance, the required directive does this to work out if the input has data or not.
  26350. *
  26351. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  26352. *
  26353. * You can override this for input directives whose concept of being empty is different from the
  26354. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  26355. * implies empty.
  26356. *
  26357. * @param {*} value The value of the input to check for emptiness.
  26358. * @returns {boolean} True if `value` is "empty".
  26359. */
  26360. $isEmpty: function(value) {
  26361. // eslint-disable-next-line no-self-compare
  26362. return isUndefined(value) || value === '' || value === null || value !== value;
  26363. },
  26364. $$updateEmptyClasses: function(value) {
  26365. if (this.$isEmpty(value)) {
  26366. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  26367. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  26368. } else {
  26369. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  26370. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  26371. }
  26372. },
  26373. /**
  26374. * @ngdoc method
  26375. * @name ngModel.NgModelController#$setPristine
  26376. *
  26377. * @description
  26378. * Sets the control to its pristine state.
  26379. *
  26380. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  26381. * state (`ng-pristine` class). A model is considered to be pristine when the control
  26382. * has not been changed from when first compiled.
  26383. */
  26384. $setPristine: function() {
  26385. this.$dirty = false;
  26386. this.$pristine = true;
  26387. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  26388. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  26389. },
  26390. /**
  26391. * @ngdoc method
  26392. * @name ngModel.NgModelController#$setDirty
  26393. *
  26394. * @description
  26395. * Sets the control to its dirty state.
  26396. *
  26397. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  26398. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  26399. * from when first compiled.
  26400. */
  26401. $setDirty: function() {
  26402. this.$dirty = true;
  26403. this.$pristine = false;
  26404. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  26405. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  26406. this.$$parentForm.$setDirty();
  26407. },
  26408. /**
  26409. * @ngdoc method
  26410. * @name ngModel.NgModelController#$setUntouched
  26411. *
  26412. * @description
  26413. * Sets the control to its untouched state.
  26414. *
  26415. * This method can be called to remove the `ng-touched` class and set the control to its
  26416. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  26417. * by default, however this function can be used to restore that state if the model has
  26418. * already been touched by the user.
  26419. */
  26420. $setUntouched: function() {
  26421. this.$touched = false;
  26422. this.$untouched = true;
  26423. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  26424. },
  26425. /**
  26426. * @ngdoc method
  26427. * @name ngModel.NgModelController#$setTouched
  26428. *
  26429. * @description
  26430. * Sets the control to its touched state.
  26431. *
  26432. * This method can be called to remove the `ng-untouched` class and set the control to its
  26433. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  26434. * first focused the control element and then shifted focus away from the control (blur event).
  26435. */
  26436. $setTouched: function() {
  26437. this.$touched = true;
  26438. this.$untouched = false;
  26439. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  26440. },
  26441. /**
  26442. * @ngdoc method
  26443. * @name ngModel.NgModelController#$rollbackViewValue
  26444. *
  26445. * @description
  26446. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  26447. * which may be caused by a pending debounced event or because the input is waiting for some
  26448. * future event.
  26449. *
  26450. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  26451. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  26452. * sync with the ngModel's `$modelValue`.
  26453. *
  26454. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  26455. * and reset the input to the last committed view value.
  26456. *
  26457. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  26458. * programmatically before these debounced/future events have resolved/occurred, because AngularJS's
  26459. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  26460. *
  26461. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  26462. * input which may have such events pending. This is important in order to make sure that the
  26463. * input field will be updated with the new model value and any pending operations are cancelled.
  26464. *
  26465. * @example
  26466. * <example name="ng-model-cancel-update" module="cancel-update-example">
  26467. * <file name="app.js">
  26468. * angular.module('cancel-update-example', [])
  26469. *
  26470. * .controller('CancelUpdateController', ['$scope', function($scope) {
  26471. * $scope.model = {value1: '', value2: ''};
  26472. *
  26473. * $scope.setEmpty = function(e, value, rollback) {
  26474. * if (e.keyCode === 27) {
  26475. * e.preventDefault();
  26476. * if (rollback) {
  26477. * $scope.myForm[value].$rollbackViewValue();
  26478. * }
  26479. * $scope.model[value] = '';
  26480. * }
  26481. * };
  26482. * }]);
  26483. * </file>
  26484. * <file name="index.html">
  26485. * <div ng-controller="CancelUpdateController">
  26486. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  26487. * empty them. Follow these steps and observe the difference:</p>
  26488. * <ol>
  26489. * <li>Type something in the input. You will see that the model is not yet updated</li>
  26490. * <li>Press the Escape key.
  26491. * <ol>
  26492. * <li> In the first example, nothing happens, because the model is already '', and no
  26493. * update is detected. If you blur the input, the model will be set to the current view.
  26494. * </li>
  26495. * <li> In the second example, the pending update is cancelled, and the input is set back
  26496. * to the last committed view value (''). Blurring the input does nothing.
  26497. * </li>
  26498. * </ol>
  26499. * </li>
  26500. * </ol>
  26501. *
  26502. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  26503. * <div>
  26504. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  26505. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  26506. * ng-keydown="setEmpty($event, 'value1')">
  26507. * value1: "{{ model.value1 }}"
  26508. * </div>
  26509. *
  26510. * <div>
  26511. * <p id="inputDescription2">With $rollbackViewValue():</p>
  26512. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  26513. * ng-keydown="setEmpty($event, 'value2', true)">
  26514. * value2: "{{ model.value2 }}"
  26515. * </div>
  26516. * </form>
  26517. * </div>
  26518. * </file>
  26519. <file name="style.css">
  26520. div {
  26521. display: table-cell;
  26522. }
  26523. div:nth-child(1) {
  26524. padding-right: 30px;
  26525. }
  26526. </file>
  26527. * </example>
  26528. */
  26529. $rollbackViewValue: function() {
  26530. this.$$timeout.cancel(this.$$pendingDebounce);
  26531. this.$viewValue = this.$$lastCommittedViewValue;
  26532. this.$render();
  26533. },
  26534. /**
  26535. * @ngdoc method
  26536. * @name ngModel.NgModelController#$validate
  26537. *
  26538. * @description
  26539. * Runs each of the registered validators (first synchronous validators and then
  26540. * asynchronous validators).
  26541. * If the validity changes to invalid, the model will be set to `undefined`,
  26542. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  26543. * If the validity changes to valid, it will set the model to the last available valid
  26544. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  26545. */
  26546. $validate: function() {
  26547. // ignore $validate before model is initialized
  26548. if (isNumberNaN(this.$modelValue)) {
  26549. return;
  26550. }
  26551. var viewValue = this.$$lastCommittedViewValue;
  26552. // Note: we use the $$rawModelValue as $modelValue might have been
  26553. // set to undefined during a view -> model update that found validation
  26554. // errors. We can't parse the view here, since that could change
  26555. // the model although neither viewValue nor the model on the scope changed
  26556. var modelValue = this.$$rawModelValue;
  26557. var prevValid = this.$valid;
  26558. var prevModelValue = this.$modelValue;
  26559. var allowInvalid = this.$options.getOption('allowInvalid');
  26560. var that = this;
  26561. this.$$runValidators(modelValue, viewValue, function(allValid) {
  26562. // If there was no change in validity, don't update the model
  26563. // This prevents changing an invalid modelValue to undefined
  26564. if (!allowInvalid && prevValid !== allValid) {
  26565. // Note: Don't check this.$valid here, as we could have
  26566. // external validators (e.g. calculated on the server),
  26567. // that just call $setValidity and need the model value
  26568. // to calculate their validity.
  26569. that.$modelValue = allValid ? modelValue : undefined;
  26570. if (that.$modelValue !== prevModelValue) {
  26571. that.$$writeModelToScope();
  26572. }
  26573. }
  26574. });
  26575. },
  26576. $$runValidators: function(modelValue, viewValue, doneCallback) {
  26577. this.$$currentValidationRunId++;
  26578. var localValidationRunId = this.$$currentValidationRunId;
  26579. var that = this;
  26580. // check parser error
  26581. if (!processParseErrors()) {
  26582. validationDone(false);
  26583. return;
  26584. }
  26585. if (!processSyncValidators()) {
  26586. validationDone(false);
  26587. return;
  26588. }
  26589. processAsyncValidators();
  26590. function processParseErrors() {
  26591. var errorKey = that.$$parserName || 'parse';
  26592. if (isUndefined(that.$$parserValid)) {
  26593. setValidity(errorKey, null);
  26594. } else {
  26595. if (!that.$$parserValid) {
  26596. forEach(that.$validators, function(v, name) {
  26597. setValidity(name, null);
  26598. });
  26599. forEach(that.$asyncValidators, function(v, name) {
  26600. setValidity(name, null);
  26601. });
  26602. }
  26603. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  26604. setValidity(errorKey, that.$$parserValid);
  26605. return that.$$parserValid;
  26606. }
  26607. return true;
  26608. }
  26609. function processSyncValidators() {
  26610. var syncValidatorsValid = true;
  26611. forEach(that.$validators, function(validator, name) {
  26612. var result = Boolean(validator(modelValue, viewValue));
  26613. syncValidatorsValid = syncValidatorsValid && result;
  26614. setValidity(name, result);
  26615. });
  26616. if (!syncValidatorsValid) {
  26617. forEach(that.$asyncValidators, function(v, name) {
  26618. setValidity(name, null);
  26619. });
  26620. return false;
  26621. }
  26622. return true;
  26623. }
  26624. function processAsyncValidators() {
  26625. var validatorPromises = [];
  26626. var allValid = true;
  26627. forEach(that.$asyncValidators, function(validator, name) {
  26628. var promise = validator(modelValue, viewValue);
  26629. if (!isPromiseLike(promise)) {
  26630. throw ngModelMinErr('nopromise',
  26631. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  26632. }
  26633. setValidity(name, undefined);
  26634. validatorPromises.push(promise.then(function() {
  26635. setValidity(name, true);
  26636. }, function() {
  26637. allValid = false;
  26638. setValidity(name, false);
  26639. }));
  26640. });
  26641. if (!validatorPromises.length) {
  26642. validationDone(true);
  26643. } else {
  26644. that.$$q.all(validatorPromises).then(function() {
  26645. validationDone(allValid);
  26646. }, noop);
  26647. }
  26648. }
  26649. function setValidity(name, isValid) {
  26650. if (localValidationRunId === that.$$currentValidationRunId) {
  26651. that.$setValidity(name, isValid);
  26652. }
  26653. }
  26654. function validationDone(allValid) {
  26655. if (localValidationRunId === that.$$currentValidationRunId) {
  26656. doneCallback(allValid);
  26657. }
  26658. }
  26659. },
  26660. /**
  26661. * @ngdoc method
  26662. * @name ngModel.NgModelController#$commitViewValue
  26663. *
  26664. * @description
  26665. * Commit a pending update to the `$modelValue`.
  26666. *
  26667. * Updates may be pending by a debounced event or because the input is waiting for a some future
  26668. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  26669. * usually handles calling this in response to input events.
  26670. */
  26671. $commitViewValue: function() {
  26672. var viewValue = this.$viewValue;
  26673. this.$$timeout.cancel(this.$$pendingDebounce);
  26674. // If the view value has not changed then we should just exit, except in the case where there is
  26675. // a native validator on the element. In this case the validation state may have changed even though
  26676. // the viewValue has stayed empty.
  26677. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26678. return;
  26679. }
  26680. this.$$updateEmptyClasses(viewValue);
  26681. this.$$lastCommittedViewValue = viewValue;
  26682. // change to dirty
  26683. if (this.$pristine) {
  26684. this.$setDirty();
  26685. }
  26686. this.$$parseAndValidate();
  26687. },
  26688. $$parseAndValidate: function() {
  26689. var viewValue = this.$$lastCommittedViewValue;
  26690. var modelValue = viewValue;
  26691. var that = this;
  26692. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26693. if (this.$$parserValid) {
  26694. for (var i = 0; i < this.$parsers.length; i++) {
  26695. modelValue = this.$parsers[i](modelValue);
  26696. if (isUndefined(modelValue)) {
  26697. this.$$parserValid = false;
  26698. break;
  26699. }
  26700. }
  26701. }
  26702. if (isNumberNaN(this.$modelValue)) {
  26703. // this.$modelValue has not been touched yet...
  26704. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26705. }
  26706. var prevModelValue = this.$modelValue;
  26707. var allowInvalid = this.$options.getOption('allowInvalid');
  26708. this.$$rawModelValue = modelValue;
  26709. if (allowInvalid) {
  26710. this.$modelValue = modelValue;
  26711. writeToModelIfNeeded();
  26712. }
  26713. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26714. // This can happen if e.g. $setViewValue is called from inside a parser
  26715. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26716. if (!allowInvalid) {
  26717. // Note: Don't check this.$valid here, as we could have
  26718. // external validators (e.g. calculated on the server),
  26719. // that just call $setValidity and need the model value
  26720. // to calculate their validity.
  26721. that.$modelValue = allValid ? modelValue : undefined;
  26722. writeToModelIfNeeded();
  26723. }
  26724. });
  26725. function writeToModelIfNeeded() {
  26726. if (that.$modelValue !== prevModelValue) {
  26727. that.$$writeModelToScope();
  26728. }
  26729. }
  26730. },
  26731. $$writeModelToScope: function() {
  26732. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26733. forEach(this.$viewChangeListeners, function(listener) {
  26734. try {
  26735. listener();
  26736. } catch (e) {
  26737. // eslint-disable-next-line no-invalid-this
  26738. this.$$exceptionHandler(e);
  26739. }
  26740. }, this);
  26741. },
  26742. /**
  26743. * @ngdoc method
  26744. * @name ngModel.NgModelController#$setViewValue
  26745. *
  26746. * @description
  26747. * Update the view value.
  26748. *
  26749. * This method should be called when a control wants to change the view value; typically,
  26750. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26751. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26752. * calls it when an option is selected.
  26753. *
  26754. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26755. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26756. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  26757. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  26758. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  26759. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  26760. *
  26761. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26762. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26763. * `updateOn` events is triggered on the DOM element.
  26764. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26765. * directive is used with a custom debounce for this particular event.
  26766. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26767. * is specified, once the timer runs out.
  26768. *
  26769. * When used with standard inputs, the view value will always be a string (which is in some cases
  26770. * parsed into another type, such as a `Date` object for `input[date]`.)
  26771. * However, custom controls might also pass objects to this method. In this case, we should make
  26772. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26773. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26774. * the property of the object then ngModel will not realize that the object has changed and
  26775. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26776. * not change properties of the copy once it has been passed to `$setViewValue`.
  26777. * Otherwise you may cause the model value on the scope to change incorrectly.
  26778. *
  26779. * <div class="alert alert-info">
  26780. * In any case, the value passed to the method should always reflect the current value
  26781. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26782. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26783. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26784. * the control's DOM value in any way. If we want to change the control's DOM value
  26785. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26786. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26787. * to update the DOM, and finally call `$validate` on it.
  26788. * </div>
  26789. *
  26790. * @param {*} value value from the view.
  26791. * @param {string} trigger Event that triggered the update.
  26792. */
  26793. $setViewValue: function(value, trigger) {
  26794. this.$viewValue = value;
  26795. if (this.$options.getOption('updateOnDefault')) {
  26796. this.$$debounceViewValueCommit(trigger);
  26797. }
  26798. },
  26799. $$debounceViewValueCommit: function(trigger) {
  26800. var debounceDelay = this.$options.getOption('debounce');
  26801. if (isNumber(debounceDelay[trigger])) {
  26802. debounceDelay = debounceDelay[trigger];
  26803. } else if (isNumber(debounceDelay['default'])) {
  26804. debounceDelay = debounceDelay['default'];
  26805. }
  26806. this.$$timeout.cancel(this.$$pendingDebounce);
  26807. var that = this;
  26808. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26809. this.$$pendingDebounce = this.$$timeout(function() {
  26810. that.$commitViewValue();
  26811. }, debounceDelay);
  26812. } else if (this.$$scope.$root.$$phase) {
  26813. this.$commitViewValue();
  26814. } else {
  26815. this.$$scope.$apply(function() {
  26816. that.$commitViewValue();
  26817. });
  26818. }
  26819. },
  26820. /**
  26821. * @ngdoc method
  26822. *
  26823. * @name ngModel.NgModelController#$overrideModelOptions
  26824. *
  26825. * @description
  26826. *
  26827. * Override the current model options settings programmatically.
  26828. *
  26829. * The previous `ModelOptions` value will not be modified. Instead, a
  26830. * new `ModelOptions` object will inherit from the previous one overriding
  26831. * or inheriting settings that are defined in the given parameter.
  26832. *
  26833. * See {@link ngModelOptions} for information about what options can be specified
  26834. * and how model option inheritance works.
  26835. *
  26836. * <div class="alert alert-warning">
  26837. * **Note:** this function only affects the options set on the `ngModelController`,
  26838. * and not the options on the {@link ngModelOptions} directive from which they might have been
  26839. * obtained initially.
  26840. * </div>
  26841. *
  26842. * <div class="alert alert-danger">
  26843. * **Note:** it is not possible to override the `getterSetter` option.
  26844. * </div>
  26845. *
  26846. * @param {Object} options a hash of settings to override the previous options
  26847. *
  26848. */
  26849. $overrideModelOptions: function(options) {
  26850. this.$options = this.$options.createChild(options);
  26851. this.$$setUpdateOnEvents();
  26852. },
  26853. /**
  26854. * @ngdoc method
  26855. *
  26856. * @name ngModel.NgModelController#$processModelValue
  26857. * @description
  26858. *
  26859. * Runs the model -> view pipeline on the current
  26860. * {@link ngModel.NgModelController#$modelValue $modelValue}.
  26861. *
  26862. * The following actions are performed by this method:
  26863. *
  26864. * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters}
  26865. * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue}
  26866. * - the `ng-empty` or `ng-not-empty` class is set on the element
  26867. * - if the `$viewValue` has changed:
  26868. * - {@link ngModel.NgModelController#$render $render} is called on the control
  26869. * - the {@link ngModel.NgModelController#$validators $validators} are run and
  26870. * the validation status is set.
  26871. *
  26872. * This method is called by ngModel internally when the bound scope value changes.
  26873. * Application developers usually do not have to call this function themselves.
  26874. *
  26875. * This function can be used when the `$viewValue` or the rendered DOM value are not correctly
  26876. * formatted and the `$modelValue` must be run through the `$formatters` again.
  26877. *
  26878. * @example
  26879. * Consider a text input with an autocomplete list (for fruit), where the items are
  26880. * objects with a name and an id.
  26881. * A user enters `ap` and then selects `Apricot` from the list.
  26882. * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`,
  26883. * but the rendered value will still be `ap`.
  26884. * The widget can then call `ctrl.$processModelValue()` to run the model -> view
  26885. * pipeline again, which formats the object to the string `Apricot`,
  26886. * then updates the `$viewValue`, and finally renders it in the DOM.
  26887. *
  26888. * <example module="inputExample" name="ng-model-process">
  26889. <file name="index.html">
  26890. <div ng-controller="inputController" style="display: flex;">
  26891. <div style="margin-right: 30px;">
  26892. Search Fruit:
  26893. <basic-autocomplete items="items" on-select="selectedFruit = item"></basic-autocomplete>
  26894. </div>
  26895. <div>
  26896. Model:<br>
  26897. <pre>{{selectedFruit | json}}</pre>
  26898. </div>
  26899. </div>
  26900. </file>
  26901. <file name="app.js">
  26902. angular.module('inputExample', [])
  26903. .controller('inputController', function($scope) {
  26904. $scope.items = [
  26905. {name: 'Apricot', id: 443},
  26906. {name: 'Clementine', id: 972},
  26907. {name: 'Durian', id: 169},
  26908. {name: 'Jackfruit', id: 982},
  26909. {name: 'Strawberry', id: 863}
  26910. ];
  26911. })
  26912. .component('basicAutocomplete', {
  26913. bindings: {
  26914. items: '<',
  26915. onSelect: '&'
  26916. },
  26917. templateUrl: 'autocomplete.html',
  26918. controller: function($element, $scope) {
  26919. var that = this;
  26920. var ngModel;
  26921. that.$postLink = function() {
  26922. ngModel = $element.find('input').controller('ngModel');
  26923. ngModel.$formatters.push(function(value) {
  26924. return (value && value.name) || value;
  26925. });
  26926. ngModel.$parsers.push(function(value) {
  26927. var match = value;
  26928. for (var i = 0; i < that.items.length; i++) {
  26929. if (that.items[i].name === value) {
  26930. match = that.items[i];
  26931. break;
  26932. }
  26933. }
  26934. return match;
  26935. });
  26936. };
  26937. that.selectItem = function(item) {
  26938. ngModel.$setViewValue(item);
  26939. ngModel.$processModelValue();
  26940. that.onSelect({item: item});
  26941. };
  26942. }
  26943. });
  26944. </file>
  26945. <file name="autocomplete.html">
  26946. <div>
  26947. <input type="search" ng-model="$ctrl.searchTerm" />
  26948. <ul>
  26949. <li ng-repeat="item in $ctrl.items | filter:$ctrl.searchTerm">
  26950. <button ng-click="$ctrl.selectItem(item)">{{ item.name }}</button>
  26951. </li>
  26952. </ul>
  26953. </div>
  26954. </file>
  26955. * </example>
  26956. *
  26957. */
  26958. $processModelValue: function() {
  26959. var viewValue = this.$$format();
  26960. if (this.$viewValue !== viewValue) {
  26961. this.$$updateEmptyClasses(viewValue);
  26962. this.$viewValue = this.$$lastCommittedViewValue = viewValue;
  26963. this.$render();
  26964. // It is possible that model and view value have been updated during render
  26965. this.$$runValidators(this.$modelValue, this.$viewValue, noop);
  26966. }
  26967. },
  26968. /**
  26969. * This method is called internally to run the $formatters on the $modelValue
  26970. */
  26971. $$format: function() {
  26972. var formatters = this.$formatters,
  26973. idx = formatters.length;
  26974. var viewValue = this.$modelValue;
  26975. while (idx--) {
  26976. viewValue = formatters[idx](viewValue);
  26977. }
  26978. return viewValue;
  26979. },
  26980. /**
  26981. * This method is called internally when the bound scope value changes.
  26982. */
  26983. $$setModelValue: function(modelValue) {
  26984. this.$modelValue = this.$$rawModelValue = modelValue;
  26985. this.$$parserValid = undefined;
  26986. this.$processModelValue();
  26987. },
  26988. $$setUpdateOnEvents: function() {
  26989. if (this.$$updateEvents) {
  26990. this.$$element.off(this.$$updateEvents, this.$$updateEventHandler);
  26991. }
  26992. this.$$updateEvents = this.$options.getOption('updateOn');
  26993. if (this.$$updateEvents) {
  26994. this.$$element.on(this.$$updateEvents, this.$$updateEventHandler);
  26995. }
  26996. },
  26997. $$updateEventHandler: function(ev) {
  26998. this.$$debounceViewValueCommit(ev && ev.type);
  26999. }
  27000. };
  27001. function setupModelWatcher(ctrl) {
  27002. // model -> value
  27003. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  27004. // 1. scope value is 'a'
  27005. // 2. user enters 'b'
  27006. // 3. ng-change kicks in and reverts scope value to 'a'
  27007. // -> scope value did not change since the last digest as
  27008. // ng-change executes in apply phase
  27009. // 4. view should be changed back to 'a'
  27010. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  27011. var modelValue = ctrl.$$ngModelGet(scope);
  27012. // if scope model value and ngModel value are out of sync
  27013. // This cannot be moved to the action function, because it would not catch the
  27014. // case where the model is changed in the ngChange function or the model setter
  27015. if (modelValue !== ctrl.$modelValue &&
  27016. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  27017. // eslint-disable-next-line no-self-compare
  27018. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  27019. ) {
  27020. ctrl.$$setModelValue(modelValue);
  27021. }
  27022. return modelValue;
  27023. });
  27024. }
  27025. /**
  27026. * @ngdoc method
  27027. * @name ngModel.NgModelController#$setValidity
  27028. *
  27029. * @description
  27030. * Change the validity state, and notify the form.
  27031. *
  27032. * This method can be called within $parsers/$formatters or a custom validation implementation.
  27033. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  27034. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  27035. *
  27036. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  27037. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  27038. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  27039. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  27040. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  27041. * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.
  27042. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  27043. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  27044. * Skipped is used by AngularJS when validators do not run because of parse errors and
  27045. * when `$asyncValidators` do not run because any of the `$validators` failed.
  27046. */
  27047. addSetValidityMethod({
  27048. clazz: NgModelController,
  27049. set: function(object, property) {
  27050. object[property] = true;
  27051. },
  27052. unset: function(object, property) {
  27053. delete object[property];
  27054. }
  27055. });
  27056. /**
  27057. * @ngdoc directive
  27058. * @name ngModel
  27059. * @restrict A
  27060. * @priority 1
  27061. * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to.
  27062. *
  27063. * @description
  27064. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  27065. * property on the scope using {@link ngModel.NgModelController NgModelController},
  27066. * which is created and exposed by this directive.
  27067. *
  27068. * `ngModel` is responsible for:
  27069. *
  27070. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  27071. * require.
  27072. * - Providing validation behavior (i.e. required, number, email, url).
  27073. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  27074. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  27075. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  27076. * - Registering the control with its parent {@link ng.directive:form form}.
  27077. *
  27078. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  27079. * current scope. If the property doesn't already exist on this scope, it will be created
  27080. * implicitly and added to the scope.
  27081. *
  27082. * For best practices on using `ngModel`, see:
  27083. *
  27084. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  27085. *
  27086. * For basic examples, how to use `ngModel`, see:
  27087. *
  27088. * - {@link ng.directive:input input}
  27089. * - {@link input[text] text}
  27090. * - {@link input[checkbox] checkbox}
  27091. * - {@link input[radio] radio}
  27092. * - {@link input[number] number}
  27093. * - {@link input[email] email}
  27094. * - {@link input[url] url}
  27095. * - {@link input[date] date}
  27096. * - {@link input[datetime-local] datetime-local}
  27097. * - {@link input[time] time}
  27098. * - {@link input[month] month}
  27099. * - {@link input[week] week}
  27100. * - {@link ng.directive:select select}
  27101. * - {@link ng.directive:textarea textarea}
  27102. *
  27103. * ## Complex Models (objects or collections)
  27104. *
  27105. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27106. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  27107. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  27108. *
  27109. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  27110. *
  27111. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  27112. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  27113. * if the select is given the `multiple` attribute.
  27114. *
  27115. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  27116. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  27117. * not trigger a re-rendering of the model.
  27118. *
  27119. * ## CSS classes
  27120. * The following CSS classes are added and removed on the associated input/select/textarea element
  27121. * depending on the validity of the model.
  27122. *
  27123. * - `ng-valid`: the model is valid
  27124. * - `ng-invalid`: the model is invalid
  27125. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  27126. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  27127. * - `ng-pristine`: the control hasn't been interacted with yet
  27128. * - `ng-dirty`: the control has been interacted with
  27129. * - `ng-touched`: the control has been blurred
  27130. * - `ng-untouched`: the control hasn't been blurred
  27131. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  27132. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  27133. * by the {@link ngModel.NgModelController#$isEmpty} method
  27134. * - `ng-not-empty`: the view contains a non-empty value
  27135. *
  27136. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  27137. *
  27138. * @animations
  27139. * Animations within models are triggered when any of the associated CSS classes are added and removed
  27140. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  27141. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  27142. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  27143. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  27144. *
  27145. * The following example shows a simple way to utilize CSS transitions to style an input element
  27146. * that has been rendered as invalid after it has been validated:
  27147. *
  27148. * <pre>
  27149. * //be sure to include ngAnimate as a module to hook into more
  27150. * //advanced animations
  27151. * .my-input {
  27152. * transition:0.5s linear all;
  27153. * background: white;
  27154. * }
  27155. * .my-input.ng-invalid {
  27156. * background: red;
  27157. * color:white;
  27158. * }
  27159. * </pre>
  27160. *
  27161. * @example
  27162. * ### Basic Usage
  27163. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  27164. <file name="index.html">
  27165. <script>
  27166. angular.module('inputExample', [])
  27167. .controller('ExampleController', ['$scope', function($scope) {
  27168. $scope.val = '1';
  27169. }]);
  27170. </script>
  27171. <style>
  27172. .my-input {
  27173. transition:all linear 0.5s;
  27174. background: transparent;
  27175. }
  27176. .my-input.ng-invalid {
  27177. color:white;
  27178. background: red;
  27179. }
  27180. </style>
  27181. <p id="inputDescription">
  27182. Update input to see transitions when valid/invalid.
  27183. Integer is a valid value.
  27184. </p>
  27185. <form name="testForm" ng-controller="ExampleController">
  27186. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  27187. aria-describedby="inputDescription" />
  27188. </form>
  27189. </file>
  27190. * </example>
  27191. *
  27192. * @example
  27193. * ### Binding to a getter/setter
  27194. *
  27195. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  27196. * function that returns a representation of the model when called with zero arguments, and sets
  27197. * the internal state of a model when called with an argument. It's sometimes useful to use this
  27198. * for models that have an internal representation that's different from what the model exposes
  27199. * to the view.
  27200. *
  27201. * <div class="alert alert-success">
  27202. * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more
  27203. * frequently than other parts of your code.
  27204. * </div>
  27205. *
  27206. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  27207. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  27208. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  27209. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  27210. *
  27211. * The following example shows how to use `ngModel` with a getter/setter:
  27212. *
  27213. * @example
  27214. * <example name="ngModel-getter-setter" module="getterSetterExample">
  27215. <file name="index.html">
  27216. <div ng-controller="ExampleController">
  27217. <form name="userForm">
  27218. <label>Name:
  27219. <input type="text" name="userName"
  27220. ng-model="user.name"
  27221. ng-model-options="{ getterSetter: true }" />
  27222. </label>
  27223. </form>
  27224. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  27225. </div>
  27226. </file>
  27227. <file name="app.js">
  27228. angular.module('getterSetterExample', [])
  27229. .controller('ExampleController', ['$scope', function($scope) {
  27230. var _name = 'Brian';
  27231. $scope.user = {
  27232. name: function(newName) {
  27233. // Note that newName can be undefined for two reasons:
  27234. // 1. Because it is called as a getter and thus called with no arguments
  27235. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  27236. // input is invalid
  27237. return arguments.length ? (_name = newName) : _name;
  27238. }
  27239. };
  27240. }]);
  27241. </file>
  27242. * </example>
  27243. */
  27244. var ngModelDirective = ['$rootScope', function($rootScope) {
  27245. return {
  27246. restrict: 'A',
  27247. require: ['ngModel', '^?form', '^?ngModelOptions'],
  27248. controller: NgModelController,
  27249. // Prelink needs to run before any input directive
  27250. // so that we can set the NgModelOptions in NgModelController
  27251. // before anyone else uses it.
  27252. priority: 1,
  27253. compile: function ngModelCompile(element) {
  27254. // Setup initial state of the control
  27255. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  27256. return {
  27257. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  27258. var modelCtrl = ctrls[0],
  27259. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  27260. optionsCtrl = ctrls[2];
  27261. if (optionsCtrl) {
  27262. modelCtrl.$options = optionsCtrl.$options;
  27263. }
  27264. modelCtrl.$$initGetterSetters();
  27265. // notify others, especially parent forms
  27266. formCtrl.$addControl(modelCtrl);
  27267. attr.$observe('name', function(newValue) {
  27268. if (modelCtrl.$name !== newValue) {
  27269. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  27270. }
  27271. });
  27272. scope.$on('$destroy', function() {
  27273. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  27274. });
  27275. },
  27276. post: function ngModelPostLink(scope, element, attr, ctrls) {
  27277. var modelCtrl = ctrls[0];
  27278. modelCtrl.$$setUpdateOnEvents();
  27279. function setTouched() {
  27280. modelCtrl.$setTouched();
  27281. }
  27282. element.on('blur', function() {
  27283. if (modelCtrl.$touched) return;
  27284. if ($rootScope.$$phase) {
  27285. scope.$evalAsync(setTouched);
  27286. } else {
  27287. scope.$apply(setTouched);
  27288. }
  27289. });
  27290. }
  27291. };
  27292. }
  27293. };
  27294. }];
  27295. /* exported defaultModelOptions */
  27296. var defaultModelOptions;
  27297. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  27298. /**
  27299. * @ngdoc type
  27300. * @name ModelOptions
  27301. * @description
  27302. * A container for the options set by the {@link ngModelOptions} directive
  27303. */
  27304. function ModelOptions(options) {
  27305. this.$$options = options;
  27306. }
  27307. ModelOptions.prototype = {
  27308. /**
  27309. * @ngdoc method
  27310. * @name ModelOptions#getOption
  27311. * @param {string} name the name of the option to retrieve
  27312. * @returns {*} the value of the option
  27313. * @description
  27314. * Returns the value of the given option
  27315. */
  27316. getOption: function(name) {
  27317. return this.$$options[name];
  27318. },
  27319. /**
  27320. * @ngdoc method
  27321. * @name ModelOptions#createChild
  27322. * @param {Object} options a hash of options for the new child that will override the parent's options
  27323. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  27324. */
  27325. createChild: function(options) {
  27326. var inheritAll = false;
  27327. // make a shallow copy
  27328. options = extend({}, options);
  27329. // Inherit options from the parent if specified by the value `"$inherit"`
  27330. forEach(options, /* @this */ function(option, key) {
  27331. if (option === '$inherit') {
  27332. if (key === '*') {
  27333. inheritAll = true;
  27334. } else {
  27335. options[key] = this.$$options[key];
  27336. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  27337. if (key === 'updateOn') {
  27338. options.updateOnDefault = this.$$options.updateOnDefault;
  27339. }
  27340. }
  27341. } else {
  27342. if (key === 'updateOn') {
  27343. // If the `updateOn` property contains the `default` event then we have to remove
  27344. // it from the event list and set the `updateOnDefault` flag.
  27345. options.updateOnDefault = false;
  27346. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  27347. options.updateOnDefault = true;
  27348. return ' ';
  27349. }));
  27350. }
  27351. }
  27352. }, this);
  27353. if (inheritAll) {
  27354. // We have a property of the form: `"*": "$inherit"`
  27355. delete options['*'];
  27356. defaults(options, this.$$options);
  27357. }
  27358. // Finally add in any missing defaults
  27359. defaults(options, defaultModelOptions.$$options);
  27360. return new ModelOptions(options);
  27361. }
  27362. };
  27363. defaultModelOptions = new ModelOptions({
  27364. updateOn: '',
  27365. updateOnDefault: true,
  27366. debounce: 0,
  27367. getterSetter: false,
  27368. allowInvalid: false,
  27369. timezone: null
  27370. });
  27371. /**
  27372. * @ngdoc directive
  27373. * @name ngModelOptions
  27374. * @restrict A
  27375. * @priority 10
  27376. *
  27377. * @description
  27378. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  27379. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  27380. * directives will use the options of their nearest `ngModelOptions` ancestor.
  27381. *
  27382. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  27383. * an AngularJS expression. This expression should evaluate to an object, whose properties contain
  27384. * the settings. For example: `<div ng-model-options="{ debounce: 100 }"`.
  27385. *
  27386. * ## Inheriting Options
  27387. *
  27388. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  27389. * directive by giving it the value of `"$inherit"`.
  27390. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  27391. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  27392. * will be used.
  27393. *
  27394. * For example given the following fragment of HTML
  27395. *
  27396. *
  27397. * ```html
  27398. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27399. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  27400. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  27401. * </form>
  27402. * </div>
  27403. * ```
  27404. *
  27405. * the `input` element will have the following settings
  27406. *
  27407. * ```js
  27408. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  27409. * ```
  27410. *
  27411. * Notice that the `debounce` setting was not inherited and used the default value instead.
  27412. *
  27413. * You can specify that all undefined settings are automatically inherited from an ancestor by
  27414. * including a property with key of `"*"` and value of `"$inherit"`.
  27415. *
  27416. * For example given the following fragment of HTML
  27417. *
  27418. *
  27419. * ```html
  27420. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27421. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  27422. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  27423. * </form>
  27424. * </div>
  27425. * ```
  27426. *
  27427. * the `input` element will have the following settings
  27428. *
  27429. * ```js
  27430. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  27431. * ```
  27432. *
  27433. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  27434. *
  27435. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  27436. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  27437. *
  27438. *
  27439. * ## Triggering and debouncing model updates
  27440. *
  27441. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  27442. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  27443. * a timer expires; this timer will be reset after another change takes place.
  27444. *
  27445. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  27446. * be different from the value in the actual model. This means that if you update the model you
  27447. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  27448. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  27449. *
  27450. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  27451. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  27452. * important because `form` controllers are published to the related scope under the name in their
  27453. * `name` attribute.
  27454. *
  27455. * Any pending changes will take place immediately when an enclosing form is submitted via the
  27456. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  27457. * to have access to the updated model.
  27458. *
  27459. * ### Overriding immediate updates
  27460. *
  27461. * The following example shows how to override immediate updates. Changes on the inputs within the
  27462. * form will update the model only when the control loses focus (blur event). If `escape` key is
  27463. * pressed while the input field is focused, the value is reset to the value in the current model.
  27464. *
  27465. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  27466. * <file name="index.html">
  27467. * <div ng-controller="ExampleController">
  27468. * <form name="userForm">
  27469. * <label>
  27470. * Name:
  27471. * <input type="text" name="userName"
  27472. * ng-model="user.name"
  27473. * ng-model-options="{ updateOn: 'blur' }"
  27474. * ng-keyup="cancel($event)" />
  27475. * </label><br />
  27476. * <label>
  27477. * Other data:
  27478. * <input type="text" ng-model="user.data" />
  27479. * </label><br />
  27480. * </form>
  27481. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27482. * </div>
  27483. * </file>
  27484. * <file name="app.js">
  27485. * angular.module('optionsExample', [])
  27486. * .controller('ExampleController', ['$scope', function($scope) {
  27487. * $scope.user = { name: 'say', data: '' };
  27488. *
  27489. * $scope.cancel = function(e) {
  27490. * if (e.keyCode === 27) {
  27491. * $scope.userForm.userName.$rollbackViewValue();
  27492. * }
  27493. * };
  27494. * }]);
  27495. * </file>
  27496. * <file name="protractor.js" type="protractor">
  27497. * var model = element(by.binding('user.name'));
  27498. * var input = element(by.model('user.name'));
  27499. * var other = element(by.model('user.data'));
  27500. *
  27501. * it('should allow custom events', function() {
  27502. * input.sendKeys(' hello');
  27503. * input.click();
  27504. * expect(model.getText()).toEqual('say');
  27505. * other.click();
  27506. * expect(model.getText()).toEqual('say hello');
  27507. * });
  27508. *
  27509. * it('should $rollbackViewValue when model changes', function() {
  27510. * input.sendKeys(' hello');
  27511. * expect(input.getAttribute('value')).toEqual('say hello');
  27512. * input.sendKeys(protractor.Key.ESCAPE);
  27513. * expect(input.getAttribute('value')).toEqual('say');
  27514. * other.click();
  27515. * expect(model.getText()).toEqual('say');
  27516. * });
  27517. * </file>
  27518. * </example>
  27519. *
  27520. * ### Debouncing updates
  27521. *
  27522. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  27523. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  27524. *
  27525. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  27526. * <file name="index.html">
  27527. * <div ng-controller="ExampleController">
  27528. * <form name="userForm">
  27529. * Name:
  27530. * <input type="text" name="userName"
  27531. * ng-model="user.name"
  27532. * ng-model-options="{ debounce: 1000 }" />
  27533. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  27534. * </form>
  27535. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27536. * </div>
  27537. * </file>
  27538. * <file name="app.js">
  27539. * angular.module('optionsExample', [])
  27540. * .controller('ExampleController', ['$scope', function($scope) {
  27541. * $scope.user = { name: 'say' };
  27542. * }]);
  27543. * </file>
  27544. * </example>
  27545. *
  27546. *
  27547. * ## Model updates and validation
  27548. *
  27549. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  27550. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  27551. * the model will still be updated even if the value is invalid.
  27552. *
  27553. *
  27554. * ## Connecting to the scope
  27555. *
  27556. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  27557. * on the scope refers to a "getter/setter" function rather than the value itself.
  27558. *
  27559. * The following example shows how to bind to getter/setters:
  27560. *
  27561. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  27562. * <file name="index.html">
  27563. * <div ng-controller="ExampleController">
  27564. * <form name="userForm">
  27565. * <label>
  27566. * Name:
  27567. * <input type="text" name="userName"
  27568. * ng-model="user.name"
  27569. * ng-model-options="{ getterSetter: true }" />
  27570. * </label>
  27571. * </form>
  27572. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  27573. * </div>
  27574. * </file>
  27575. * <file name="app.js">
  27576. * angular.module('getterSetterExample', [])
  27577. * .controller('ExampleController', ['$scope', function($scope) {
  27578. * var _name = 'Brian';
  27579. * $scope.user = {
  27580. * name: function(newName) {
  27581. * return angular.isDefined(newName) ? (_name = newName) : _name;
  27582. * }
  27583. * };
  27584. * }]);
  27585. * </file>
  27586. * </example>
  27587. *
  27588. *
  27589. * ## Specifying timezones
  27590. *
  27591. * You can specify the timezone that date/time input directives expect by providing its name in the
  27592. * `timezone` property.
  27593. *
  27594. *
  27595. * ## Programmatically changing options
  27596. *
  27597. * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not
  27598. * watched for changes. However, it is possible to override the options on a single
  27599. * {@link ngModel.NgModelController} instance with
  27600. * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}.
  27601. *
  27602. *
  27603. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  27604. * and its descendents. Valid keys are:
  27605. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  27606. * events using an space delimited list. There is a special event called `default` that
  27607. * matches the default events belonging to the control. These are the events that are bound to
  27608. * the control, and when fired, update the `$viewValue` via `$setViewValue`.
  27609. *
  27610. * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event,
  27611. * since different control types use different default events.
  27612. *
  27613. * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates
  27614. * Triggering and debouncing model updates}.
  27615. *
  27616. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  27617. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  27618. * custom value for each event. For example:
  27619. * ```
  27620. * ng-model-options="{
  27621. * updateOn: 'default blur click',
  27622. * debounce: { 'default': 500, 'blur': 0 }
  27623. * }"
  27624. * ```
  27625. *
  27626. * "default" also applies to all events that are listed in `updateOn` but are not
  27627. * listed in `debounce`, i.e. "click" would also be debounced by 500 milliseconds.
  27628. *
  27629. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  27630. * not validate correctly instead of the default behavior of setting the model to undefined.
  27631. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  27632. * `ngModel` as getters/setters.
  27633. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  27634. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  27635. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  27636. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  27637. * If not specified, the timezone of the browser will be used.
  27638. *
  27639. */
  27640. var ngModelOptionsDirective = function() {
  27641. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  27642. function NgModelOptionsController($attrs, $scope) {
  27643. this.$$attrs = $attrs;
  27644. this.$$scope = $scope;
  27645. }
  27646. NgModelOptionsController.prototype = {
  27647. $onInit: function() {
  27648. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  27649. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  27650. this.$options = parentOptions.createChild(modelOptionsDefinition);
  27651. }
  27652. };
  27653. return {
  27654. restrict: 'A',
  27655. // ngModelOptions needs to run before ngModel and input directives
  27656. priority: 10,
  27657. require: {parentCtrl: '?^^ngModelOptions'},
  27658. bindToController: true,
  27659. controller: NgModelOptionsController
  27660. };
  27661. };
  27662. // shallow copy over values from `src` that are not already specified on `dst`
  27663. function defaults(dst, src) {
  27664. forEach(src, function(value, key) {
  27665. if (!isDefined(dst[key])) {
  27666. dst[key] = value;
  27667. }
  27668. });
  27669. }
  27670. /**
  27671. * @ngdoc directive
  27672. * @name ngNonBindable
  27673. * @restrict AC
  27674. * @priority 1000
  27675. * @element ANY
  27676. *
  27677. * @description
  27678. * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current
  27679. * DOM element, including directives on the element itself that have a lower priority than
  27680. * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives
  27681. * and bindings but which should be ignored by AngularJS. This could be the case if you have a site
  27682. * that displays snippets of code, for instance.
  27683. *
  27684. * @example
  27685. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  27686. * but the one wrapped in `ngNonBindable` is left alone.
  27687. *
  27688. <example name="ng-non-bindable">
  27689. <file name="index.html">
  27690. <div>Normal: {{1 + 2}}</div>
  27691. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  27692. </file>
  27693. <file name="protractor.js" type="protractor">
  27694. it('should check ng-non-bindable', function() {
  27695. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  27696. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  27697. });
  27698. </file>
  27699. </example>
  27700. */
  27701. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  27702. /* exported ngOptionsDirective */
  27703. /* global jqLiteRemove */
  27704. var ngOptionsMinErr = minErr('ngOptions');
  27705. /**
  27706. * @ngdoc directive
  27707. * @name ngOptions
  27708. * @restrict A
  27709. *
  27710. * @description
  27711. *
  27712. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  27713. * elements for the `<select>` element using the array or object obtained by evaluating the
  27714. * `ngOptions` comprehension expression.
  27715. *
  27716. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  27717. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  27718. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27719. * comprehension expression
  27720. * - reduced memory consumption by not creating a new scope for each repeated instance
  27721. * - increased render speed by creating the options in a documentFragment instead of individually
  27722. *
  27723. * When an item in the `<select>` menu is selected, the array element or object property
  27724. * represented by the selected option will be bound to the model identified by the `ngModel`
  27725. * directive.
  27726. *
  27727. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27728. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27729. * option. See example below for demonstration.
  27730. *
  27731. * ## Complex Models (objects or collections)
  27732. *
  27733. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27734. * binding the select to a model that is an object or a collection.
  27735. *
  27736. * One issue occurs if you want to preselect an option. For example, if you set
  27737. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  27738. * because the objects are not identical. So by default, you should always reference the item in your collection
  27739. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  27740. *
  27741. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  27742. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  27743. * collection items have an id property, you would `track by item.id`.
  27744. *
  27745. * A different issue with objects or collections is that ngModel won't detect if an object property or
  27746. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  27747. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  27748. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  27749. * has not changed identity, but only a property on the object or an item in the collection changes.
  27750. *
  27751. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  27752. * if the model is an array). This means that changing a property deeper than the first level inside the
  27753. * object/collection will not trigger a re-rendering.
  27754. *
  27755. * ## `select` **`as`**
  27756. *
  27757. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  27758. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  27759. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  27760. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  27761. *
  27762. *
  27763. * ### `select` **`as`** and **`track by`**
  27764. *
  27765. * <div class="alert alert-warning">
  27766. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  27767. * </div>
  27768. *
  27769. * Given this array of items on the $scope:
  27770. *
  27771. * ```js
  27772. * $scope.items = [{
  27773. * id: 1,
  27774. * label: 'aLabel',
  27775. * subItem: { name: 'aSubItem' }
  27776. * }, {
  27777. * id: 2,
  27778. * label: 'bLabel',
  27779. * subItem: { name: 'bSubItem' }
  27780. * }];
  27781. * ```
  27782. *
  27783. * This will work:
  27784. *
  27785. * ```html
  27786. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  27787. * ```
  27788. * ```js
  27789. * $scope.selected = $scope.items[0];
  27790. * ```
  27791. *
  27792. * but this will not work:
  27793. *
  27794. * ```html
  27795. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  27796. * ```
  27797. * ```js
  27798. * $scope.selected = $scope.items[0].subItem;
  27799. * ```
  27800. *
  27801. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  27802. * `items` array. Because the selected option has been set programmatically in the controller, the
  27803. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  27804. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  27805. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  27806. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  27807. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  27808. *
  27809. *
  27810. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  27811. * @param {comprehension_expression} ngOptions in one of the following forms:
  27812. *
  27813. * * for array data sources:
  27814. * * `label` **`for`** `value` **`in`** `array`
  27815. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  27816. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  27817. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  27818. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27819. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27820. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  27821. * (for including a filter with `track by`)
  27822. * * for object data sources:
  27823. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27824. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27825. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27826. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27827. * * `select` **`as`** `label` **`group by`** `group`
  27828. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27829. * * `select` **`as`** `label` **`disable when`** `disable`
  27830. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27831. *
  27832. * Where:
  27833. *
  27834. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  27835. * * `value`: local variable which will refer to each item in the `array` or each property value
  27836. * of `object` during iteration.
  27837. * * `key`: local variable which will refer to a property name in `object` during iteration.
  27838. * * `label`: The result of this expression will be the label for `<option>` element. The
  27839. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  27840. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  27841. * element. If not specified, `select` expression will default to `value`.
  27842. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27843. * DOM element.
  27844. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27845. * element. Return `true` to disable.
  27846. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27847. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27848. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27849. * even when the options are recreated (e.g. reloaded from the server).
  27850. * @param {string=} name Property name of the form under which the control is published.
  27851. * @param {string=} required The control is considered valid only if value is entered.
  27852. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  27853. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  27854. * `required` when you want to data-bind to the `required` attribute.
  27855. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  27856. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  27857. *
  27858. * @example
  27859. <example module="selectExample" name="select">
  27860. <file name="index.html">
  27861. <script>
  27862. angular.module('selectExample', [])
  27863. .controller('ExampleController', ['$scope', function($scope) {
  27864. $scope.colors = [
  27865. {name:'black', shade:'dark'},
  27866. {name:'white', shade:'light', notAnOption: true},
  27867. {name:'red', shade:'dark'},
  27868. {name:'blue', shade:'dark', notAnOption: true},
  27869. {name:'yellow', shade:'light', notAnOption: false}
  27870. ];
  27871. $scope.myColor = $scope.colors[2]; // red
  27872. }]);
  27873. </script>
  27874. <div ng-controller="ExampleController">
  27875. <ul>
  27876. <li ng-repeat="color in colors">
  27877. <label>Name: <input ng-model="color.name"></label>
  27878. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27879. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27880. </li>
  27881. <li>
  27882. <button ng-click="colors.push({})">add</button>
  27883. </li>
  27884. </ul>
  27885. <hr/>
  27886. <label>Color (null not allowed):
  27887. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27888. </label><br/>
  27889. <label>Color (null allowed):
  27890. <span class="nullable">
  27891. <select ng-model="myColor" ng-options="color.name for color in colors">
  27892. <option value="">-- choose color --</option>
  27893. </select>
  27894. </span></label><br/>
  27895. <label>Color grouped by shade:
  27896. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27897. </select>
  27898. </label><br/>
  27899. <label>Color grouped by shade, with some disabled:
  27900. <select ng-model="myColor"
  27901. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27902. </select>
  27903. </label><br/>
  27904. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27905. <br/>
  27906. <hr/>
  27907. Currently selected: {{ {selected_color:myColor} }}
  27908. <div style="border:solid 1px black; height:20px"
  27909. ng-style="{'background-color':myColor.name}">
  27910. </div>
  27911. </div>
  27912. </file>
  27913. <file name="protractor.js" type="protractor">
  27914. it('should check ng-options', function() {
  27915. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27916. element.all(by.model('myColor')).first().click();
  27917. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27918. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27919. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27920. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27921. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27922. });
  27923. </file>
  27924. </example>
  27925. */
  27926. /* eslint-disable max-len */
  27927. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27928. 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]+?))?$/;
  27929. // 1: value expression (valueFn)
  27930. // 2: label expression (displayFn)
  27931. // 3: group by expression (groupByFn)
  27932. // 4: disable when expression (disableWhenFn)
  27933. // 5: array item variable name
  27934. // 6: object item key variable name
  27935. // 7: object item value variable name
  27936. // 8: collection expression
  27937. // 9: track by expression
  27938. /* eslint-enable */
  27939. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27940. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27941. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27942. if (!(match)) {
  27943. throw ngOptionsMinErr('iexp',
  27944. 'Expected expression in form of ' +
  27945. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27946. ' but got \'{0}\'. Element: {1}',
  27947. optionsExp, startingTag(selectElement));
  27948. }
  27949. // Extract the parts from the ngOptions expression
  27950. // The variable name for the value of the item in the collection
  27951. var valueName = match[5] || match[7];
  27952. // The variable name for the key of the item in the collection
  27953. var keyName = match[6];
  27954. // An expression that generates the viewValue for an option if there is a label expression
  27955. var selectAs = / as /.test(match[0]) && match[1];
  27956. // An expression that is used to track the id of each object in the options collection
  27957. var trackBy = match[9];
  27958. // An expression that generates the viewValue for an option if there is no label expression
  27959. var valueFn = $parse(match[2] ? match[1] : valueName);
  27960. var selectAsFn = selectAs && $parse(selectAs);
  27961. var viewValueFn = selectAsFn || valueFn;
  27962. var trackByFn = trackBy && $parse(trackBy);
  27963. // Get the value by which we are going to track the option
  27964. // if we have a trackFn then use that (passing scope and locals)
  27965. // otherwise just hash the given viewValue
  27966. var getTrackByValueFn = trackBy ?
  27967. function(value, locals) { return trackByFn(scope, locals); } :
  27968. function getHashOfValue(value) { return hashKey(value); };
  27969. var getTrackByValue = function(value, key) {
  27970. return getTrackByValueFn(value, getLocals(value, key));
  27971. };
  27972. var displayFn = $parse(match[2] || match[1]);
  27973. var groupByFn = $parse(match[3] || '');
  27974. var disableWhenFn = $parse(match[4] || '');
  27975. var valuesFn = $parse(match[8]);
  27976. var locals = {};
  27977. var getLocals = keyName ? function(value, key) {
  27978. locals[keyName] = key;
  27979. locals[valueName] = value;
  27980. return locals;
  27981. } : function(value) {
  27982. locals[valueName] = value;
  27983. return locals;
  27984. };
  27985. function Option(selectValue, viewValue, label, group, disabled) {
  27986. this.selectValue = selectValue;
  27987. this.viewValue = viewValue;
  27988. this.label = label;
  27989. this.group = group;
  27990. this.disabled = disabled;
  27991. }
  27992. function getOptionValuesKeys(optionValues) {
  27993. var optionValuesKeys;
  27994. if (!keyName && isArrayLike(optionValues)) {
  27995. optionValuesKeys = optionValues;
  27996. } else {
  27997. // if object, extract keys, in enumeration order, unsorted
  27998. optionValuesKeys = [];
  27999. for (var itemKey in optionValues) {
  28000. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  28001. optionValuesKeys.push(itemKey);
  28002. }
  28003. }
  28004. }
  28005. return optionValuesKeys;
  28006. }
  28007. return {
  28008. trackBy: trackBy,
  28009. getTrackByValue: getTrackByValue,
  28010. getWatchables: $parse(valuesFn, function(optionValues) {
  28011. // Create a collection of things that we would like to watch (watchedArray)
  28012. // so that they can all be watched using a single $watchCollection
  28013. // that only runs the handler once if anything changes
  28014. var watchedArray = [];
  28015. optionValues = optionValues || [];
  28016. var optionValuesKeys = getOptionValuesKeys(optionValues);
  28017. var optionValuesLength = optionValuesKeys.length;
  28018. for (var index = 0; index < optionValuesLength; index++) {
  28019. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  28020. var value = optionValues[key];
  28021. var locals = getLocals(value, key);
  28022. var selectValue = getTrackByValueFn(value, locals);
  28023. watchedArray.push(selectValue);
  28024. // Only need to watch the displayFn if there is a specific label expression
  28025. if (match[2] || match[1]) {
  28026. var label = displayFn(scope, locals);
  28027. watchedArray.push(label);
  28028. }
  28029. // Only need to watch the disableWhenFn if there is a specific disable expression
  28030. if (match[4]) {
  28031. var disableWhen = disableWhenFn(scope, locals);
  28032. watchedArray.push(disableWhen);
  28033. }
  28034. }
  28035. return watchedArray;
  28036. }),
  28037. getOptions: function() {
  28038. var optionItems = [];
  28039. var selectValueMap = {};
  28040. // The option values were already computed in the `getWatchables` fn,
  28041. // which must have been called to trigger `getOptions`
  28042. var optionValues = valuesFn(scope) || [];
  28043. var optionValuesKeys = getOptionValuesKeys(optionValues);
  28044. var optionValuesLength = optionValuesKeys.length;
  28045. for (var index = 0; index < optionValuesLength; index++) {
  28046. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  28047. var value = optionValues[key];
  28048. var locals = getLocals(value, key);
  28049. var viewValue = viewValueFn(scope, locals);
  28050. var selectValue = getTrackByValueFn(viewValue, locals);
  28051. var label = displayFn(scope, locals);
  28052. var group = groupByFn(scope, locals);
  28053. var disabled = disableWhenFn(scope, locals);
  28054. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  28055. optionItems.push(optionItem);
  28056. selectValueMap[selectValue] = optionItem;
  28057. }
  28058. return {
  28059. items: optionItems,
  28060. selectValueMap: selectValueMap,
  28061. getOptionFromViewValue: function(value) {
  28062. return selectValueMap[getTrackByValue(value)];
  28063. },
  28064. getViewValueFromOption: function(option) {
  28065. // If the viewValue could be an object that may be mutated by the application,
  28066. // we need to make a copy and not return the reference to the value on the option.
  28067. return trackBy ? copy(option.viewValue) : option.viewValue;
  28068. }
  28069. };
  28070. }
  28071. };
  28072. }
  28073. // Support: IE 9 only
  28074. // We can't just jqLite('<option>') since jqLite is not smart enough
  28075. // to create it in <select> and IE barfs otherwise.
  28076. var optionTemplate = window.document.createElement('option'),
  28077. optGroupTemplate = window.document.createElement('optgroup');
  28078. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  28079. var selectCtrl = ctrls[0];
  28080. var ngModelCtrl = ctrls[1];
  28081. var multiple = attr.multiple;
  28082. // The emptyOption allows the application developer to provide their own custom "empty"
  28083. // option when the viewValue does not match any of the option values.
  28084. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  28085. if (children[i].value === '') {
  28086. selectCtrl.hasEmptyOption = true;
  28087. selectCtrl.emptyOption = children.eq(i);
  28088. break;
  28089. }
  28090. }
  28091. // The empty option will be compiled and rendered before we first generate the options
  28092. selectElement.empty();
  28093. var providedEmptyOption = !!selectCtrl.emptyOption;
  28094. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  28095. unknownOption.val('?');
  28096. var options;
  28097. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  28098. // This stores the newly created options before they are appended to the select.
  28099. // Since the contents are removed from the fragment when it is appended,
  28100. // we only need to create it once.
  28101. var listFragment = $document[0].createDocumentFragment();
  28102. // Overwrite the implementation. ngOptions doesn't use hashes
  28103. selectCtrl.generateUnknownOptionValue = function(val) {
  28104. return '?';
  28105. };
  28106. // Update the controller methods for multiple selectable options
  28107. if (!multiple) {
  28108. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  28109. // The options might not be defined yet when ngModel tries to render
  28110. if (!options) return;
  28111. var selectedOption = selectElement[0].options[selectElement[0].selectedIndex];
  28112. var option = options.getOptionFromViewValue(value);
  28113. // Make sure to remove the selected attribute from the previously selected option
  28114. // Otherwise, screen readers might get confused
  28115. if (selectedOption) selectedOption.removeAttribute('selected');
  28116. if (option) {
  28117. // Don't update the option when it is already selected.
  28118. // For example, the browser will select the first option by default. In that case,
  28119. // most properties are set automatically - except the `selected` attribute, which we
  28120. // set always
  28121. if (selectElement[0].value !== option.selectValue) {
  28122. selectCtrl.removeUnknownOption();
  28123. selectElement[0].value = option.selectValue;
  28124. option.element.selected = true;
  28125. }
  28126. option.element.setAttribute('selected', 'selected');
  28127. } else {
  28128. selectCtrl.selectUnknownOrEmptyOption(value);
  28129. }
  28130. };
  28131. selectCtrl.readValue = function readNgOptionsValue() {
  28132. var selectedOption = options.selectValueMap[selectElement.val()];
  28133. if (selectedOption && !selectedOption.disabled) {
  28134. selectCtrl.unselectEmptyOption();
  28135. selectCtrl.removeUnknownOption();
  28136. return options.getViewValueFromOption(selectedOption);
  28137. }
  28138. return null;
  28139. };
  28140. // If we are using `track by` then we must watch the tracked value on the model
  28141. // since ngModel only watches for object identity change
  28142. // FIXME: When a user selects an option, this watch will fire needlessly
  28143. if (ngOptions.trackBy) {
  28144. scope.$watch(
  28145. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  28146. function() { ngModelCtrl.$render(); }
  28147. );
  28148. }
  28149. } else {
  28150. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  28151. // The options might not be defined yet when ngModel tries to render
  28152. if (!options) return;
  28153. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  28154. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  28155. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  28156. options.items.forEach(function(option) {
  28157. if (option.element.selected && !includes(selectedOptions, option)) {
  28158. option.element.selected = false;
  28159. }
  28160. });
  28161. };
  28162. selectCtrl.readValue = function readNgOptionsMultiple() {
  28163. var selectedValues = selectElement.val() || [],
  28164. selections = [];
  28165. forEach(selectedValues, function(value) {
  28166. var option = options.selectValueMap[value];
  28167. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  28168. });
  28169. return selections;
  28170. };
  28171. // If we are using `track by` then we must watch these tracked values on the model
  28172. // since ngModel only watches for object identity change
  28173. if (ngOptions.trackBy) {
  28174. scope.$watchCollection(function() {
  28175. if (isArray(ngModelCtrl.$viewValue)) {
  28176. return ngModelCtrl.$viewValue.map(function(value) {
  28177. return ngOptions.getTrackByValue(value);
  28178. });
  28179. }
  28180. }, function() {
  28181. ngModelCtrl.$render();
  28182. });
  28183. }
  28184. }
  28185. if (providedEmptyOption) {
  28186. // compile the element since there might be bindings in it
  28187. $compile(selectCtrl.emptyOption)(scope);
  28188. selectElement.prepend(selectCtrl.emptyOption);
  28189. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  28190. // This means the empty option has currently no actual DOM node, probably because
  28191. // it has been modified by a transclusion directive.
  28192. selectCtrl.hasEmptyOption = false;
  28193. // Redefine the registerOption function, which will catch
  28194. // options that are added by ngIf etc. (rendering of the node is async because of
  28195. // lazy transclusion)
  28196. selectCtrl.registerOption = function(optionScope, optionEl) {
  28197. if (optionEl.val() === '') {
  28198. selectCtrl.hasEmptyOption = true;
  28199. selectCtrl.emptyOption = optionEl;
  28200. selectCtrl.emptyOption.removeClass('ng-scope');
  28201. // This ensures the new empty option is selected if previously no option was selected
  28202. ngModelCtrl.$render();
  28203. optionEl.on('$destroy', function() {
  28204. var needsRerender = selectCtrl.$isEmptyOptionSelected();
  28205. selectCtrl.hasEmptyOption = false;
  28206. selectCtrl.emptyOption = undefined;
  28207. if (needsRerender) ngModelCtrl.$render();
  28208. });
  28209. }
  28210. };
  28211. } else {
  28212. // remove the class, which is added automatically because we recompile the element and it
  28213. // becomes the compilation root
  28214. selectCtrl.emptyOption.removeClass('ng-scope');
  28215. }
  28216. }
  28217. // We will re-render the option elements if the option values or labels change
  28218. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  28219. // ------------------------------------------------------------------ //
  28220. function addOptionElement(option, parent) {
  28221. var optionElement = optionTemplate.cloneNode(false);
  28222. parent.appendChild(optionElement);
  28223. updateOptionElement(option, optionElement);
  28224. }
  28225. function getAndUpdateSelectedOption(viewValue) {
  28226. var option = options.getOptionFromViewValue(viewValue);
  28227. var element = option && option.element;
  28228. if (element && !element.selected) element.selected = true;
  28229. return option;
  28230. }
  28231. function updateOptionElement(option, element) {
  28232. option.element = element;
  28233. element.disabled = option.disabled;
  28234. // Support: IE 11 only, Edge 12-13 only
  28235. // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive
  28236. // selects in certain circumstances when multiple selects are next to each other and display
  28237. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  28238. // See https://github.com/angular/angular.js/issues/11314 for more info.
  28239. // This is unfortunately untestable with unit / e2e tests
  28240. if (option.label !== element.label) {
  28241. element.label = option.label;
  28242. element.textContent = option.label;
  28243. }
  28244. element.value = option.selectValue;
  28245. }
  28246. function updateOptions() {
  28247. var previousValue = options && selectCtrl.readValue();
  28248. // We must remove all current options, but cannot simply set innerHTML = null
  28249. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  28250. // must preserve.
  28251. // Instead, iterate over the current option elements and remove them or their optgroup
  28252. // parents
  28253. if (options) {
  28254. for (var i = options.items.length - 1; i >= 0; i--) {
  28255. var option = options.items[i];
  28256. if (isDefined(option.group)) {
  28257. jqLiteRemove(option.element.parentNode);
  28258. } else {
  28259. jqLiteRemove(option.element);
  28260. }
  28261. }
  28262. }
  28263. options = ngOptions.getOptions();
  28264. var groupElementMap = {};
  28265. options.items.forEach(function addOption(option) {
  28266. var groupElement;
  28267. if (isDefined(option.group)) {
  28268. // This option is to live in a group
  28269. // See if we have already created this group
  28270. groupElement = groupElementMap[option.group];
  28271. if (!groupElement) {
  28272. groupElement = optGroupTemplate.cloneNode(false);
  28273. listFragment.appendChild(groupElement);
  28274. // Update the label on the group element
  28275. // "null" is special cased because of Safari
  28276. groupElement.label = option.group === null ? 'null' : option.group;
  28277. // Store it for use later
  28278. groupElementMap[option.group] = groupElement;
  28279. }
  28280. addOptionElement(option, groupElement);
  28281. } else {
  28282. // This option is not in a group
  28283. addOptionElement(option, listFragment);
  28284. }
  28285. });
  28286. selectElement[0].appendChild(listFragment);
  28287. ngModelCtrl.$render();
  28288. // Check to see if the value has changed due to the update to the options
  28289. if (!ngModelCtrl.$isEmpty(previousValue)) {
  28290. var nextValue = selectCtrl.readValue();
  28291. var isNotPrimitive = ngOptions.trackBy || multiple;
  28292. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  28293. ngModelCtrl.$setViewValue(nextValue);
  28294. ngModelCtrl.$render();
  28295. }
  28296. }
  28297. }
  28298. }
  28299. return {
  28300. restrict: 'A',
  28301. terminal: true,
  28302. require: ['select', 'ngModel'],
  28303. link: {
  28304. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  28305. // Deactivate the SelectController.register method to prevent
  28306. // option directives from accidentally registering themselves
  28307. // (and unwanted $destroy handlers etc.)
  28308. ctrls[0].registerOption = noop;
  28309. },
  28310. post: ngOptionsPostLink
  28311. }
  28312. };
  28313. }];
  28314. /**
  28315. * @ngdoc directive
  28316. * @name ngPluralize
  28317. * @restrict EA
  28318. *
  28319. * @description
  28320. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  28321. * These rules are bundled with angular.js, but can be overridden
  28322. * (see {@link guide/i18n AngularJS i18n} dev guide). You configure ngPluralize directive
  28323. * by specifying the mappings between
  28324. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  28325. * and the strings to be displayed.
  28326. *
  28327. * ## Plural categories and explicit number rules
  28328. * There are two
  28329. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  28330. * in AngularJS's default en-US locale: "one" and "other".
  28331. *
  28332. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  28333. * any number that is not 1), an explicit number rule can only match one number. For example, the
  28334. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  28335. * and explicit number rules throughout the rest of this documentation.
  28336. *
  28337. * ## Configuring ngPluralize
  28338. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  28339. * You can also provide an optional attribute, `offset`.
  28340. *
  28341. * The value of the `count` attribute can be either a string or an {@link guide/expression
  28342. * AngularJS expression}; these are evaluated on the current scope for its bound value.
  28343. *
  28344. * The `when` attribute specifies the mappings between plural categories and the actual
  28345. * string to be displayed. The value of the attribute should be a JSON object.
  28346. *
  28347. * The following example shows how to configure ngPluralize:
  28348. *
  28349. * ```html
  28350. * <ng-pluralize count="personCount"
  28351. when="{'0': 'Nobody is viewing.',
  28352. * 'one': '1 person is viewing.',
  28353. * 'other': '{} people are viewing.'}">
  28354. * </ng-pluralize>
  28355. *```
  28356. *
  28357. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  28358. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  28359. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  28360. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  28361. * show "a dozen people are viewing".
  28362. *
  28363. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  28364. * into pluralized strings. In the previous example, AngularJS will replace `{}` with
  28365. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  28366. * for <span ng-non-bindable>{{numberExpression}}</span>.
  28367. *
  28368. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  28369. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  28370. *
  28371. * ## Configuring ngPluralize with offset
  28372. * The `offset` attribute allows further customization of pluralized text, which can result in
  28373. * a better user experience. For example, instead of the message "4 people are viewing this document",
  28374. * you might display "John, Kate and 2 others are viewing this document".
  28375. * The offset attribute allows you to offset a number by any desired value.
  28376. * Let's take a look at an example:
  28377. *
  28378. * ```html
  28379. * <ng-pluralize count="personCount" offset=2
  28380. * when="{'0': 'Nobody is viewing.',
  28381. * '1': '{{person1}} is viewing.',
  28382. * '2': '{{person1}} and {{person2}} are viewing.',
  28383. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28384. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28385. * </ng-pluralize>
  28386. * ```
  28387. *
  28388. * Notice that we are still using two plural categories(one, other), but we added
  28389. * three explicit number rules 0, 1 and 2.
  28390. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  28391. * When three people view the document, no explicit number rule is found, so
  28392. * an offset of 2 is taken off 3, and AngularJS uses 1 to decide the plural category.
  28393. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  28394. * is shown.
  28395. *
  28396. * Note that when you specify offsets, you must provide explicit number rules for
  28397. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  28398. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  28399. * plural categories "one" and "other".
  28400. *
  28401. * @param {string|expression} count The variable to be bound to.
  28402. * @param {string} when The mapping between plural category to its corresponding strings.
  28403. * @param {number=} offset Offset to deduct from the total number.
  28404. *
  28405. * @example
  28406. <example module="pluralizeExample" name="ng-pluralize">
  28407. <file name="index.html">
  28408. <script>
  28409. angular.module('pluralizeExample', [])
  28410. .controller('ExampleController', ['$scope', function($scope) {
  28411. $scope.person1 = 'Igor';
  28412. $scope.person2 = 'Misko';
  28413. $scope.personCount = 1;
  28414. }]);
  28415. </script>
  28416. <div ng-controller="ExampleController">
  28417. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  28418. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  28419. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  28420. <!--- Example with simple pluralization rules for en locale --->
  28421. Without Offset:
  28422. <ng-pluralize count="personCount"
  28423. when="{'0': 'Nobody is viewing.',
  28424. 'one': '1 person is viewing.',
  28425. 'other': '{} people are viewing.'}">
  28426. </ng-pluralize><br>
  28427. <!--- Example with offset --->
  28428. With Offset(2):
  28429. <ng-pluralize count="personCount" offset=2
  28430. when="{'0': 'Nobody is viewing.',
  28431. '1': '{{person1}} is viewing.',
  28432. '2': '{{person1}} and {{person2}} are viewing.',
  28433. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28434. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28435. </ng-pluralize>
  28436. </div>
  28437. </file>
  28438. <file name="protractor.js" type="protractor">
  28439. it('should show correct pluralized string', function() {
  28440. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  28441. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28442. var countInput = element(by.model('personCount'));
  28443. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  28444. expect(withOffset.getText()).toEqual('Igor is viewing.');
  28445. countInput.clear();
  28446. countInput.sendKeys('0');
  28447. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  28448. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  28449. countInput.clear();
  28450. countInput.sendKeys('2');
  28451. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  28452. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  28453. countInput.clear();
  28454. countInput.sendKeys('3');
  28455. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  28456. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  28457. countInput.clear();
  28458. countInput.sendKeys('4');
  28459. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  28460. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  28461. });
  28462. it('should show data-bound names', function() {
  28463. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28464. var personCount = element(by.model('personCount'));
  28465. var person1 = element(by.model('person1'));
  28466. var person2 = element(by.model('person2'));
  28467. personCount.clear();
  28468. personCount.sendKeys('4');
  28469. person1.clear();
  28470. person1.sendKeys('Di');
  28471. person2.clear();
  28472. person2.sendKeys('Vojta');
  28473. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  28474. });
  28475. </file>
  28476. </example>
  28477. */
  28478. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  28479. var BRACE = /{}/g,
  28480. IS_WHEN = /^when(Minus)?(.+)$/;
  28481. return {
  28482. link: function(scope, element, attr) {
  28483. var numberExp = attr.count,
  28484. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  28485. offset = attr.offset || 0,
  28486. whens = scope.$eval(whenExp) || {},
  28487. whensExpFns = {},
  28488. startSymbol = $interpolate.startSymbol(),
  28489. endSymbol = $interpolate.endSymbol(),
  28490. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  28491. watchRemover = angular.noop,
  28492. lastCount;
  28493. forEach(attr, function(expression, attributeName) {
  28494. var tmpMatch = IS_WHEN.exec(attributeName);
  28495. if (tmpMatch) {
  28496. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  28497. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  28498. }
  28499. });
  28500. forEach(whens, function(expression, key) {
  28501. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  28502. });
  28503. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  28504. var count = parseFloat(newVal);
  28505. var countIsNaN = isNumberNaN(count);
  28506. if (!countIsNaN && !(count in whens)) {
  28507. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  28508. // Otherwise, check it against pluralization rules in $locale service.
  28509. count = $locale.pluralCat(count - offset);
  28510. }
  28511. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  28512. // In JS `NaN !== NaN`, so we have to explicitly check.
  28513. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  28514. watchRemover();
  28515. var whenExpFn = whensExpFns[count];
  28516. if (isUndefined(whenExpFn)) {
  28517. if (newVal != null) {
  28518. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  28519. }
  28520. watchRemover = noop;
  28521. updateElementText();
  28522. } else {
  28523. watchRemover = scope.$watch(whenExpFn, updateElementText);
  28524. }
  28525. lastCount = count;
  28526. }
  28527. });
  28528. function updateElementText(newText) {
  28529. element.text(newText || '');
  28530. }
  28531. }
  28532. };
  28533. }];
  28534. /* exported ngRepeatDirective */
  28535. /**
  28536. * @ngdoc directive
  28537. * @name ngRepeat
  28538. * @multiElement
  28539. * @restrict A
  28540. *
  28541. * @description
  28542. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  28543. * instance gets its own scope, where the given loop variable is set to the current collection item,
  28544. * and `$index` is set to the item index or key.
  28545. *
  28546. * Special properties are exposed on the local scope of each template instance, including:
  28547. *
  28548. * | Variable | Type | Details |
  28549. * |-----------|-----------------|-----------------------------------------------------------------------------|
  28550. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  28551. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  28552. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  28553. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  28554. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  28555. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  28556. *
  28557. * <div class="alert alert-info">
  28558. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  28559. * This may be useful when, for instance, nesting ngRepeats.
  28560. * </div>
  28561. *
  28562. *
  28563. * ## Iterating over object properties
  28564. *
  28565. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  28566. * syntax:
  28567. *
  28568. * ```js
  28569. * <div ng-repeat="(key, value) in myObj"> ... </div>
  28570. * ```
  28571. *
  28572. * However, there are a few limitations compared to array iteration:
  28573. *
  28574. * - The JavaScript specification does not define the order of keys
  28575. * returned for an object, so AngularJS relies on the order returned by the browser
  28576. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  28577. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  28578. * and reinstated. See the
  28579. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  28580. *
  28581. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  28582. * it's a prefix used by AngularJS for public (`$`) and private (`$$`) properties.
  28583. *
  28584. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  28585. * objects, and will throw an error if used with one.
  28586. *
  28587. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  28588. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  28589. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  28590. * or implement a `$watch` on the object yourself.
  28591. *
  28592. *
  28593. * ## Tracking and Duplicates
  28594. *
  28595. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  28596. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  28597. *
  28598. * * When an item is added, a new instance of the template is added to the DOM.
  28599. * * When an item is removed, its template instance is removed from the DOM.
  28600. * * When items are reordered, their respective templates are reordered in the DOM.
  28601. *
  28602. * To minimize creation of DOM elements, `ngRepeat` uses a function
  28603. * to "keep track" of all items in the collection and their corresponding DOM elements.
  28604. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  28605. * already have DOM elements, and will not re-render them.
  28606. *
  28607. * All different types of tracking functions, their syntax, and and their support for duplicate
  28608. * items in collections can be found in the
  28609. * {@link ngRepeat#ngRepeat-arguments ngRepeat expression description}.
  28610. *
  28611. * <div class="alert alert-success">
  28612. * **Best Practice:** If you are working with objects that have a unique identifier property, you
  28613. * should track by this identifier instead of the object instance,
  28614. * e.g. `item in items track by item.id`.
  28615. * Should you reload your data later, `ngRepeat` will not have to rebuild the DOM elements for items
  28616. * it has already rendered, even if the JavaScript objects in the collection have been substituted
  28617. * for new ones. For large collections, this significantly improves rendering performance.
  28618. * </div>
  28619. *
  28620. * ### Effects of DOM Element re-use
  28621. *
  28622. * When DOM elements are re-used, ngRepeat updates the scope for the element, which will
  28623. * automatically update any active bindings on the template. However, other
  28624. * functionality will not be updated, because the element is not re-created:
  28625. *
  28626. * - Directives are not re-compiled
  28627. * - {@link guide/expression#one-time-binding one-time expressions} on the repeated template are not
  28628. * updated if they have stabilized.
  28629. *
  28630. * The above affects all kinds of element re-use due to tracking, but may be especially visible
  28631. * when tracking by `$index` due to the way ngRepeat re-uses elements.
  28632. *
  28633. * The following example shows the effects of different actions with tracking:
  28634. <example module="ngRepeat" name="ngRepeat-tracking" deps="angular-animate.js" animations="true">
  28635. <file name="script.js">
  28636. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28637. var friends = [
  28638. {name:'John', age:25},
  28639. {name:'Mary', age:40},
  28640. {name:'Peter', age:85}
  28641. ];
  28642. $scope.removeFirst = function() {
  28643. $scope.friends.shift();
  28644. };
  28645. $scope.updateAge = function() {
  28646. $scope.friends.forEach(function(el) {
  28647. el.age = el.age + 5;
  28648. });
  28649. };
  28650. $scope.copy = function() {
  28651. $scope.friends = angular.copy($scope.friends);
  28652. };
  28653. $scope.reset = function() {
  28654. $scope.friends = angular.copy(friends);
  28655. };
  28656. $scope.reset();
  28657. });
  28658. </file>
  28659. <file name="index.html">
  28660. <div ng-controller="repeatController">
  28661. <ol>
  28662. <li>When you click "Update Age", only the first list updates the age, because all others have
  28663. a one-time binding on the age property. If you then click "Copy", the current friend list
  28664. is copied, and now the second list updates the age, because the identity of the collection items
  28665. has changed and the list must be re-rendered. The 3rd and 4th list stay the same, because all the
  28666. items are already known according to their tracking functions.
  28667. </li>
  28668. <li>When you click "Remove First", the 4th list has the wrong age on both remaining items. This is
  28669. due to tracking by $index: when the first collection item is removed, ngRepeat reuses the first
  28670. DOM element for the new first collection item, and so on. Since the age property is one-time
  28671. bound, the value remains from the collection item which was previously at this index.
  28672. </li>
  28673. </ol>
  28674. <button ng-click="removeFirst()">Remove First</button>
  28675. <button ng-click="updateAge()">Update Age</button>
  28676. <button ng-click="copy()">Copy</button>
  28677. <br><button ng-click="reset()">Reset List</button>
  28678. <br>
  28679. <code>track by $id(friend)</code> (default):
  28680. <ul class="example-animate-container">
  28681. <li class="animate-repeat" ng-repeat="friend in friends">
  28682. {{friend.name}} is {{friend.age}} years old.
  28683. </li>
  28684. </ul>
  28685. <code>track by $id(friend)</code> (default), with age one-time binding:
  28686. <ul class="example-animate-container">
  28687. <li class="animate-repeat" ng-repeat="friend in friends">
  28688. {{friend.name}} is {{::friend.age}} years old.
  28689. </li>
  28690. </ul>
  28691. <code>track by friend.name</code>, with age one-time binding:
  28692. <ul class="example-animate-container">
  28693. <li class="animate-repeat" ng-repeat="friend in friends track by friend.name">
  28694. {{friend.name}} is {{::friend.age}} years old.
  28695. </li>
  28696. </ul>
  28697. <code>track by $index</code>, with age one-time binding:
  28698. <ul class="example-animate-container">
  28699. <li class="animate-repeat" ng-repeat="friend in friends track by $index">
  28700. {{friend.name}} is {{::friend.age}} years old.
  28701. </li>
  28702. </ul>
  28703. </div>
  28704. </file>
  28705. <file name="animations.css">
  28706. .example-animate-container {
  28707. background:white;
  28708. border:1px solid black;
  28709. list-style:none;
  28710. margin:0;
  28711. padding:0 10px;
  28712. }
  28713. .animate-repeat {
  28714. line-height:30px;
  28715. list-style:none;
  28716. box-sizing:border-box;
  28717. }
  28718. .animate-repeat.ng-move,
  28719. .animate-repeat.ng-enter,
  28720. .animate-repeat.ng-leave {
  28721. transition:all linear 0.5s;
  28722. }
  28723. .animate-repeat.ng-leave.ng-leave-active,
  28724. .animate-repeat.ng-move,
  28725. .animate-repeat.ng-enter {
  28726. opacity:0;
  28727. max-height:0;
  28728. }
  28729. .animate-repeat.ng-leave,
  28730. .animate-repeat.ng-move.ng-move-active,
  28731. .animate-repeat.ng-enter.ng-enter-active {
  28732. opacity:1;
  28733. max-height:30px;
  28734. }
  28735. </file>
  28736. </example>
  28737. *
  28738. * ## Special repeat start and end points
  28739. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  28740. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  28741. * 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)
  28742. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  28743. *
  28744. * The example below makes use of this feature:
  28745. * ```html
  28746. * <header ng-repeat-start="item in items">
  28747. * Header {{ item }}
  28748. * </header>
  28749. * <div class="body">
  28750. * Body {{ item }}
  28751. * </div>
  28752. * <footer ng-repeat-end>
  28753. * Footer {{ item }}
  28754. * </footer>
  28755. * ```
  28756. *
  28757. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  28758. * ```html
  28759. * <header>
  28760. * Header A
  28761. * </header>
  28762. * <div class="body">
  28763. * Body A
  28764. * </div>
  28765. * <footer>
  28766. * Footer A
  28767. * </footer>
  28768. * <header>
  28769. * Header B
  28770. * </header>
  28771. * <div class="body">
  28772. * Body B
  28773. * </div>
  28774. * <footer>
  28775. * Footer B
  28776. * </footer>
  28777. * ```
  28778. *
  28779. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  28780. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  28781. *
  28782. * @animations
  28783. * | Animation | Occurs |
  28784. * |----------------------------------|-------------------------------------|
  28785. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  28786. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  28787. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  28788. *
  28789. * See the example below for defining CSS animations with ngRepeat.
  28790. *
  28791. * @element ANY
  28792. * @scope
  28793. * @priority 1000
  28794. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  28795. * formats are currently supported:
  28796. *
  28797. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  28798. * is a scope expression giving the collection to enumerate.
  28799. *
  28800. * For example: `album in artist.albums`.
  28801. *
  28802. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  28803. * and `expression` is the scope expression giving the collection to enumerate.
  28804. *
  28805. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  28806. *
  28807. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  28808. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  28809. * is specified, ng-repeat associates elements by identity. It is an error to have
  28810. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  28811. * mapped to the same DOM element, which is not possible.)
  28812. *
  28813. * *Default tracking: $id()*: `item in items` is equivalent to `item in items track by $id(item)`.
  28814. * This implies that the DOM elements will be associated by item identity in the collection.
  28815. *
  28816. * The built-in `$id()` function can be used to assign a unique
  28817. * `$$hashKey` property to each item in the collection. This property is then used as a key to associated DOM elements
  28818. * with the corresponding item in the collection by identity. Moving the same object would move
  28819. * the DOM element in the same way in the DOM.
  28820. * Note that the default id function does not support duplicate primitive values (`number`, `string`),
  28821. * but supports duplictae non-primitive values (`object`) that are *equal* in shape.
  28822. *
  28823. * *Custom Expression*: It is possible to use any AngularJS expression to compute the tracking
  28824. * id, for example with a function, or using a property on the collection items.
  28825. * `item in items track by item.id` is a typical pattern when the items have a unique identifier,
  28826. * e.g. database id. In this case the object identity does not matter. Two objects are considered
  28827. * equivalent as long as their `id` property is same.
  28828. * Tracking by unique identifier is the most performant way and should be used whenever possible.
  28829. *
  28830. * *$index*: This special property tracks the collection items by their index, and
  28831. * re-uses the DOM elements that match that index, e.g. `item in items track by $index`. This can
  28832. * be used for a performance improvement if no unique identfier is available and the identity of
  28833. * the collection items cannot be easily computed. It also allows duplicates.
  28834. *
  28835. * <div class="alert alert-warning">
  28836. * <strong>Note:</strong> Re-using DOM elements can have unforeseen effects. Read the
  28837. * {@link ngRepeat#tracking-and-duplicates section on tracking and duplicates} for
  28838. * more info.
  28839. * </div>
  28840. *
  28841. * <div class="alert alert-warning">
  28842. * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression:
  28843. * `item in items | filter:searchText as results track by item.id`
  28844. * </div>
  28845. *
  28846. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  28847. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  28848. * when a filter is active on the repeater, but the filtered result set is empty.
  28849. *
  28850. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  28851. * the items have been processed through the filter.
  28852. *
  28853. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat
  28854. * micro-syntax so it can be used only after all filters (and not as operator, inside an expression).
  28855. *
  28856. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results track by item.id` .
  28857. *
  28858. * @example
  28859. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  28860. * results by name or by age. New (entering) and removed (leaving) items are animated.
  28861. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  28862. <file name="index.html">
  28863. <div ng-controller="repeatController">
  28864. I have {{friends.length}} friends. They are:
  28865. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  28866. <ul class="example-animate-container">
  28867. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results track by friend.name">
  28868. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  28869. </li>
  28870. <li class="animate-repeat" ng-if="results.length === 0">
  28871. <strong>No results found...</strong>
  28872. </li>
  28873. </ul>
  28874. </div>
  28875. </file>
  28876. <file name="script.js">
  28877. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28878. $scope.friends = [
  28879. {name:'John', age:25, gender:'boy'},
  28880. {name:'Jessie', age:30, gender:'girl'},
  28881. {name:'Johanna', age:28, gender:'girl'},
  28882. {name:'Joy', age:15, gender:'girl'},
  28883. {name:'Mary', age:28, gender:'girl'},
  28884. {name:'Peter', age:95, gender:'boy'},
  28885. {name:'Sebastian', age:50, gender:'boy'},
  28886. {name:'Erika', age:27, gender:'girl'},
  28887. {name:'Patrick', age:40, gender:'boy'},
  28888. {name:'Samantha', age:60, gender:'girl'}
  28889. ];
  28890. });
  28891. </file>
  28892. <file name="animations.css">
  28893. .example-animate-container {
  28894. background:white;
  28895. border:1px solid black;
  28896. list-style:none;
  28897. margin:0;
  28898. padding:0 10px;
  28899. }
  28900. .animate-repeat {
  28901. line-height:30px;
  28902. list-style:none;
  28903. box-sizing:border-box;
  28904. }
  28905. .animate-repeat.ng-move,
  28906. .animate-repeat.ng-enter,
  28907. .animate-repeat.ng-leave {
  28908. transition:all linear 0.5s;
  28909. }
  28910. .animate-repeat.ng-leave.ng-leave-active,
  28911. .animate-repeat.ng-move,
  28912. .animate-repeat.ng-enter {
  28913. opacity:0;
  28914. max-height:0;
  28915. }
  28916. .animate-repeat.ng-leave,
  28917. .animate-repeat.ng-move.ng-move-active,
  28918. .animate-repeat.ng-enter.ng-enter-active {
  28919. opacity:1;
  28920. max-height:30px;
  28921. }
  28922. </file>
  28923. <file name="protractor.js" type="protractor">
  28924. var friends = element.all(by.repeater('friend in friends'));
  28925. it('should render initial data set', function() {
  28926. expect(friends.count()).toBe(10);
  28927. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28928. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28929. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28930. expect(element(by.binding('friends.length')).getText())
  28931. .toMatch("I have 10 friends. They are:");
  28932. });
  28933. it('should update repeater when filter predicate changes', function() {
  28934. expect(friends.count()).toBe(10);
  28935. element(by.model('q')).sendKeys('ma');
  28936. expect(friends.count()).toBe(2);
  28937. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28938. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28939. });
  28940. </file>
  28941. </example>
  28942. */
  28943. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28944. var NG_REMOVED = '$$NG_REMOVED';
  28945. var ngRepeatMinErr = minErr('ngRepeat');
  28946. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28947. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28948. scope[valueIdentifier] = value;
  28949. if (keyIdentifier) scope[keyIdentifier] = key;
  28950. scope.$index = index;
  28951. scope.$first = (index === 0);
  28952. scope.$last = (index === (arrayLength - 1));
  28953. scope.$middle = !(scope.$first || scope.$last);
  28954. // eslint-disable-next-line no-bitwise
  28955. scope.$odd = !(scope.$even = (index & 1) === 0);
  28956. };
  28957. var getBlockStart = function(block) {
  28958. return block.clone[0];
  28959. };
  28960. var getBlockEnd = function(block) {
  28961. return block.clone[block.clone.length - 1];
  28962. };
  28963. return {
  28964. restrict: 'A',
  28965. multiElement: true,
  28966. transclude: 'element',
  28967. priority: 1000,
  28968. terminal: true,
  28969. $$tlb: true,
  28970. compile: function ngRepeatCompile($element, $attr) {
  28971. var expression = $attr.ngRepeat;
  28972. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28973. 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*$/);
  28974. if (!match) {
  28975. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28976. expression);
  28977. }
  28978. var lhs = match[1];
  28979. var rhs = match[2];
  28980. var aliasAs = match[3];
  28981. var trackByExp = match[4];
  28982. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28983. if (!match) {
  28984. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28985. lhs);
  28986. }
  28987. var valueIdentifier = match[3] || match[1];
  28988. var keyIdentifier = match[2];
  28989. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28990. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28991. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28992. aliasAs);
  28993. }
  28994. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28995. var hashFnLocals = {$id: hashKey};
  28996. if (trackByExp) {
  28997. trackByExpGetter = $parse(trackByExp);
  28998. } else {
  28999. trackByIdArrayFn = function(key, value) {
  29000. return hashKey(value);
  29001. };
  29002. trackByIdObjFn = function(key) {
  29003. return key;
  29004. };
  29005. }
  29006. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  29007. if (trackByExpGetter) {
  29008. trackByIdExpFn = function(key, value, index) {
  29009. // assign key, value, and $index to the locals so that they can be used in hash functions
  29010. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  29011. hashFnLocals[valueIdentifier] = value;
  29012. hashFnLocals.$index = index;
  29013. return trackByExpGetter($scope, hashFnLocals);
  29014. };
  29015. }
  29016. // Store a list of elements from previous run. This is a hash where key is the item from the
  29017. // iterator, and the value is objects with following properties.
  29018. // - scope: bound scope
  29019. // - clone: previous element.
  29020. // - index: position
  29021. //
  29022. // We are using no-proto object so that we don't need to guard against inherited props via
  29023. // hasOwnProperty.
  29024. var lastBlockMap = createMap();
  29025. //watch props
  29026. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  29027. var index, length,
  29028. previousNode = $element[0], // node that cloned nodes should be inserted after
  29029. // initialized to the comment node anchor
  29030. nextNode,
  29031. // Same as lastBlockMap but it has the current state. It will become the
  29032. // lastBlockMap on the next iteration.
  29033. nextBlockMap = createMap(),
  29034. collectionLength,
  29035. key, value, // key/value of iteration
  29036. trackById,
  29037. trackByIdFn,
  29038. collectionKeys,
  29039. block, // last object information {scope, element, id}
  29040. nextBlockOrder,
  29041. elementsToRemove;
  29042. if (aliasAs) {
  29043. $scope[aliasAs] = collection;
  29044. }
  29045. if (isArrayLike(collection)) {
  29046. collectionKeys = collection;
  29047. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  29048. } else {
  29049. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  29050. // if object, extract keys, in enumeration order, unsorted
  29051. collectionKeys = [];
  29052. for (var itemKey in collection) {
  29053. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  29054. collectionKeys.push(itemKey);
  29055. }
  29056. }
  29057. }
  29058. collectionLength = collectionKeys.length;
  29059. nextBlockOrder = new Array(collectionLength);
  29060. // locate existing items
  29061. for (index = 0; index < collectionLength; index++) {
  29062. key = (collection === collectionKeys) ? index : collectionKeys[index];
  29063. value = collection[key];
  29064. trackById = trackByIdFn(key, value, index);
  29065. if (lastBlockMap[trackById]) {
  29066. // found previously seen block
  29067. block = lastBlockMap[trackById];
  29068. delete lastBlockMap[trackById];
  29069. nextBlockMap[trackById] = block;
  29070. nextBlockOrder[index] = block;
  29071. } else if (nextBlockMap[trackById]) {
  29072. // if collision detected. restore lastBlockMap and throw an error
  29073. forEach(nextBlockOrder, function(block) {
  29074. if (block && block.scope) lastBlockMap[block.id] = block;
  29075. });
  29076. throw ngRepeatMinErr('dupes',
  29077. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  29078. expression, trackById, value);
  29079. } else {
  29080. // new never before seen block
  29081. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  29082. nextBlockMap[trackById] = true;
  29083. }
  29084. }
  29085. // remove leftover items
  29086. for (var blockKey in lastBlockMap) {
  29087. block = lastBlockMap[blockKey];
  29088. elementsToRemove = getBlockNodes(block.clone);
  29089. $animate.leave(elementsToRemove);
  29090. if (elementsToRemove[0].parentNode) {
  29091. // if the element was not removed yet because of pending animation, mark it as deleted
  29092. // so that we can ignore it later
  29093. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  29094. elementsToRemove[index][NG_REMOVED] = true;
  29095. }
  29096. }
  29097. block.scope.$destroy();
  29098. }
  29099. // we are not using forEach for perf reasons (trying to avoid #call)
  29100. for (index = 0; index < collectionLength; index++) {
  29101. key = (collection === collectionKeys) ? index : collectionKeys[index];
  29102. value = collection[key];
  29103. block = nextBlockOrder[index];
  29104. if (block.scope) {
  29105. // if we have already seen this object, then we need to reuse the
  29106. // associated scope/element
  29107. nextNode = previousNode;
  29108. // skip nodes that are already pending removal via leave animation
  29109. do {
  29110. nextNode = nextNode.nextSibling;
  29111. } while (nextNode && nextNode[NG_REMOVED]);
  29112. if (getBlockStart(block) !== nextNode) {
  29113. // existing item which got moved
  29114. $animate.move(getBlockNodes(block.clone), null, previousNode);
  29115. }
  29116. previousNode = getBlockEnd(block);
  29117. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  29118. } else {
  29119. // new item which we don't know about
  29120. $transclude(function ngRepeatTransclude(clone, scope) {
  29121. block.scope = scope;
  29122. // http://jsperf.com/clone-vs-createcomment
  29123. var endNode = ngRepeatEndComment.cloneNode(false);
  29124. clone[clone.length++] = endNode;
  29125. $animate.enter(clone, null, previousNode);
  29126. previousNode = endNode;
  29127. // Note: We only need the first/last node of the cloned nodes.
  29128. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  29129. // by a directive with templateUrl when its template arrives.
  29130. block.clone = clone;
  29131. nextBlockMap[block.id] = block;
  29132. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  29133. });
  29134. }
  29135. }
  29136. lastBlockMap = nextBlockMap;
  29137. });
  29138. };
  29139. }
  29140. };
  29141. }];
  29142. var NG_HIDE_CLASS = 'ng-hide';
  29143. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  29144. /**
  29145. * @ngdoc directive
  29146. * @name ngShow
  29147. * @multiElement
  29148. *
  29149. * @description
  29150. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  29151. * the `ngShow` attribute.
  29152. *
  29153. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  29154. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  29155. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  29156. * {@link ng.directive:ngCsp ngCsp}).
  29157. *
  29158. * ```html
  29159. * <!-- when $scope.myValue is truthy (element is visible) -->
  29160. * <div ng-show="myValue"></div>
  29161. *
  29162. * <!-- when $scope.myValue is falsy (element is hidden) -->
  29163. * <div ng-show="myValue" class="ng-hide"></div>
  29164. * ```
  29165. *
  29166. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  29167. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  29168. * CSS class is removed from the element causing the element not to appear hidden.
  29169. *
  29170. * ## Why is `!important` used?
  29171. *
  29172. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  29173. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  29174. * simple as changing the display style on a HTML list item would make hidden elements appear
  29175. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  29176. *
  29177. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  29178. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  29179. * developer chooses to override the styling to change how to hide an element then it is just a
  29180. * matter of using `!important` in their own CSS code.
  29181. *
  29182. * ### Overriding `.ng-hide`
  29183. *
  29184. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  29185. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  29186. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  29187. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  29188. *
  29189. * ```css
  29190. * .ng-hide:not(.ng-hide-animate) {
  29191. * /&#42; These are just alternative ways of hiding an element &#42;/
  29192. * display: block!important;
  29193. * position: absolute;
  29194. * top: -9999px;
  29195. * left: -9999px;
  29196. * }
  29197. * ```
  29198. *
  29199. * By default you don't need to override anything in CSS and the animations will work around the
  29200. * display style.
  29201. *
  29202. * @animations
  29203. * | Animation | Occurs |
  29204. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  29205. * | {@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. |
  29206. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  29207. *
  29208. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  29209. * directive expression is true and false. This system works like the animation system present with
  29210. * `ngClass` except that you must also include the `!important` flag to override the display
  29211. * property so that the elements are not actually hidden during the animation.
  29212. *
  29213. * ```css
  29214. * /&#42; A working example can be found at the bottom of this page. &#42;/
  29215. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  29216. * transition: all 0.5s linear;
  29217. * }
  29218. *
  29219. * .my-element.ng-hide-add { ... }
  29220. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  29221. * .my-element.ng-hide-remove { ... }
  29222. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  29223. * ```
  29224. *
  29225. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  29226. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  29227. *
  29228. * @element ANY
  29229. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  29230. * element is shown/hidden respectively.
  29231. *
  29232. * @example
  29233. * A simple example, animating the element's opacity:
  29234. *
  29235. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  29236. <file name="index.html">
  29237. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  29238. <div class="check-element animate-show-hide" ng-show="checked">
  29239. I show up when your checkbox is checked.
  29240. </div>
  29241. </file>
  29242. <file name="animations.css">
  29243. .animate-show-hide.ng-hide {
  29244. opacity: 0;
  29245. }
  29246. .animate-show-hide.ng-hide-add,
  29247. .animate-show-hide.ng-hide-remove {
  29248. transition: all linear 0.5s;
  29249. }
  29250. .check-element {
  29251. border: 1px solid black;
  29252. opacity: 1;
  29253. padding: 10px;
  29254. }
  29255. </file>
  29256. <file name="protractor.js" type="protractor">
  29257. it('should check ngShow', function() {
  29258. var checkbox = element(by.model('checked'));
  29259. var checkElem = element(by.css('.check-element'));
  29260. expect(checkElem.isDisplayed()).toBe(false);
  29261. checkbox.click();
  29262. expect(checkElem.isDisplayed()).toBe(true);
  29263. });
  29264. </file>
  29265. </example>
  29266. *
  29267. * <hr />
  29268. * @example
  29269. * A more complex example, featuring different show/hide animations:
  29270. *
  29271. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  29272. <file name="index.html">
  29273. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  29274. <div class="check-element funky-show-hide" ng-show="checked">
  29275. I show up when your checkbox is checked.
  29276. </div>
  29277. </file>
  29278. <file name="animations.css">
  29279. body {
  29280. overflow: hidden;
  29281. perspective: 1000px;
  29282. }
  29283. .funky-show-hide.ng-hide-add {
  29284. transform: rotateZ(0);
  29285. transform-origin: right;
  29286. transition: all 0.5s ease-in-out;
  29287. }
  29288. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  29289. transform: rotateZ(-135deg);
  29290. }
  29291. .funky-show-hide.ng-hide-remove {
  29292. transform: rotateY(90deg);
  29293. transform-origin: left;
  29294. transition: all 0.5s ease;
  29295. }
  29296. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  29297. transform: rotateY(0);
  29298. }
  29299. .check-element {
  29300. border: 1px solid black;
  29301. opacity: 1;
  29302. padding: 10px;
  29303. }
  29304. </file>
  29305. <file name="protractor.js" type="protractor">
  29306. it('should check ngShow', function() {
  29307. var checkbox = element(by.model('checked'));
  29308. var checkElem = element(by.css('.check-element'));
  29309. expect(checkElem.isDisplayed()).toBe(false);
  29310. checkbox.click();
  29311. expect(checkElem.isDisplayed()).toBe(true);
  29312. });
  29313. </file>
  29314. </example>
  29315. */
  29316. var ngShowDirective = ['$animate', function($animate) {
  29317. return {
  29318. restrict: 'A',
  29319. multiElement: true,
  29320. link: function(scope, element, attr) {
  29321. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  29322. // we're adding a temporary, animation-specific class for ng-hide since this way
  29323. // we can control when the element is actually displayed on screen without having
  29324. // to have a global/greedy CSS selector that breaks when other animations are run.
  29325. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  29326. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  29327. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  29328. });
  29329. });
  29330. }
  29331. };
  29332. }];
  29333. /**
  29334. * @ngdoc directive
  29335. * @name ngHide
  29336. * @multiElement
  29337. *
  29338. * @description
  29339. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  29340. * the `ngHide` attribute.
  29341. *
  29342. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  29343. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  29344. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  29345. * {@link ng.directive:ngCsp ngCsp}).
  29346. *
  29347. * ```html
  29348. * <!-- when $scope.myValue is truthy (element is hidden) -->
  29349. * <div ng-hide="myValue" class="ng-hide"></div>
  29350. *
  29351. * <!-- when $scope.myValue is falsy (element is visible) -->
  29352. * <div ng-hide="myValue"></div>
  29353. * ```
  29354. *
  29355. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  29356. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  29357. * CSS class is removed from the element causing the element not to appear hidden.
  29358. *
  29359. * ## Why is `!important` used?
  29360. *
  29361. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  29362. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  29363. * simple as changing the display style on a HTML list item would make hidden elements appear
  29364. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  29365. *
  29366. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  29367. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  29368. * developer chooses to override the styling to change how to hide an element then it is just a
  29369. * matter of using `!important` in their own CSS code.
  29370. *
  29371. * ### Overriding `.ng-hide`
  29372. *
  29373. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  29374. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  29375. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  29376. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  29377. *
  29378. * ```css
  29379. * .ng-hide:not(.ng-hide-animate) {
  29380. * /&#42; These are just alternative ways of hiding an element &#42;/
  29381. * display: block!important;
  29382. * position: absolute;
  29383. * top: -9999px;
  29384. * left: -9999px;
  29385. * }
  29386. * ```
  29387. *
  29388. * By default you don't need to override in CSS anything and the animations will work around the
  29389. * display style.
  29390. *
  29391. * @animations
  29392. * | Animation | Occurs |
  29393. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  29394. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  29395. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  29396. *
  29397. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  29398. * directive expression is true and false. This system works like the animation system present with
  29399. * `ngClass` except that you must also include the `!important` flag to override the display
  29400. * property so that the elements are not actually hidden during the animation.
  29401. *
  29402. * ```css
  29403. * /&#42; A working example can be found at the bottom of this page. &#42;/
  29404. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  29405. * transition: all 0.5s linear;
  29406. * }
  29407. *
  29408. * .my-element.ng-hide-add { ... }
  29409. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  29410. * .my-element.ng-hide-remove { ... }
  29411. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  29412. * ```
  29413. *
  29414. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  29415. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  29416. *
  29417. * @element ANY
  29418. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  29419. * element is hidden/shown respectively.
  29420. *
  29421. * @example
  29422. * A simple example, animating the element's opacity:
  29423. *
  29424. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  29425. <file name="index.html">
  29426. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29427. <div class="check-element animate-show-hide" ng-hide="checked">
  29428. I hide when your checkbox is checked.
  29429. </div>
  29430. </file>
  29431. <file name="animations.css">
  29432. .animate-show-hide.ng-hide {
  29433. opacity: 0;
  29434. }
  29435. .animate-show-hide.ng-hide-add,
  29436. .animate-show-hide.ng-hide-remove {
  29437. transition: all linear 0.5s;
  29438. }
  29439. .check-element {
  29440. border: 1px solid black;
  29441. opacity: 1;
  29442. padding: 10px;
  29443. }
  29444. </file>
  29445. <file name="protractor.js" type="protractor">
  29446. it('should check ngHide', function() {
  29447. var checkbox = element(by.model('checked'));
  29448. var checkElem = element(by.css('.check-element'));
  29449. expect(checkElem.isDisplayed()).toBe(true);
  29450. checkbox.click();
  29451. expect(checkElem.isDisplayed()).toBe(false);
  29452. });
  29453. </file>
  29454. </example>
  29455. *
  29456. * <hr />
  29457. * @example
  29458. * A more complex example, featuring different show/hide animations:
  29459. *
  29460. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  29461. <file name="index.html">
  29462. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29463. <div class="check-element funky-show-hide" ng-hide="checked">
  29464. I hide when your checkbox is checked.
  29465. </div>
  29466. </file>
  29467. <file name="animations.css">
  29468. body {
  29469. overflow: hidden;
  29470. perspective: 1000px;
  29471. }
  29472. .funky-show-hide.ng-hide-add {
  29473. transform: rotateZ(0);
  29474. transform-origin: right;
  29475. transition: all 0.5s ease-in-out;
  29476. }
  29477. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  29478. transform: rotateZ(-135deg);
  29479. }
  29480. .funky-show-hide.ng-hide-remove {
  29481. transform: rotateY(90deg);
  29482. transform-origin: left;
  29483. transition: all 0.5s ease;
  29484. }
  29485. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  29486. transform: rotateY(0);
  29487. }
  29488. .check-element {
  29489. border: 1px solid black;
  29490. opacity: 1;
  29491. padding: 10px;
  29492. }
  29493. </file>
  29494. <file name="protractor.js" type="protractor">
  29495. it('should check ngHide', function() {
  29496. var checkbox = element(by.model('checked'));
  29497. var checkElem = element(by.css('.check-element'));
  29498. expect(checkElem.isDisplayed()).toBe(true);
  29499. checkbox.click();
  29500. expect(checkElem.isDisplayed()).toBe(false);
  29501. });
  29502. </file>
  29503. </example>
  29504. */
  29505. var ngHideDirective = ['$animate', function($animate) {
  29506. return {
  29507. restrict: 'A',
  29508. multiElement: true,
  29509. link: function(scope, element, attr) {
  29510. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  29511. // The comment inside of the ngShowDirective explains why we add and
  29512. // remove a temporary class for the show/hide animation
  29513. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  29514. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  29515. });
  29516. });
  29517. }
  29518. };
  29519. }];
  29520. /**
  29521. * @ngdoc directive
  29522. * @name ngStyle
  29523. * @restrict AC
  29524. *
  29525. * @description
  29526. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  29527. *
  29528. * @knownIssue
  29529. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  29530. * attribute, when using the `ngStyle` directive on the same element.
  29531. * See {@link guide/interpolation#known-issues here} for more info.
  29532. *
  29533. * @element ANY
  29534. * @param {expression} ngStyle
  29535. *
  29536. * {@link guide/expression Expression} which evals to an
  29537. * object whose keys are CSS style names and values are corresponding values for those CSS
  29538. * keys.
  29539. *
  29540. * Since some CSS style names are not valid keys for an object, they must be quoted.
  29541. * See the 'background-color' style in the example below.
  29542. *
  29543. * @example
  29544. <example name="ng-style">
  29545. <file name="index.html">
  29546. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  29547. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  29548. <input type="button" value="clear" ng-click="myStyle={}">
  29549. <br/>
  29550. <span ng-style="myStyle">Sample Text</span>
  29551. <pre>myStyle={{myStyle}}</pre>
  29552. </file>
  29553. <file name="style.css">
  29554. span {
  29555. color: black;
  29556. }
  29557. </file>
  29558. <file name="protractor.js" type="protractor">
  29559. var colorSpan = element(by.css('span'));
  29560. it('should check ng-style', function() {
  29561. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29562. element(by.css('input[value=\'set color\']')).click();
  29563. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  29564. element(by.css('input[value=clear]')).click();
  29565. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29566. });
  29567. </file>
  29568. </example>
  29569. */
  29570. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  29571. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  29572. if (oldStyles && (newStyles !== oldStyles)) {
  29573. forEach(oldStyles, function(val, style) { element.css(style, '');});
  29574. }
  29575. if (newStyles) element.css(newStyles);
  29576. }, true);
  29577. });
  29578. /**
  29579. * @ngdoc directive
  29580. * @name ngSwitch
  29581. * @restrict EA
  29582. *
  29583. * @description
  29584. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  29585. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  29586. * as specified in the template.
  29587. *
  29588. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  29589. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  29590. * matches the value obtained from the evaluated expression. In other words, you define a container element
  29591. * (where you place the directive), place an expression on the **`on="..."` attribute**
  29592. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  29593. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  29594. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  29595. * attribute is displayed.
  29596. *
  29597. * <div class="alert alert-info">
  29598. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  29599. * as literal string values to match against.
  29600. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  29601. * value of the expression `$scope.someVal`.
  29602. * </div>
  29603. * @animations
  29604. * | Animation | Occurs |
  29605. * |----------------------------------|-------------------------------------|
  29606. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  29607. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  29608. *
  29609. * @usage
  29610. *
  29611. * ```
  29612. * <ANY ng-switch="expression">
  29613. * <ANY ng-switch-when="matchValue1">...</ANY>
  29614. * <ANY ng-switch-when="matchValue2">...</ANY>
  29615. * <ANY ng-switch-default>...</ANY>
  29616. * </ANY>
  29617. * ```
  29618. *
  29619. *
  29620. * @scope
  29621. * @priority 1200
  29622. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  29623. * On child elements add:
  29624. *
  29625. * * `ngSwitchWhen`: the case statement to match against. If match then this
  29626. * case will be displayed. If the same match appears multiple times, all the
  29627. * elements will be displayed. It is possible to associate multiple values to
  29628. * the same `ngSwitchWhen` by defining the optional attribute
  29629. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  29630. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  29631. * if any of the `ngSwitch` evaluates to any of these tokens.
  29632. * * `ngSwitchDefault`: the default case when no other case match. If there
  29633. * are multiple default cases, all of them will be displayed when no other
  29634. * case match.
  29635. *
  29636. *
  29637. * @example
  29638. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  29639. <file name="index.html">
  29640. <div ng-controller="ExampleController">
  29641. <select ng-model="selection" ng-options="item for item in items">
  29642. </select>
  29643. <code>selection={{selection}}</code>
  29644. <hr/>
  29645. <div class="animate-switch-container"
  29646. ng-switch on="selection">
  29647. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  29648. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  29649. <div class="animate-switch" ng-switch-default>default</div>
  29650. </div>
  29651. </div>
  29652. </file>
  29653. <file name="script.js">
  29654. angular.module('switchExample', ['ngAnimate'])
  29655. .controller('ExampleController', ['$scope', function($scope) {
  29656. $scope.items = ['settings', 'home', 'options', 'other'];
  29657. $scope.selection = $scope.items[0];
  29658. }]);
  29659. </file>
  29660. <file name="animations.css">
  29661. .animate-switch-container {
  29662. position:relative;
  29663. background:white;
  29664. border:1px solid black;
  29665. height:40px;
  29666. overflow:hidden;
  29667. }
  29668. .animate-switch {
  29669. padding:10px;
  29670. }
  29671. .animate-switch.ng-animate {
  29672. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  29673. position:absolute;
  29674. top:0;
  29675. left:0;
  29676. right:0;
  29677. bottom:0;
  29678. }
  29679. .animate-switch.ng-leave.ng-leave-active,
  29680. .animate-switch.ng-enter {
  29681. top:-50px;
  29682. }
  29683. .animate-switch.ng-leave,
  29684. .animate-switch.ng-enter.ng-enter-active {
  29685. top:0;
  29686. }
  29687. </file>
  29688. <file name="protractor.js" type="protractor">
  29689. var switchElem = element(by.css('[ng-switch]'));
  29690. var select = element(by.model('selection'));
  29691. it('should start in settings', function() {
  29692. expect(switchElem.getText()).toMatch(/Settings Div/);
  29693. });
  29694. it('should change to home', function() {
  29695. select.all(by.css('option')).get(1).click();
  29696. expect(switchElem.getText()).toMatch(/Home Span/);
  29697. });
  29698. it('should change to settings via "options"', function() {
  29699. select.all(by.css('option')).get(2).click();
  29700. expect(switchElem.getText()).toMatch(/Settings Div/);
  29701. });
  29702. it('should select default', function() {
  29703. select.all(by.css('option')).get(3).click();
  29704. expect(switchElem.getText()).toMatch(/default/);
  29705. });
  29706. </file>
  29707. </example>
  29708. */
  29709. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  29710. return {
  29711. require: 'ngSwitch',
  29712. // asks for $scope to fool the BC controller module
  29713. controller: ['$scope', function NgSwitchController() {
  29714. this.cases = {};
  29715. }],
  29716. link: function(scope, element, attr, ngSwitchController) {
  29717. var watchExpr = attr.ngSwitch || attr.on,
  29718. selectedTranscludes = [],
  29719. selectedElements = [],
  29720. previousLeaveAnimations = [],
  29721. selectedScopes = [];
  29722. var spliceFactory = function(array, index) {
  29723. return function(response) {
  29724. if (response !== false) array.splice(index, 1);
  29725. };
  29726. };
  29727. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  29728. var i, ii;
  29729. // Start with the last, in case the array is modified during the loop
  29730. while (previousLeaveAnimations.length) {
  29731. $animate.cancel(previousLeaveAnimations.pop());
  29732. }
  29733. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  29734. var selected = getBlockNodes(selectedElements[i].clone);
  29735. selectedScopes[i].$destroy();
  29736. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  29737. runner.done(spliceFactory(previousLeaveAnimations, i));
  29738. }
  29739. selectedElements.length = 0;
  29740. selectedScopes.length = 0;
  29741. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  29742. forEach(selectedTranscludes, function(selectedTransclude) {
  29743. selectedTransclude.transclude(function(caseElement, selectedScope) {
  29744. selectedScopes.push(selectedScope);
  29745. var anchor = selectedTransclude.element;
  29746. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  29747. var block = { clone: caseElement };
  29748. selectedElements.push(block);
  29749. $animate.enter(caseElement, anchor.parent(), anchor);
  29750. });
  29751. });
  29752. }
  29753. });
  29754. }
  29755. };
  29756. }];
  29757. var ngSwitchWhenDirective = ngDirective({
  29758. transclude: 'element',
  29759. priority: 1200,
  29760. require: '^ngSwitch',
  29761. multiElement: true,
  29762. link: function(scope, element, attrs, ctrl, $transclude) {
  29763. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  29764. // Filter duplicate cases
  29765. function(element, index, array) { return array[index - 1] !== element; }
  29766. );
  29767. forEach(cases, function(whenCase) {
  29768. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  29769. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  29770. });
  29771. }
  29772. });
  29773. var ngSwitchDefaultDirective = ngDirective({
  29774. transclude: 'element',
  29775. priority: 1200,
  29776. require: '^ngSwitch',
  29777. multiElement: true,
  29778. link: function(scope, element, attr, ctrl, $transclude) {
  29779. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  29780. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  29781. }
  29782. });
  29783. /**
  29784. * @ngdoc directive
  29785. * @name ngTransclude
  29786. * @restrict EAC
  29787. *
  29788. * @description
  29789. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  29790. *
  29791. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  29792. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  29793. *
  29794. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  29795. * content of this element will be removed before the transcluded content is inserted.
  29796. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  29797. * content in the case that no transcluded content is provided.
  29798. *
  29799. * @element ANY
  29800. *
  29801. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  29802. * or its value is the same as the name of the attribute then the default slot is used.
  29803. *
  29804. * @example
  29805. * ### Basic transclusion
  29806. * This example demonstrates basic transclusion of content into a component directive.
  29807. * <example name="simpleTranscludeExample" module="transcludeExample">
  29808. * <file name="index.html">
  29809. * <script>
  29810. * angular.module('transcludeExample', [])
  29811. * .directive('pane', function(){
  29812. * return {
  29813. * restrict: 'E',
  29814. * transclude: true,
  29815. * scope: { title:'@' },
  29816. * template: '<div style="border: 1px solid black;">' +
  29817. * '<div style="background-color: gray">{{title}}</div>' +
  29818. * '<ng-transclude></ng-transclude>' +
  29819. * '</div>'
  29820. * };
  29821. * })
  29822. * .controller('ExampleController', ['$scope', function($scope) {
  29823. * $scope.title = 'Lorem Ipsum';
  29824. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29825. * }]);
  29826. * </script>
  29827. * <div ng-controller="ExampleController">
  29828. * <input ng-model="title" aria-label="title"> <br/>
  29829. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29830. * <pane title="{{title}}"><span>{{text}}</span></pane>
  29831. * </div>
  29832. * </file>
  29833. * <file name="protractor.js" type="protractor">
  29834. * it('should have transcluded', function() {
  29835. * var titleElement = element(by.model('title'));
  29836. * titleElement.clear();
  29837. * titleElement.sendKeys('TITLE');
  29838. * var textElement = element(by.model('text'));
  29839. * textElement.clear();
  29840. * textElement.sendKeys('TEXT');
  29841. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  29842. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29843. * });
  29844. * </file>
  29845. * </example>
  29846. *
  29847. * @example
  29848. * ### Transclude fallback content
  29849. * This example shows how to use `NgTransclude` with fallback content, that
  29850. * is displayed if no transcluded content is provided.
  29851. *
  29852. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  29853. * <file name="index.html">
  29854. * <script>
  29855. * angular.module('transcludeFallbackContentExample', [])
  29856. * .directive('myButton', function(){
  29857. * return {
  29858. * restrict: 'E',
  29859. * transclude: true,
  29860. * scope: true,
  29861. * template: '<button style="cursor: pointer;">' +
  29862. * '<ng-transclude>' +
  29863. * '<b style="color: red;">Button1</b>' +
  29864. * '</ng-transclude>' +
  29865. * '</button>'
  29866. * };
  29867. * });
  29868. * </script>
  29869. * <!-- fallback button content -->
  29870. * <my-button id="fallback"></my-button>
  29871. * <!-- modified button content -->
  29872. * <my-button id="modified">
  29873. * <i style="color: green;">Button2</i>
  29874. * </my-button>
  29875. * </file>
  29876. * <file name="protractor.js" type="protractor">
  29877. * it('should have different transclude element content', function() {
  29878. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  29879. * expect(element(by.id('modified')).getText()).toBe('Button2');
  29880. * });
  29881. * </file>
  29882. * </example>
  29883. *
  29884. * @example
  29885. * ### Multi-slot transclusion
  29886. * This example demonstrates using multi-slot transclusion in a component directive.
  29887. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  29888. * <file name="index.html">
  29889. * <style>
  29890. * .title, .footer {
  29891. * background-color: gray
  29892. * }
  29893. * </style>
  29894. * <div ng-controller="ExampleController">
  29895. * <input ng-model="title" aria-label="title"> <br/>
  29896. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29897. * <pane>
  29898. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  29899. * <pane-body><p>{{text}}</p></pane-body>
  29900. * </pane>
  29901. * </div>
  29902. * </file>
  29903. * <file name="app.js">
  29904. * angular.module('multiSlotTranscludeExample', [])
  29905. * .directive('pane', function() {
  29906. * return {
  29907. * restrict: 'E',
  29908. * transclude: {
  29909. * 'title': '?paneTitle',
  29910. * 'body': 'paneBody',
  29911. * 'footer': '?paneFooter'
  29912. * },
  29913. * template: '<div style="border: 1px solid black;">' +
  29914. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  29915. * '<div ng-transclude="body"></div>' +
  29916. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  29917. * '</div>'
  29918. * };
  29919. * })
  29920. * .controller('ExampleController', ['$scope', function($scope) {
  29921. * $scope.title = 'Lorem Ipsum';
  29922. * $scope.link = 'https://google.com';
  29923. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29924. * }]);
  29925. * </file>
  29926. * <file name="protractor.js" type="protractor">
  29927. * it('should have transcluded the title and the body', function() {
  29928. * var titleElement = element(by.model('title'));
  29929. * titleElement.clear();
  29930. * titleElement.sendKeys('TITLE');
  29931. * var textElement = element(by.model('text'));
  29932. * textElement.clear();
  29933. * textElement.sendKeys('TEXT');
  29934. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29935. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29936. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29937. * });
  29938. * </file>
  29939. * </example>
  29940. */
  29941. var ngTranscludeMinErr = minErr('ngTransclude');
  29942. var ngTranscludeDirective = ['$compile', function($compile) {
  29943. return {
  29944. restrict: 'EAC',
  29945. compile: function ngTranscludeCompile(tElement) {
  29946. // Remove and cache any original content to act as a fallback
  29947. var fallbackLinkFn = $compile(tElement.contents());
  29948. tElement.empty();
  29949. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29950. if (!$transclude) {
  29951. throw ngTranscludeMinErr('orphan',
  29952. 'Illegal use of ngTransclude directive in the template! ' +
  29953. 'No parent directive that requires a transclusion found. ' +
  29954. 'Element: {0}',
  29955. startingTag($element));
  29956. }
  29957. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29958. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29959. $attrs.ngTransclude = '';
  29960. }
  29961. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29962. // If the slot is required and no transclusion content is provided then this call will throw an error
  29963. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29964. // If the slot is optional and no transclusion content is provided then use the fallback content
  29965. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29966. useFallbackContent();
  29967. }
  29968. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29969. if (clone.length && notWhitespace(clone)) {
  29970. $element.append(clone);
  29971. } else {
  29972. useFallbackContent();
  29973. // There is nothing linked against the transcluded scope since no content was available,
  29974. // so it should be safe to clean up the generated scope.
  29975. transcludedScope.$destroy();
  29976. }
  29977. }
  29978. function useFallbackContent() {
  29979. // Since this is the fallback content rather than the transcluded content,
  29980. // we link against the scope of this directive rather than the transcluded scope
  29981. fallbackLinkFn($scope, function(clone) {
  29982. $element.append(clone);
  29983. });
  29984. }
  29985. function notWhitespace(nodes) {
  29986. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29987. var node = nodes[i];
  29988. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29989. return true;
  29990. }
  29991. }
  29992. }
  29993. };
  29994. }
  29995. };
  29996. }];
  29997. /**
  29998. * @ngdoc directive
  29999. * @name script
  30000. * @restrict E
  30001. *
  30002. * @description
  30003. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  30004. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  30005. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  30006. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  30007. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  30008. *
  30009. * @param {string} type Must be set to `'text/ng-template'`.
  30010. * @param {string} id Cache name of the template.
  30011. *
  30012. * @example
  30013. <example name="script-tag">
  30014. <file name="index.html">
  30015. <script type="text/ng-template" id="/tpl.html">
  30016. Content of the template.
  30017. </script>
  30018. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  30019. <div id="tpl-content" ng-include src="currentTpl"></div>
  30020. </file>
  30021. <file name="protractor.js" type="protractor">
  30022. it('should load template defined inside script tag', function() {
  30023. element(by.css('#tpl-link')).click();
  30024. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  30025. });
  30026. </file>
  30027. </example>
  30028. */
  30029. var scriptDirective = ['$templateCache', function($templateCache) {
  30030. return {
  30031. restrict: 'E',
  30032. terminal: true,
  30033. compile: function(element, attr) {
  30034. if (attr.type === 'text/ng-template') {
  30035. var templateUrl = attr.id,
  30036. text = element[0].text;
  30037. $templateCache.put(templateUrl, text);
  30038. }
  30039. }
  30040. };
  30041. }];
  30042. /* exported selectDirective, optionDirective */
  30043. var noopNgModelController = { $setViewValue: noop, $render: noop };
  30044. function setOptionSelectedStatus(optionEl, value) {
  30045. optionEl.prop('selected', value);
  30046. /**
  30047. * When unselecting an option, setting the property to null / false should be enough
  30048. * However, screenreaders might react to the selected attribute instead, see
  30049. * https://github.com/angular/angular.js/issues/14419
  30050. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  30051. * or null
  30052. */
  30053. optionEl.attr('selected', value);
  30054. }
  30055. /**
  30056. * @ngdoc type
  30057. * @name select.SelectController
  30058. *
  30059. * @description
  30060. * The controller for the {@link ng.select select} directive. The controller exposes
  30061. * a few utility methods that can be used to augment the behavior of a regular or an
  30062. * {@link ng.ngOptions ngOptions} select element.
  30063. *
  30064. * @example
  30065. * ### Set a custom error when the unknown option is selected
  30066. *
  30067. * This example sets a custom error "unknownValue" on the ngModelController
  30068. * when the select element's unknown option is selected, i.e. when the model is set to a value
  30069. * that is not matched by any option.
  30070. *
  30071. * <example name="select-unknown-value-error" module="staticSelect">
  30072. * <file name="index.html">
  30073. * <div ng-controller="ExampleController">
  30074. * <form name="myForm">
  30075. * <label for="testSelect"> Single select: </label><br>
  30076. * <select name="testSelect" ng-model="selected" unknown-value-error>
  30077. * <option value="option-1">Option 1</option>
  30078. * <option value="option-2">Option 2</option>
  30079. * </select><br>
  30080. * <span class="error" ng-if="myForm.testSelect.$error.unknownValue">
  30081. * Error: The current model doesn't match any option</span><br>
  30082. *
  30083. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  30084. * </form>
  30085. * </div>
  30086. * </file>
  30087. * <file name="app.js">
  30088. * angular.module('staticSelect', [])
  30089. * .controller('ExampleController', ['$scope', function($scope) {
  30090. * $scope.selected = null;
  30091. *
  30092. * $scope.forceUnknownOption = function() {
  30093. * $scope.selected = 'nonsense';
  30094. * };
  30095. * }])
  30096. * .directive('unknownValueError', function() {
  30097. * return {
  30098. * require: ['ngModel', 'select'],
  30099. * link: function(scope, element, attrs, ctrls) {
  30100. * var ngModelCtrl = ctrls[0];
  30101. * var selectCtrl = ctrls[1];
  30102. *
  30103. * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) {
  30104. * if (selectCtrl.$isUnknownOptionSelected()) {
  30105. * return false;
  30106. * }
  30107. *
  30108. * return true;
  30109. * };
  30110. * }
  30111. *
  30112. * };
  30113. * });
  30114. * </file>
  30115. *</example>
  30116. *
  30117. *
  30118. * @example
  30119. * ### Set the "required" error when the unknown option is selected.
  30120. *
  30121. * By default, the "required" error on the ngModelController is only set on a required select
  30122. * when the empty option is selected. This example adds a custom directive that also sets the
  30123. * error when the unknown option is selected.
  30124. *
  30125. * <example name="select-unknown-value-required" module="staticSelect">
  30126. * <file name="index.html">
  30127. * <div ng-controller="ExampleController">
  30128. * <form name="myForm">
  30129. * <label for="testSelect"> Select: </label><br>
  30130. * <select name="testSelect" ng-model="selected" required unknown-value-required>
  30131. * <option value="option-1">Option 1</option>
  30132. * <option value="option-2">Option 2</option>
  30133. * </select><br>
  30134. * <span class="error" ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br>
  30135. *
  30136. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  30137. * </form>
  30138. * </div>
  30139. * </file>
  30140. * <file name="app.js">
  30141. * angular.module('staticSelect', [])
  30142. * .controller('ExampleController', ['$scope', function($scope) {
  30143. * $scope.selected = null;
  30144. *
  30145. * $scope.forceUnknownOption = function() {
  30146. * $scope.selected = 'nonsense';
  30147. * };
  30148. * }])
  30149. * .directive('unknownValueRequired', function() {
  30150. * return {
  30151. * priority: 1, // This directive must run after the required directive has added its validator
  30152. * require: ['ngModel', 'select'],
  30153. * link: function(scope, element, attrs, ctrls) {
  30154. * var ngModelCtrl = ctrls[0];
  30155. * var selectCtrl = ctrls[1];
  30156. *
  30157. * var originalRequiredValidator = ngModelCtrl.$validators.required;
  30158. *
  30159. * ngModelCtrl.$validators.required = function() {
  30160. * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) {
  30161. * return false;
  30162. * }
  30163. *
  30164. * return originalRequiredValidator.apply(this, arguments);
  30165. * };
  30166. * }
  30167. * };
  30168. * });
  30169. * </file>
  30170. * <file name="protractor.js" type="protractor">
  30171. * it('should show the error message when the unknown option is selected', function() {
  30172. var error = element(by.className('error'));
  30173. expect(error.getText()).toBe('Error: Please select a value');
  30174. element(by.cssContainingText('option', 'Option 1')).click();
  30175. expect(error.isPresent()).toBe(false);
  30176. element(by.tagName('button')).click();
  30177. expect(error.getText()).toBe('Error: Please select a value');
  30178. });
  30179. * </file>
  30180. *</example>
  30181. *
  30182. *
  30183. */
  30184. var SelectController =
  30185. ['$element', '$scope', /** @this */ function($element, $scope) {
  30186. var self = this,
  30187. optionsMap = new NgMap();
  30188. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  30189. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  30190. self.ngModelCtrl = noopNgModelController;
  30191. self.multiple = false;
  30192. // The "unknown" option is one that is prepended to the list if the viewValue
  30193. // does not match any of the options. When it is rendered the value of the unknown
  30194. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  30195. //
  30196. // Support: IE 9 only
  30197. // We can't just jqLite('<option>') since jqLite is not smart enough
  30198. // to create it in <select> and IE barfs otherwise.
  30199. self.unknownOption = jqLite(window.document.createElement('option'));
  30200. // The empty option is an option with the value '' that the application developer can
  30201. // provide inside the select. It is always selectable and indicates that a "null" selection has
  30202. // been made by the user.
  30203. // If the select has an empty option, and the model of the select is set to "undefined" or "null",
  30204. // the empty option is selected.
  30205. // If the model is set to a different unmatched value, the unknown option is rendered and
  30206. // selected, i.e both are present, because a "null" selection and an unknown value are different.
  30207. self.hasEmptyOption = false;
  30208. self.emptyOption = undefined;
  30209. self.renderUnknownOption = function(val) {
  30210. var unknownVal = self.generateUnknownOptionValue(val);
  30211. self.unknownOption.val(unknownVal);
  30212. $element.prepend(self.unknownOption);
  30213. setOptionSelectedStatus(self.unknownOption, true);
  30214. $element.val(unknownVal);
  30215. };
  30216. self.updateUnknownOption = function(val) {
  30217. var unknownVal = self.generateUnknownOptionValue(val);
  30218. self.unknownOption.val(unknownVal);
  30219. setOptionSelectedStatus(self.unknownOption, true);
  30220. $element.val(unknownVal);
  30221. };
  30222. self.generateUnknownOptionValue = function(val) {
  30223. return '? ' + hashKey(val) + ' ?';
  30224. };
  30225. self.removeUnknownOption = function() {
  30226. if (self.unknownOption.parent()) self.unknownOption.remove();
  30227. };
  30228. self.selectEmptyOption = function() {
  30229. if (self.emptyOption) {
  30230. $element.val('');
  30231. setOptionSelectedStatus(self.emptyOption, true);
  30232. }
  30233. };
  30234. self.unselectEmptyOption = function() {
  30235. if (self.hasEmptyOption) {
  30236. setOptionSelectedStatus(self.emptyOption, false);
  30237. }
  30238. };
  30239. $scope.$on('$destroy', function() {
  30240. // disable unknown option so that we don't do work when the whole select is being destroyed
  30241. self.renderUnknownOption = noop;
  30242. });
  30243. // Read the value of the select control, the implementation of this changes depending
  30244. // upon whether the select can have multiple values and whether ngOptions is at work.
  30245. self.readValue = function readSingleValue() {
  30246. var val = $element.val();
  30247. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  30248. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  30249. if (self.hasOption(realVal)) {
  30250. return realVal;
  30251. }
  30252. return null;
  30253. };
  30254. // Write the value to the select control, the implementation of this changes depending
  30255. // upon whether the select can have multiple values and whether ngOptions is at work.
  30256. self.writeValue = function writeSingleValue(value) {
  30257. // Make sure to remove the selected attribute from the previously selected option
  30258. // Otherwise, screen readers might get confused
  30259. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  30260. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  30261. if (self.hasOption(value)) {
  30262. self.removeUnknownOption();
  30263. var hashedVal = hashKey(value);
  30264. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  30265. // Set selected attribute and property on selected option for screen readers
  30266. var selectedOption = $element[0].options[$element[0].selectedIndex];
  30267. setOptionSelectedStatus(jqLite(selectedOption), true);
  30268. } else {
  30269. self.selectUnknownOrEmptyOption(value);
  30270. }
  30271. };
  30272. // Tell the select control that an option, with the given value, has been added
  30273. self.addOption = function(value, element) {
  30274. // Skip comment nodes, as they only pollute the `optionsMap`
  30275. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  30276. assertNotHasOwnProperty(value, '"option value"');
  30277. if (value === '') {
  30278. self.hasEmptyOption = true;
  30279. self.emptyOption = element;
  30280. }
  30281. var count = optionsMap.get(value) || 0;
  30282. optionsMap.set(value, count + 1);
  30283. // Only render at the end of a digest. This improves render performance when many options
  30284. // are added during a digest and ensures all relevant options are correctly marked as selected
  30285. scheduleRender();
  30286. };
  30287. // Tell the select control that an option, with the given value, has been removed
  30288. self.removeOption = function(value) {
  30289. var count = optionsMap.get(value);
  30290. if (count) {
  30291. if (count === 1) {
  30292. optionsMap.delete(value);
  30293. if (value === '') {
  30294. self.hasEmptyOption = false;
  30295. self.emptyOption = undefined;
  30296. }
  30297. } else {
  30298. optionsMap.set(value, count - 1);
  30299. }
  30300. }
  30301. };
  30302. // Check whether the select control has an option matching the given value
  30303. self.hasOption = function(value) {
  30304. return !!optionsMap.get(value);
  30305. };
  30306. /**
  30307. * @ngdoc method
  30308. * @name select.SelectController#$hasEmptyOption
  30309. *
  30310. * @description
  30311. *
  30312. * Returns `true` if the select element currently has an empty option
  30313. * element, i.e. an option that signifies that the select is empty / the selection is null.
  30314. *
  30315. */
  30316. self.$hasEmptyOption = function() {
  30317. return self.hasEmptyOption;
  30318. };
  30319. /**
  30320. * @ngdoc method
  30321. * @name select.SelectController#$isUnknownOptionSelected
  30322. *
  30323. * @description
  30324. *
  30325. * Returns `true` if the select element's unknown option is selected. The unknown option is added
  30326. * and automatically selected whenever the select model doesn't match any option.
  30327. *
  30328. */
  30329. self.$isUnknownOptionSelected = function() {
  30330. // Presence of the unknown option means it is selected
  30331. return $element[0].options[0] === self.unknownOption[0];
  30332. };
  30333. /**
  30334. * @ngdoc method
  30335. * @name select.SelectController#$isEmptyOptionSelected
  30336. *
  30337. * @description
  30338. *
  30339. * Returns `true` if the select element has an empty option and this empty option is currently
  30340. * selected. Returns `false` if the select element has no empty option or it is not selected.
  30341. *
  30342. */
  30343. self.$isEmptyOptionSelected = function() {
  30344. return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0];
  30345. };
  30346. self.selectUnknownOrEmptyOption = function(value) {
  30347. if (value == null && self.emptyOption) {
  30348. self.removeUnknownOption();
  30349. self.selectEmptyOption();
  30350. } else if (self.unknownOption.parent().length) {
  30351. self.updateUnknownOption(value);
  30352. } else {
  30353. self.renderUnknownOption(value);
  30354. }
  30355. };
  30356. var renderScheduled = false;
  30357. function scheduleRender() {
  30358. if (renderScheduled) return;
  30359. renderScheduled = true;
  30360. $scope.$$postDigest(function() {
  30361. renderScheduled = false;
  30362. self.ngModelCtrl.$render();
  30363. });
  30364. }
  30365. var updateScheduled = false;
  30366. function scheduleViewValueUpdate(renderAfter) {
  30367. if (updateScheduled) return;
  30368. updateScheduled = true;
  30369. $scope.$$postDigest(function() {
  30370. if ($scope.$$destroyed) return;
  30371. updateScheduled = false;
  30372. self.ngModelCtrl.$setViewValue(self.readValue());
  30373. if (renderAfter) self.ngModelCtrl.$render();
  30374. });
  30375. }
  30376. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  30377. if (optionAttrs.$attr.ngValue) {
  30378. // The value attribute is set by ngValue
  30379. var oldVal, hashedVal = NaN;
  30380. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  30381. var removal;
  30382. var previouslySelected = optionElement.prop('selected');
  30383. if (isDefined(hashedVal)) {
  30384. self.removeOption(oldVal);
  30385. delete self.selectValueMap[hashedVal];
  30386. removal = true;
  30387. }
  30388. hashedVal = hashKey(newVal);
  30389. oldVal = newVal;
  30390. self.selectValueMap[hashedVal] = newVal;
  30391. self.addOption(newVal, optionElement);
  30392. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  30393. // from firing a second time. Other $observers on value will also get the result of the
  30394. // ngValue expression, not the hashed value
  30395. optionElement.attr('value', hashedVal);
  30396. if (removal && previouslySelected) {
  30397. scheduleViewValueUpdate();
  30398. }
  30399. });
  30400. } else if (interpolateValueFn) {
  30401. // The value attribute is interpolated
  30402. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  30403. // This method is overwritten in ngOptions and has side-effects!
  30404. self.readValue();
  30405. var removal;
  30406. var previouslySelected = optionElement.prop('selected');
  30407. if (isDefined(oldVal)) {
  30408. self.removeOption(oldVal);
  30409. removal = true;
  30410. }
  30411. oldVal = newVal;
  30412. self.addOption(newVal, optionElement);
  30413. if (removal && previouslySelected) {
  30414. scheduleViewValueUpdate();
  30415. }
  30416. });
  30417. } else if (interpolateTextFn) {
  30418. // The text content is interpolated
  30419. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  30420. optionAttrs.$set('value', newVal);
  30421. var previouslySelected = optionElement.prop('selected');
  30422. if (oldVal !== newVal) {
  30423. self.removeOption(oldVal);
  30424. }
  30425. self.addOption(newVal, optionElement);
  30426. if (oldVal && previouslySelected) {
  30427. scheduleViewValueUpdate();
  30428. }
  30429. });
  30430. } else {
  30431. // The value attribute is static
  30432. self.addOption(optionAttrs.value, optionElement);
  30433. }
  30434. optionAttrs.$observe('disabled', function(newVal) {
  30435. // Since model updates will also select disabled options (like ngOptions),
  30436. // we only have to handle options becoming disabled, not enabled
  30437. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  30438. if (self.multiple) {
  30439. scheduleViewValueUpdate(true);
  30440. } else {
  30441. self.ngModelCtrl.$setViewValue(null);
  30442. self.ngModelCtrl.$render();
  30443. }
  30444. }
  30445. });
  30446. optionElement.on('$destroy', function() {
  30447. var currentValue = self.readValue();
  30448. var removeValue = optionAttrs.value;
  30449. self.removeOption(removeValue);
  30450. scheduleRender();
  30451. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  30452. currentValue === removeValue
  30453. ) {
  30454. // When multiple (selected) options are destroyed at the same time, we don't want
  30455. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  30456. scheduleViewValueUpdate(true);
  30457. }
  30458. });
  30459. };
  30460. }];
  30461. /**
  30462. * @ngdoc directive
  30463. * @name select
  30464. * @restrict E
  30465. *
  30466. * @description
  30467. * HTML `select` element with AngularJS data-binding.
  30468. *
  30469. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  30470. * between the scope and the `<select>` control (including setting default values).
  30471. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  30472. * {@link ngOptions `ngOptions`} directives.
  30473. *
  30474. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  30475. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  30476. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  30477. * Value and textContent can be interpolated.
  30478. *
  30479. * The {@link select.SelectController select controller} exposes utility functions that can be used
  30480. * to manipulate the select's behavior.
  30481. *
  30482. * ## Matching model and option values
  30483. *
  30484. * In general, the match between the model and an option is evaluated by strictly comparing the model
  30485. * value against the value of the available options.
  30486. *
  30487. * If you are setting the option value with the option's `value` attribute, or textContent, the
  30488. * value will always be a `string` which means that the model value must also be a string.
  30489. * Otherwise the `select` directive cannot match them correctly.
  30490. *
  30491. * To bind the model to a non-string value, you can use one of the following strategies:
  30492. * - the {@link ng.ngOptions `ngOptions`} directive
  30493. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  30494. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  30495. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  30496. * - model $parsers / $formatters to convert the string value
  30497. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  30498. *
  30499. * If the viewValue of `ngModel` does not match any of the options, then the control
  30500. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  30501. *
  30502. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  30503. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  30504. * option. See example below for demonstration.
  30505. *
  30506. * ## Choosing between `ngRepeat` and `ngOptions`
  30507. *
  30508. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  30509. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  30510. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  30511. * comprehension expression
  30512. * - reduced memory consumption by not creating a new scope for each repeated instance
  30513. * - increased render speed by creating the options in a documentFragment instead of individually
  30514. *
  30515. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  30516. * Chrome and Internet Explorer / Edge.
  30517. *
  30518. *
  30519. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  30520. * @param {string=} name Property name of the form under which the control is published.
  30521. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  30522. * bound to the model as an array.
  30523. * @param {string=} required Sets `required` validation error key if the value is not entered.
  30524. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  30525. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  30526. * when you want to data-bind to the required attribute.
  30527. * @param {string=} ngChange AngularJS expression to be executed when selected option(s) changes due to user
  30528. * interaction with the select element.
  30529. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  30530. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  30531. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  30532. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  30533. *
  30534. *
  30535. * @knownIssue
  30536. *
  30537. * In Firefox, the select model is only updated when the select element is blurred. For example,
  30538. * when switching between options with the keyboard, the select model is only set to the
  30539. * currently selected option when the select is blurred, e.g via tab key or clicking the mouse
  30540. * outside the select.
  30541. *
  30542. * This is due to an ambiguity in the select element specification. See the
  30543. * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379)
  30544. * for more information, and this
  30545. * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488)
  30546. *
  30547. * @example
  30548. * ### Simple `select` elements with static options
  30549. *
  30550. * <example name="static-select" module="staticSelect">
  30551. * <file name="index.html">
  30552. * <div ng-controller="ExampleController">
  30553. * <form name="myForm">
  30554. * <label for="singleSelect"> Single select: </label><br>
  30555. * <select name="singleSelect" ng-model="data.singleSelect">
  30556. * <option value="option-1">Option 1</option>
  30557. * <option value="option-2">Option 2</option>
  30558. * </select><br>
  30559. *
  30560. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  30561. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  30562. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  30563. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  30564. * <option value="option-2">Option 2</option>
  30565. * </select><br>
  30566. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  30567. * <tt>singleSelect = {{data.singleSelect}}</tt>
  30568. *
  30569. * <hr>
  30570. * <label for="multipleSelect"> Multiple select: </label><br>
  30571. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  30572. * <option value="option-1">Option 1</option>
  30573. * <option value="option-2">Option 2</option>
  30574. * <option value="option-3">Option 3</option>
  30575. * </select><br>
  30576. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  30577. * </form>
  30578. * </div>
  30579. * </file>
  30580. * <file name="app.js">
  30581. * angular.module('staticSelect', [])
  30582. * .controller('ExampleController', ['$scope', function($scope) {
  30583. * $scope.data = {
  30584. * singleSelect: null,
  30585. * multipleSelect: [],
  30586. * option1: 'option-1'
  30587. * };
  30588. *
  30589. * $scope.forceUnknownOption = function() {
  30590. * $scope.data.singleSelect = 'nonsense';
  30591. * };
  30592. * }]);
  30593. * </file>
  30594. *</example>
  30595. *
  30596. * @example
  30597. * ### Using `ngRepeat` to generate `select` options
  30598. * <example name="select-ngrepeat" module="ngrepeatSelect">
  30599. * <file name="index.html">
  30600. * <div ng-controller="ExampleController">
  30601. * <form name="myForm">
  30602. * <label for="repeatSelect"> Repeat select: </label>
  30603. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  30604. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  30605. * </select>
  30606. * </form>
  30607. * <hr>
  30608. * <tt>model = {{data.model}}</tt><br/>
  30609. * </div>
  30610. * </file>
  30611. * <file name="app.js">
  30612. * angular.module('ngrepeatSelect', [])
  30613. * .controller('ExampleController', ['$scope', function($scope) {
  30614. * $scope.data = {
  30615. * model: null,
  30616. * availableOptions: [
  30617. * {id: '1', name: 'Option A'},
  30618. * {id: '2', name: 'Option B'},
  30619. * {id: '3', name: 'Option C'}
  30620. * ]
  30621. * };
  30622. * }]);
  30623. * </file>
  30624. *</example>
  30625. *
  30626. * @example
  30627. * ### Using `ngValue` to bind the model to an array of objects
  30628. * <example name="select-ngvalue" module="ngvalueSelect">
  30629. * <file name="index.html">
  30630. * <div ng-controller="ExampleController">
  30631. * <form name="myForm">
  30632. * <label for="ngvalueselect"> ngvalue select: </label>
  30633. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  30634. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  30635. * </select>
  30636. * </form>
  30637. * <hr>
  30638. * <pre>model = {{data.model | json}}</pre><br/>
  30639. * </div>
  30640. * </file>
  30641. * <file name="app.js">
  30642. * angular.module('ngvalueSelect', [])
  30643. * .controller('ExampleController', ['$scope', function($scope) {
  30644. * $scope.data = {
  30645. * model: null,
  30646. * availableOptions: [
  30647. {value: 'myString', name: 'string'},
  30648. {value: 1, name: 'integer'},
  30649. {value: true, name: 'boolean'},
  30650. {value: null, name: 'null'},
  30651. {value: {prop: 'value'}, name: 'object'},
  30652. {value: ['a'], name: 'array'}
  30653. * ]
  30654. * };
  30655. * }]);
  30656. * </file>
  30657. *</example>
  30658. *
  30659. * @example
  30660. * ### Using `select` with `ngOptions` and setting a default value
  30661. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  30662. *
  30663. * <example name="select-with-default-values" module="defaultValueSelect">
  30664. * <file name="index.html">
  30665. * <div ng-controller="ExampleController">
  30666. * <form name="myForm">
  30667. * <label for="mySelect">Make a choice:</label>
  30668. * <select name="mySelect" id="mySelect"
  30669. * ng-options="option.name for option in data.availableOptions track by option.id"
  30670. * ng-model="data.selectedOption"></select>
  30671. * </form>
  30672. * <hr>
  30673. * <tt>option = {{data.selectedOption}}</tt><br/>
  30674. * </div>
  30675. * </file>
  30676. * <file name="app.js">
  30677. * angular.module('defaultValueSelect', [])
  30678. * .controller('ExampleController', ['$scope', function($scope) {
  30679. * $scope.data = {
  30680. * availableOptions: [
  30681. * {id: '1', name: 'Option A'},
  30682. * {id: '2', name: 'Option B'},
  30683. * {id: '3', name: 'Option C'}
  30684. * ],
  30685. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  30686. * };
  30687. * }]);
  30688. * </file>
  30689. *</example>
  30690. *
  30691. * @example
  30692. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  30693. *
  30694. * <example name="select-with-non-string-options" module="nonStringSelect">
  30695. * <file name="index.html">
  30696. * <select ng-model="model.id" convert-to-number>
  30697. * <option value="0">Zero</option>
  30698. * <option value="1">One</option>
  30699. * <option value="2">Two</option>
  30700. * </select>
  30701. * {{ model }}
  30702. * </file>
  30703. * <file name="app.js">
  30704. * angular.module('nonStringSelect', [])
  30705. * .run(function($rootScope) {
  30706. * $rootScope.model = { id: 2 };
  30707. * })
  30708. * .directive('convertToNumber', function() {
  30709. * return {
  30710. * require: 'ngModel',
  30711. * link: function(scope, element, attrs, ngModel) {
  30712. * ngModel.$parsers.push(function(val) {
  30713. * return parseInt(val, 10);
  30714. * });
  30715. * ngModel.$formatters.push(function(val) {
  30716. * return '' + val;
  30717. * });
  30718. * }
  30719. * };
  30720. * });
  30721. * </file>
  30722. * <file name="protractor.js" type="protractor">
  30723. * it('should initialize to model', function() {
  30724. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  30725. * });
  30726. * </file>
  30727. * </example>
  30728. *
  30729. */
  30730. var selectDirective = function() {
  30731. return {
  30732. restrict: 'E',
  30733. require: ['select', '?ngModel'],
  30734. controller: SelectController,
  30735. priority: 1,
  30736. link: {
  30737. pre: selectPreLink,
  30738. post: selectPostLink
  30739. }
  30740. };
  30741. function selectPreLink(scope, element, attr, ctrls) {
  30742. var selectCtrl = ctrls[0];
  30743. var ngModelCtrl = ctrls[1];
  30744. // if ngModel is not defined, we don't need to do anything but set the registerOption
  30745. // function to noop, so options don't get added internally
  30746. if (!ngModelCtrl) {
  30747. selectCtrl.registerOption = noop;
  30748. return;
  30749. }
  30750. selectCtrl.ngModelCtrl = ngModelCtrl;
  30751. // When the selected item(s) changes we delegate getting the value of the select control
  30752. // to the `readValue` method, which can be changed if the select can have multiple
  30753. // selected values or if the options are being generated by `ngOptions`
  30754. element.on('change', function() {
  30755. selectCtrl.removeUnknownOption();
  30756. scope.$apply(function() {
  30757. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  30758. });
  30759. });
  30760. // If the select allows multiple values then we need to modify how we read and write
  30761. // values from and to the control; also what it means for the value to be empty and
  30762. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  30763. // doesn't trigger rendering if only an item in the array changes.
  30764. if (attr.multiple) {
  30765. selectCtrl.multiple = true;
  30766. // Read value now needs to check each option to see if it is selected
  30767. selectCtrl.readValue = function readMultipleValue() {
  30768. var array = [];
  30769. forEach(element.find('option'), function(option) {
  30770. if (option.selected && !option.disabled) {
  30771. var val = option.value;
  30772. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  30773. }
  30774. });
  30775. return array;
  30776. };
  30777. // Write value now needs to set the selected property of each matching option
  30778. selectCtrl.writeValue = function writeMultipleValue(value) {
  30779. forEach(element.find('option'), function(option) {
  30780. var shouldBeSelected = !!value && (includes(value, option.value) ||
  30781. includes(value, selectCtrl.selectValueMap[option.value]));
  30782. var currentlySelected = option.selected;
  30783. // Support: IE 9-11 only, Edge 12-15+
  30784. // In IE and Edge adding options to the selection via shift+click/UP/DOWN
  30785. // will de-select already selected options if "selected" on those options was set
  30786. // more than once (i.e. when the options were already selected)
  30787. // So we only modify the selected property if necessary.
  30788. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  30789. // actual user interface.
  30790. if (shouldBeSelected !== currentlySelected) {
  30791. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  30792. }
  30793. });
  30794. };
  30795. // we have to do it on each watch since ngModel watches reference, but
  30796. // we need to work of an array, so we need to see if anything was inserted/removed
  30797. var lastView, lastViewRef = NaN;
  30798. scope.$watch(function selectMultipleWatch() {
  30799. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  30800. lastView = shallowCopy(ngModelCtrl.$viewValue);
  30801. ngModelCtrl.$render();
  30802. }
  30803. lastViewRef = ngModelCtrl.$viewValue;
  30804. });
  30805. // If we are a multiple select then value is now a collection
  30806. // so the meaning of $isEmpty changes
  30807. ngModelCtrl.$isEmpty = function(value) {
  30808. return !value || value.length === 0;
  30809. };
  30810. }
  30811. }
  30812. function selectPostLink(scope, element, attrs, ctrls) {
  30813. // if ngModel is not defined, we don't need to do anything
  30814. var ngModelCtrl = ctrls[1];
  30815. if (!ngModelCtrl) return;
  30816. var selectCtrl = ctrls[0];
  30817. // We delegate rendering to the `writeValue` method, which can be changed
  30818. // if the select can have multiple selected values or if the options are being
  30819. // generated by `ngOptions`.
  30820. // This must be done in the postLink fn to prevent $render to be called before
  30821. // all nodes have been linked correctly.
  30822. ngModelCtrl.$render = function() {
  30823. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  30824. };
  30825. }
  30826. };
  30827. // The option directive is purely designed to communicate the existence (or lack of)
  30828. // of dynamically created (and destroyed) option elements to their containing select
  30829. // directive via its controller.
  30830. var optionDirective = ['$interpolate', function($interpolate) {
  30831. return {
  30832. restrict: 'E',
  30833. priority: 100,
  30834. compile: function(element, attr) {
  30835. var interpolateValueFn, interpolateTextFn;
  30836. if (isDefined(attr.ngValue)) {
  30837. // Will be handled by registerOption
  30838. } else if (isDefined(attr.value)) {
  30839. // If the value attribute is defined, check if it contains an interpolation
  30840. interpolateValueFn = $interpolate(attr.value, true);
  30841. } else {
  30842. // If the value attribute is not defined then we fall back to the
  30843. // text content of the option element, which may be interpolated
  30844. interpolateTextFn = $interpolate(element.text(), true);
  30845. if (!interpolateTextFn) {
  30846. attr.$set('value', element.text());
  30847. }
  30848. }
  30849. return function(scope, element, attr) {
  30850. // This is an optimization over using ^^ since we don't want to have to search
  30851. // all the way to the root of the DOM for every single option element
  30852. var selectCtrlName = '$selectController',
  30853. parent = element.parent(),
  30854. selectCtrl = parent.data(selectCtrlName) ||
  30855. parent.parent().data(selectCtrlName); // in case we are in optgroup
  30856. if (selectCtrl) {
  30857. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  30858. }
  30859. };
  30860. }
  30861. };
  30862. }];
  30863. /**
  30864. * @ngdoc directive
  30865. * @name ngRequired
  30866. * @restrict A
  30867. *
  30868. * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the
  30869. * `required` attribute to the element and adds the `required`
  30870. * {@link ngModel.NgModelController#$validators `validator`}.
  30871. *
  30872. * @description
  30873. *
  30874. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30875. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  30876. * applied to custom controls.
  30877. *
  30878. * The directive sets the `required` attribute on the element if the AngularJS expression inside
  30879. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  30880. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  30881. * for more info.
  30882. *
  30883. * The validator will set the `required` error key to true if the `required` attribute is set and
  30884. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  30885. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  30886. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  30887. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  30888. *
  30889. * @example
  30890. * <example name="ngRequiredDirective" module="ngRequiredExample">
  30891. * <file name="index.html">
  30892. * <script>
  30893. * angular.module('ngRequiredExample', [])
  30894. * .controller('ExampleController', ['$scope', function($scope) {
  30895. * $scope.required = true;
  30896. * }]);
  30897. * </script>
  30898. * <div ng-controller="ExampleController">
  30899. * <form name="form">
  30900. * <label for="required">Toggle required: </label>
  30901. * <input type="checkbox" ng-model="required" id="required" />
  30902. * <br>
  30903. * <label for="input">This input must be filled if `required` is true: </label>
  30904. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  30905. * <hr>
  30906. * required error set? = <code>{{form.input.$error.required}}</code><br>
  30907. * model = <code>{{model}}</code>
  30908. * </form>
  30909. * </div>
  30910. * </file>
  30911. * <file name="protractor.js" type="protractor">
  30912. var required = element(by.binding('form.input.$error.required'));
  30913. var model = element(by.binding('model'));
  30914. var input = element(by.id('input'));
  30915. it('should set the required error', function() {
  30916. expect(required.getText()).toContain('true');
  30917. input.sendKeys('123');
  30918. expect(required.getText()).not.toContain('true');
  30919. expect(model.getText()).toContain('123');
  30920. });
  30921. * </file>
  30922. * </example>
  30923. */
  30924. var requiredDirective = function() {
  30925. return {
  30926. restrict: 'A',
  30927. require: '?ngModel',
  30928. link: function(scope, elm, attr, ctrl) {
  30929. if (!ctrl) return;
  30930. attr.required = true; // force truthy in case we are on non input element
  30931. ctrl.$validators.required = function(modelValue, viewValue) {
  30932. return !attr.required || !ctrl.$isEmpty(viewValue);
  30933. };
  30934. attr.$observe('required', function() {
  30935. ctrl.$validate();
  30936. });
  30937. }
  30938. };
  30939. };
  30940. /**
  30941. * @ngdoc directive
  30942. * @name ngPattern
  30943. * @restrict A
  30944. *
  30945. * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String`
  30946. * parsable into a `RegExp`, or a `RegExp` literal. See above for
  30947. * more details.
  30948. *
  30949. * @description
  30950. *
  30951. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30952. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30953. *
  30954. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30955. * does not match a RegExp which is obtained from the `ngPattern` attribute value:
  30956. * - the value is an AngularJS expression:
  30957. * - If the expression evaluates to a RegExp object, then this is used directly.
  30958. * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  30959. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  30960. * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly.
  30961. *
  30962. * <div class="alert alert-info">
  30963. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  30964. * start at the index of the last search's match, thus not taking the whole input value into
  30965. * account.
  30966. * </div>
  30967. *
  30968. * <div class="alert alert-info">
  30969. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  30970. * differences:
  30971. * <ol>
  30972. * <li>
  30973. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  30974. * not available.
  30975. * </li>
  30976. * <li>
  30977. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  30978. * interpolated.
  30979. * </li>
  30980. * </ol>
  30981. * </div>
  30982. *
  30983. * @example
  30984. * <example name="ngPatternDirective" module="ngPatternExample">
  30985. * <file name="index.html">
  30986. * <script>
  30987. * angular.module('ngPatternExample', [])
  30988. * .controller('ExampleController', ['$scope', function($scope) {
  30989. * $scope.regex = '\\d+';
  30990. * }]);
  30991. * </script>
  30992. * <div ng-controller="ExampleController">
  30993. * <form name="form">
  30994. * <label for="regex">Set a pattern (regex string): </label>
  30995. * <input type="text" ng-model="regex" id="regex" />
  30996. * <br>
  30997. * <label for="input">This input is restricted by the current pattern: </label>
  30998. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  30999. * <hr>
  31000. * input valid? = <code>{{form.input.$valid}}</code><br>
  31001. * model = <code>{{model}}</code>
  31002. * </form>
  31003. * </div>
  31004. * </file>
  31005. * <file name="protractor.js" type="protractor">
  31006. var model = element(by.binding('model'));
  31007. var input = element(by.id('input'));
  31008. it('should validate the input with the default pattern', function() {
  31009. input.sendKeys('aaa');
  31010. expect(model.getText()).not.toContain('aaa');
  31011. input.clear().then(function() {
  31012. input.sendKeys('123');
  31013. expect(model.getText()).toContain('123');
  31014. });
  31015. });
  31016. * </file>
  31017. * </example>
  31018. */
  31019. var patternDirective = function() {
  31020. return {
  31021. restrict: 'A',
  31022. require: '?ngModel',
  31023. link: function(scope, elm, attr, ctrl) {
  31024. if (!ctrl) return;
  31025. var regexp, patternExp = attr.ngPattern || attr.pattern;
  31026. attr.$observe('pattern', function(regex) {
  31027. if (isString(regex) && regex.length > 0) {
  31028. regex = new RegExp('^' + regex + '$');
  31029. }
  31030. if (regex && !regex.test) {
  31031. throw minErr('ngPattern')('noregexp',
  31032. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  31033. regex, startingTag(elm));
  31034. }
  31035. regexp = regex || undefined;
  31036. ctrl.$validate();
  31037. });
  31038. ctrl.$validators.pattern = function(modelValue, viewValue) {
  31039. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  31040. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  31041. };
  31042. }
  31043. };
  31044. };
  31045. /**
  31046. * @ngdoc directive
  31047. * @name ngMaxlength
  31048. * @restrict A
  31049. *
  31050. * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String`
  31051. * parsable into a `Number`. Used as value for the `maxlength`
  31052. * {@link ngModel.NgModelController#$validators validator}.
  31053. *
  31054. * @description
  31055. *
  31056. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  31057. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  31058. *
  31059. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  31060. * is longer than the integer obtained by evaluating the AngularJS expression given in the
  31061. * `ngMaxlength` attribute value.
  31062. *
  31063. * <div class="alert alert-info">
  31064. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  31065. * differences:
  31066. * <ol>
  31067. * <li>
  31068. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  31069. * validation is not available.
  31070. * </li>
  31071. * <li>
  31072. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  31073. * interpolated.
  31074. * </li>
  31075. * </ol>
  31076. * </div>
  31077. *
  31078. * @example
  31079. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  31080. * <file name="index.html">
  31081. * <script>
  31082. * angular.module('ngMaxlengthExample', [])
  31083. * .controller('ExampleController', ['$scope', function($scope) {
  31084. * $scope.maxlength = 5;
  31085. * }]);
  31086. * </script>
  31087. * <div ng-controller="ExampleController">
  31088. * <form name="form">
  31089. * <label for="maxlength">Set a maxlength: </label>
  31090. * <input type="number" ng-model="maxlength" id="maxlength" />
  31091. * <br>
  31092. * <label for="input">This input is restricted by the current maxlength: </label>
  31093. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  31094. * <hr>
  31095. * input valid? = <code>{{form.input.$valid}}</code><br>
  31096. * model = <code>{{model}}</code>
  31097. * </form>
  31098. * </div>
  31099. * </file>
  31100. * <file name="protractor.js" type="protractor">
  31101. var model = element(by.binding('model'));
  31102. var input = element(by.id('input'));
  31103. it('should validate the input with the default maxlength', function() {
  31104. input.sendKeys('abcdef');
  31105. expect(model.getText()).not.toContain('abcdef');
  31106. input.clear().then(function() {
  31107. input.sendKeys('abcde');
  31108. expect(model.getText()).toContain('abcde');
  31109. });
  31110. });
  31111. * </file>
  31112. * </example>
  31113. */
  31114. var maxlengthDirective = function() {
  31115. return {
  31116. restrict: 'A',
  31117. require: '?ngModel',
  31118. link: function(scope, elm, attr, ctrl) {
  31119. if (!ctrl) return;
  31120. var maxlength = -1;
  31121. attr.$observe('maxlength', function(value) {
  31122. var intVal = toInt(value);
  31123. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  31124. ctrl.$validate();
  31125. });
  31126. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  31127. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  31128. };
  31129. }
  31130. };
  31131. };
  31132. /**
  31133. * @ngdoc directive
  31134. * @name ngMinlength
  31135. * @restrict A
  31136. *
  31137. * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String`
  31138. * parsable into a `Number`. Used as value for the `minlength`
  31139. * {@link ngModel.NgModelController#$validators validator}.
  31140. *
  31141. * @description
  31142. *
  31143. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  31144. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  31145. *
  31146. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  31147. * is shorter than the integer obtained by evaluating the AngularJS expression given in the
  31148. * `ngMinlength` attribute value.
  31149. *
  31150. * <div class="alert alert-info">
  31151. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  31152. * differences:
  31153. * <ol>
  31154. * <li>
  31155. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  31156. * validation is not available.
  31157. * </li>
  31158. * <li>
  31159. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  31160. * interpolated.
  31161. * </li>
  31162. * </ol>
  31163. * </div>
  31164. *
  31165. * @example
  31166. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  31167. * <file name="index.html">
  31168. * <script>
  31169. * angular.module('ngMinlengthExample', [])
  31170. * .controller('ExampleController', ['$scope', function($scope) {
  31171. * $scope.minlength = 3;
  31172. * }]);
  31173. * </script>
  31174. * <div ng-controller="ExampleController">
  31175. * <form name="form">
  31176. * <label for="minlength">Set a minlength: </label>
  31177. * <input type="number" ng-model="minlength" id="minlength" />
  31178. * <br>
  31179. * <label for="input">This input is restricted by the current minlength: </label>
  31180. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  31181. * <hr>
  31182. * input valid? = <code>{{form.input.$valid}}</code><br>
  31183. * model = <code>{{model}}</code>
  31184. * </form>
  31185. * </div>
  31186. * </file>
  31187. * <file name="protractor.js" type="protractor">
  31188. var model = element(by.binding('model'));
  31189. var input = element(by.id('input'));
  31190. it('should validate the input with the default minlength', function() {
  31191. input.sendKeys('ab');
  31192. expect(model.getText()).not.toContain('ab');
  31193. input.sendKeys('abc');
  31194. expect(model.getText()).toContain('abc');
  31195. });
  31196. * </file>
  31197. * </example>
  31198. */
  31199. var minlengthDirective = function() {
  31200. return {
  31201. restrict: 'A',
  31202. require: '?ngModel',
  31203. link: function(scope, elm, attr, ctrl) {
  31204. if (!ctrl) return;
  31205. var minlength = 0;
  31206. attr.$observe('minlength', function(value) {
  31207. minlength = toInt(value) || 0;
  31208. ctrl.$validate();
  31209. });
  31210. ctrl.$validators.minlength = function(modelValue, viewValue) {
  31211. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  31212. };
  31213. }
  31214. };
  31215. };
  31216. if (window.angular.bootstrap) {
  31217. // AngularJS is already loaded, so we can return here...
  31218. if (window.console) {
  31219. console.log('WARNING: Tried to load AngularJS more than once.');
  31220. }
  31221. return;
  31222. }
  31223. // try to bind to jquery now so that one can write jqLite(fn)
  31224. // but we will rebind on bootstrap again.
  31225. bindJQuery();
  31226. publishExternalAPI(angular);
  31227. angular.module("ngLocale", [], ["$provide", function($provide) {
  31228. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  31229. function getDecimals(n) {
  31230. n = n + '';
  31231. var i = n.indexOf('.');
  31232. return (i == -1) ? 0 : n.length - i - 1;
  31233. }
  31234. function getVF(n, opt_precision) {
  31235. var v = opt_precision;
  31236. if (undefined === v) {
  31237. v = Math.min(getDecimals(n), 3);
  31238. }
  31239. var base = Math.pow(10, v);
  31240. var f = ((n * base) | 0) % base;
  31241. return {v: v, f: f};
  31242. }
  31243. $provide.value("$locale", {
  31244. "DATETIME_FORMATS": {
  31245. "AMPMS": [
  31246. "AM",
  31247. "PM"
  31248. ],
  31249. "DAY": [
  31250. "Sunday",
  31251. "Monday",
  31252. "Tuesday",
  31253. "Wednesday",
  31254. "Thursday",
  31255. "Friday",
  31256. "Saturday"
  31257. ],
  31258. "ERANAMES": [
  31259. "Before Christ",
  31260. "Anno Domini"
  31261. ],
  31262. "ERAS": [
  31263. "BC",
  31264. "AD"
  31265. ],
  31266. "FIRSTDAYOFWEEK": 6,
  31267. "MONTH": [
  31268. "January",
  31269. "February",
  31270. "March",
  31271. "April",
  31272. "May",
  31273. "June",
  31274. "July",
  31275. "August",
  31276. "September",
  31277. "October",
  31278. "November",
  31279. "December"
  31280. ],
  31281. "SHORTDAY": [
  31282. "Sun",
  31283. "Mon",
  31284. "Tue",
  31285. "Wed",
  31286. "Thu",
  31287. "Fri",
  31288. "Sat"
  31289. ],
  31290. "SHORTMONTH": [
  31291. "Jan",
  31292. "Feb",
  31293. "Mar",
  31294. "Apr",
  31295. "May",
  31296. "Jun",
  31297. "Jul",
  31298. "Aug",
  31299. "Sep",
  31300. "Oct",
  31301. "Nov",
  31302. "Dec"
  31303. ],
  31304. "STANDALONEMONTH": [
  31305. "January",
  31306. "February",
  31307. "March",
  31308. "April",
  31309. "May",
  31310. "June",
  31311. "July",
  31312. "August",
  31313. "September",
  31314. "October",
  31315. "November",
  31316. "December"
  31317. ],
  31318. "WEEKENDRANGE": [
  31319. 5,
  31320. 6
  31321. ],
  31322. "fullDate": "EEEE, MMMM d, y",
  31323. "longDate": "MMMM d, y",
  31324. "medium": "MMM d, y h:mm:ss a",
  31325. "mediumDate": "MMM d, y",
  31326. "mediumTime": "h:mm:ss a",
  31327. "short": "M/d/yy h:mm a",
  31328. "shortDate": "M/d/yy",
  31329. "shortTime": "h:mm a"
  31330. },
  31331. "NUMBER_FORMATS": {
  31332. "CURRENCY_SYM": "$",
  31333. "DECIMAL_SEP": ".",
  31334. "GROUP_SEP": ",",
  31335. "PATTERNS": [
  31336. {
  31337. "gSize": 3,
  31338. "lgSize": 3,
  31339. "maxFrac": 3,
  31340. "minFrac": 0,
  31341. "minInt": 1,
  31342. "negPre": "-",
  31343. "negSuf": "",
  31344. "posPre": "",
  31345. "posSuf": ""
  31346. },
  31347. {
  31348. "gSize": 3,
  31349. "lgSize": 3,
  31350. "maxFrac": 2,
  31351. "minFrac": 2,
  31352. "minInt": 1,
  31353. "negPre": "-\u00a4",
  31354. "negSuf": "",
  31355. "posPre": "\u00a4",
  31356. "posSuf": ""
  31357. }
  31358. ]
  31359. },
  31360. "id": "en-us",
  31361. "localeID": "en_US",
  31362. "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;}
  31363. });
  31364. }]);
  31365. jqLite(function() {
  31366. angularInit(window.document, bootstrap);
  31367. });
  31368. })(window);
  31369. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');